An Introduction to Dragon/Printable version


An Introduction to Dragon

The current, editable version of this book is available in Wikibooks, the open-content textbooks collection, at
https://en.wikibooks.org/wiki/An_Introduction_to_Dragon

Permission is granted to copy, distribute, and/or modify this document under the terms of the Creative Commons Attribution-ShareAlike 3.0 License.

Lessons/Introduction

Introduction edit

Welcome to the Dragon programming language!

In this chapter we are going to discuss the goals behind the language design and implementation.


Lessons/History

History edit

In Oct. 2016 I started the design and the implementation of the Dragon programming language. After 15 months of development, in Jan 2018 the language Interpreter and environment were ready for use!

The first version of the language Dragon 1.0 was released on January 4th, 2018.



Lessons/Features

Features edit

The Dragon language comes with the following features:

  • Interpreted
  • Declarative programming on top of object-oriented programming
  • No explicit end for statements (No ; or ENTER is required)
  • Portable (Windows, Linux, Mac OS X, Android, etc.)
  • Comments (one line, inline, & multi-line)
  • Dynamic typing
  • Weakly typed
  • Garbage collector - automatic memory management (escape analysis and reference counting)
  • Structure-oriented programming
  • Rich control structures & operators
  • Procedures/functions
  • No main function
  • Call function before the definition
  • Recursion
  • Multi-line literals
  • Reflection and metaprogramming
  • Clear program structure (statements, then functions)
  • Exception handling
  • I/O commands
  • Math functions
  • String functions
  • Standard functions
  • File processing functions
  • Database support
  • Create GUI applications for desktop



Lessons/Variables

Variables edit

To create a new variable, you just need to determine the variable name & value. The value will determine the variable type and you can change the value to switch between the types using the same variable name.

Syntax:

	<Variable Name> = <Value>

.. tip::

The operator '=' is used here as an assignment operator and the same operator can be used in conditions, but for testing equality of expressions.

.. note::

The variable will contain the real value (not a reference). This means that once you change the variable value, the old value will be removed from memory (even if the variable contains a list or object).

Dynamic Typing edit

Dragon uses dynamic typing:

	x = "Hello"		// x is a string
	showln x  		// print list items
	x = 5			// x is a number (int)
	showln x 
	x = 1.2 		// x is a number (double)
	showln x 
	x = [1,2,3,4]	// x is a list
	showln x

Deep Copy edit

We can use the assignment operator '=' to copy variables. We can do that to copy values like strings & numbers, and even complete lists & objects! The assignment operator will do a complete duplication for us. This operation is called a deep copy.

	list = [1,2,3,"four","five"]
	list2 = list
	list = []
	show list	// print the first list - no items to print
	showln "********" 
	show list2	// print the second list - contains 5 items

Weakly Typed edit

Dragon is a weakly typed language. This means that the language can automatically convert between data types (like string & numbers) when that conversion makes sense.



Lessons/Operators

Operators edit

In this chapter we will introduce the operators provided by the Dragon programming language.

Arithmetic Operators edit

The next table presents all of the arithmetic operators provided by the Dragon language. Assume variable x = 50 and variable y = 10, then:

+------------+---------------+----------+---------+
| Operator   | Description   | Example  | Result  |
+============+===============+==========+=========+
| +          |  Add          |  x+y     |  60     |
+------------+---------------+----------+---------+
| -          |	Subtract     |	x-y     |  40     |
+------------+---------------+----------+---------+
| *          |  Multiply     |	x*y     |  500    |
+------------+---------------+----------+---------+
| /          |  Divide	     |	x/y     |  5      |
+------------+---------------+----------+---------+
| %          |  Modulus	     |	x%y     |  0      | 
+------------+---------------+----------+---------+
| ++         |  Increment    |	x++     |  51     |
+------------+---------------+----------+---------+
| --         |  Decrement    |	x--     |  49     |
+------------+---------------+----------+---------+

Relational Operators edit

The next table presents all of the relational operators provided by the Dragon language. Assume variable x = 50 and variable y = 10, then:

+------------+---------------------+-------------+---------+
| Operator   | Description         | Example     | Result  |
+============+=====================+=============+=========+
| ==         |  Equal	           |    x == y   |  False  |
+------------+---------------------+-------------+---------+
| !=         |	Not Equal          |	x != y   |  True   |
+------------+---------------------+-------------+---------+
| >          |  Greater than       |	x > y    |  True   |
+------------+---------------------+-------------+---------+
| <          |  Less than          |	x < y    |  False  |
+------------+---------------------+-------------+---------+
| >=         |  Greater or Equal   |	x >= y   |  True   | 
+------------+---------------------+-------------+---------+
| <=         |  Less than or Equal |	x <= y   |  False  |
+------------+---------------------+-------------+---------+

Logical Operators edit

The next table presents all of the logical operators provided by the Dragon language. Assume variable x = true and variable y = false, then:

+------------+---------------------+-------------+---------+
| Operator   | Description         | Example     | Result  |
+============+=====================+=============+=========+
| &&	     |  Logical AND        |    x && y   |  false  |
+------------+---------------------+-------------+---------+
| ||         |	Logical OR         |	x || y   |  true   |
+------------+---------------------+-------------+---------+
| !	         |  Logical Not        |	!x       |  false  |
+------------+---------------------+-------------+---------+

Bitwise Operators edit

The next table presents all of the bitwise operators provided by the Dragon language. Assume variable x = 8 and variable y = 2, then:

+------------+-----------------------------+-------------+---------+
| Operator   | Description                 | Example     | Result  |
+============+=============================+=============+=========+
| &          |  Binary AND                 |    x & y    |  0      |
+------------+-----------------------------+-------------+---------+
| |          |	Binary OR                  |	x | y    |  10     |
+------------+-----------------------------+-------------+---------+
| ^          |  Binary XOR                 |	x ^ y    |  10     |
+------------+-----------------------------+-------------+---------+
| ~          |  Binary Ones Complement 	   |	~x       |  -9     |
+------------+-----------------------------+-------------+---------+
| <<         |  Binary Left Shift          |	x << y   |  32     | 
+------------+-----------------------------+-------------+---------+
| >>         |  Binary Right Shift         |	x >> y   |  2      |
+------------+-----------------------------+-------------+---------+

Assignment Operators edit

The next table presents all of the assignment operators provided by the Dragon language.

Assume variable x = 8, then:

+------------+-----------------------------+-------------+---------+
| Operator   | Description                 | Example     | Result  |
+============+=============================+=============+=========+
| =          |  Assignment                 |    x = 8    |  x=8    |
+------------+-----------------------------+-------------+---------+
| +=         |	Add AND assignment         |	x += 5   |  x=13   |
+------------+-----------------------------+-------------+---------+
| -=	     |  Subtract AND assignment    |	x -= 3   |  x=10   |
+------------+-----------------------------+-------------+---------+
| *=         |  Multiply AND assignment    |	x *= 2   |  x=20   |
+------------+-----------------------------+-------------+---------+
| /=         |  Divide AND assignment      |	x /= 3   |  x=6    |
+------------+-----------------------------+-------------+---------+
| %=         |  Modulus AND assignment     |	x %= 2   |  x=0    | 
+------------+-----------------------------+-------------+---------+
| <<=        |	Left shift AND assignment  |	x <<= 2  |  x=0    |
+------------+-----------------------------+-------------+---------+
| >>=	     |  Right shift AND assignment |	x >>= 2  |  x=0    |
+------------+-----------------------------+-------------+---------+
| &=         |  Bitwise AND assignment     |	x &= 4   |  x=0    |
+------------+-----------------------------+-------------+---------+
| |=         |  Bitwise OR and assignment  |	x |= 3   |  x=3    |
+------------+-----------------------------+-------------+---------+
| ^=         |  Bitwise XOR and assignment |	x ^= 4   |  x=7    |
+------------+-----------------------------+-------------+---------+

Misc Operators edit

==============	======================================================================
Operator        Description
==============	======================================================================
Start:End       create list contains items from start to end
[list items]    define list items
list[index]     access list item
==============	======================================================================

Operator Precedence edit

The next table presents operators from highest precedence (evaluated first) to lowest precedence.

+----------------------------------------------------------------+
| Operator                                                       |
+================================================================+
| .  []   ()     {}                                              |
+----------------------------------------------------------------+
| -  ~  :Literal  [list items]                                   |
+----------------------------------------------------------------+
| ++   --                                                        |
+----------------------------------------------------------------+
| Start:End                                                      |
+----------------------------------------------------------------+
| * /  %                                                         |
+----------------------------------------------------------------+
| + -                                                            |
+----------------------------------------------------------------+
| <<   >>                                                        |
+----------------------------------------------------------------+
| &                                                              |
+----------------------------------------------------------------+
| \|  ^	                                                         |
+----------------------------------------------------------------+
| <  >  <=  >=                                                   |
+----------------------------------------------------------------+
| =  !=                                                          |
+----------------------------------------------------------------+
| not                                                            |
+----------------------------------------------------------------+
| and   or                                                       |
+----------------------------------------------------------------+
| Assignment = += -= \*= /= %= >>= <<= &= ^= \|=                 |
+----------------------------------------------------------------+

Example:

	show 3+5*4	// prints 23



Lessons/Control Structures

Control Structures edit

In this chapter we are going to learn about the control structures provided by the Dragon programming language.

Branching edit

  • If Statement

Syntax:

	if(Expression)
	{
		Block of statements
	}
	else if(Expression)
	{
		Block of statements
	}
	else {
		Block of statements
	}

Example:

	select "types"
	select "graphic"
	nOption = int(prompt("1) Say Hello \n2) About")
	
	if nOption == 1	
	{
		name = prompt("Enter your name: ")
		showln "Hello " + name 
	}
	else if nOption == 2 
	{      
		showln "Sample : using if statement" 
	}
	else
	{ 
		showln "bad option..."
	}

Looping edit

  • While Loop

Syntax:

	while(Expression)
	{
		Block of statements
	}


  • For Loop

Syntax:

	for (identifier=initialize value, terminating expression, step expression)
	{
		Block of statements
	}

Example:

	// print numbers from 1 to 10
	for (x = 1, x <= 10, x++)
	{
		showln x  
	}


  • Foreach Loop

Syntax:

	for (identifier : List/String)
	{
		Block of statements
	}

Example:

	aList = [1,2,3,4]  //create list contains numbers from 1 to 10
	for x : aList
	{
		showln x       // print numbers from 1 to 10
	}

Do While Loop edit

Syntax:

	do {
		body
	} while (condition)

Example:

	x = 1 
	do {
		showln x 
		x++ 
	}
	while (x <= 10)



Lessons/Getting Input

Getting Input edit

We can get input from the keyboard using the readln function.

readln function edit

Syntax:

	select "std"

	a = readln()

Example:

	select "std"
	select "types"
	
    showln "Enter the first number :"
	a = int(readln())
    showln "Enter the second number :"
	b = int(readln())
	
	showln "Sum is : " + (a + b)

Output:

	Enter the first number : 3
	Enter the second number : 4
	Sum is : 7



Lessons/Functions

Functions edit

In this chapter we are going to learn about the next topics :-

  • Define functions
  • Call functions
  • Declare parameters
  • Send parameters
  • Variables Scope
  • Return Value

Define Functions edit

To define a new function:

Syntax:

	func <function_name> (parameters)
	{
		Block of statements
	}


Example:

	func hello()
	{
		showln "Hello from function"
	}

Call Functions edit

Tip: We can call the function before the function definition.

Example:

	hello()

	func hello()
	{
		showln "Hello from function"
	}


Example:

	first()  second()

	func first() {
		showln "message from the first function" 
	}

	func second() {
		showln "message from the second function" 
	}

Declare parameters edit

To declare the function parameters, write them in parentheses.

Example:

	func sum(x, y)
	{
		showln x + y
	}

Send Parameters edit

To send parameters to function, type the parameters inside () after the function name

Syntax:

	name(parameters)

Example:

	/* output
	** 8
	** 3000
	*/

	sum(3, 5) sum(1000, 2000)

	func sum(x, y)
	{
		showln x + y
	}

Variables Scope edit

The Dragon programming language uses lexical scoping to determine the scope of a variable.

Variables defined inside functions (including function parameters) are local variables. Variables defined outside functions (before any function) are global variables.

Inside any function we can access the variables defined inside this function beside the global variables.

Example:

	// the program will print numbers from 10 to 1
	
	x = 10                    // x is a global variable.
	
	for(t = 1, t < 11, t++)   // t is a local variable
		mycounter()           // call function

	func mycounter() {
		showln x              // print the global variable value
		x--                   //decrement
	}

Return Value edit

The function can return a value using the return command.

Syntax:

	return <expression>


Example:

	showln my(30, 40)      // prints 70
	
	func my(a, b)
	{ 
		return a + b
	}