User Tools

Site Tools


at:tutorial:basic

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
Next revisionBoth sides next revision
at:tutorial:basic [2007/04/06 11:35] – * elisagat:tutorial:basic [2007/04/17 17:10] tvcutsem
Line 1: Line 1:
 <note> <note>
-**This Tutorial is still under heavy construction**+**This Tutorial is still under heavy construction!!**
 </note> </note>
 ====== Functional and Imperative Programming ====== ====== Functional and Imperative Programming ======
    
-This part of the tutorial shows AmbientTalk as a simple expression language with a minimum syntax which resembles very on Java script. This section mainly describes the basic features of the language, namely variables, functions and tables and control flow.+This part of the tutorial explains AmbientTalk as a simple expression language with a flexible syntax which resembles languages like Ruby, Python and Javascript. This section mainly describes the basic features of the language, namely variables, functionstables (i.e. arrays) and control flow primitives.
  
 ===== Variables ===== ===== Variables =====
    
-As usual, one can define, assign and refer to a variable. Variable definitions are made with the keyword **def**. Note that AmbientTalk is a dynamically typed language sovariables do not have a type but, they just contain values.+As usual, one can define, assign and refer to a variable. Variable definitions are made with the keyword **def**. Note that AmbientTalk is a dynamically typed languageso variables do not have a type but can contain any value.
  
-In the examples we use the interactive AmbientTalk shell (iat) where the input and output prompt are represented by > and >> respectively. +In the examples we use the interactive AmbientTalk shell (iat) where the input and output prompt are represented by > and %%>>%% respectively. 
  
 <code> <code>
Line 19: Line 19:
 </code> </code>
  
-Variable definitions can be combined with assignments as shown aboveAs in Pico, assignments uses the ":=operator. Note that there must be an space between the variable and the ":=" operator in order for the parse to resolve the ambiguity between a keyword message and a assignment, e.g. ":= 1" is understood as an assignment while "a:" as a keyword. We will further elaborate on keywords in the following sections.+Variable definitions can include an initialization expression that immediately initializes the variableVariable assignment is performed by means of the well-known '':='' operator (''='' is used for mathematical comparison)AmbientTalk supports assignment to multiple variables as a single assignment expression. For this to work, the number of variable names on the left hand side of ":=" must match the number of expressions on the right hand side of ":=". A typical application of this is to swap the values of two variables more easily:
  
-An assignment consists of one or more expressions, providing that the number of expressions on the right hand side match the number of variables on the left hand side. This allows a permutation of variables such as: 
 <code> <code>
 >[x, y] := [ y, x ] >[x, y] := [ y, x ]
 >>[7,5] >>[7,5]
 </code> </code>
 +
 +As we will explain later, the ''[y,x]'' syntax simply denotes a literal table (a.k.a. an array).
  
 The variable name is used to refer a variable. The variable is evaluated when referenced.  The variable name is used to refer a variable. The variable is evaluated when referenced. 
Line 32: Line 33:
 >>7 >>7
 </code> </code>
 +
 +<note>
 +When using the '':='' assignment operator, beware of the following syntactic annoyance: the expression ''a := 1'' denotes an assignment to the variable ''a'', while ''a:= 1'' is misunderstood by the parser as ''a: = 1'', which is the invocation of a keyworded message named ''a:''. Keyworded message sends will be explained later on in this chapter. Hence, as a general rule, don't forget to always put a space between the variable name and the '':='' operator.
 +</note>
  
 ===== Tables ===== ===== Tables =====
  
-Indexed tables represent what other languages call arrays or listsTables are unidimensional and their indexes range from 1 to the size of the tableAs variables, one can define, assign and refer to a table. Table definition is also made  with the keyword **def** in the following form:+The //table// is AmbientTalk's native compound data type. It is akin to what other languages call //arrays//The main difference is that tables are indexed from ''1'' up to their ''length'', while arrays are indexed from ''0'' up to ''length-1''Like with variables, one can define, assign and refer to a table. Table definitions are also formed with the keyword **def** in the following format:
 <code> <code>
-def t[ <size> ] { <expression> }+def t[ <sizeexpression> ] { <initexpression> }
 </code> </code>
-This means that the <expressionwill be evaluated <sizetimes, i.e., one for each slot of the table. This allows expressions such as initializing a table of ascending numbers as shown below:+This constructs a table, the size of which is determined by ''<sizeexpression>''. The content of each slot is the result of evaluating ''<initexpression>''This means that ''<initexpression>'' is evaluated for each slot in the table! Tables of e.g. ascending numbers are easily formed: 
 <code> <code>
 >def z := 0 >def z := 0
Line 47: Line 53:
 </code> </code>
  
-Although there is no special constructor for definition of multidimensional tables, a table entry can contain another table. This is internally stored as a unidimensional table whose entries are other tables.+Although there is no special constructor for definition of multidimensional tables, a table entry can contain another table. This is internally stored as a one-dimensional table whose entries are other tables.
 <code> <code>
 >def vowels := ["a", "e", "i", "o", "u"] >def vowels := ["a", "e", "i", "o", "u"]
Line 57: Line 63:
 </code> </code>
  
-As shown in the definition of the varible //vowels//evaluating a series of comma-separated data types between square brackets (aka a tabulation) results in table.+As shown in the definition of the variable ''vowels''AmbientTalk provides literal syntax to encode in-line tables. Table assignment and indexation work as usual, but recall that table indices range from ''1'' up to ''table.length''. Some more examples of literal tables:
  
 <code> <code>
Line 66: Line 72:
 ==== Table Splicing ==== ==== Table Splicing ====
  
-TODO!+AmbientTalk provides the //splice operator// ''@'' to splice tables into surrounding table expressions: 
 +<code> 
 +>[1,@[2,3],4] 
 +>>[1, 2, 3, 4] 
 +>[1, @[2,[3]], [4], @[5], @[], 6] 
 +>>[1, 2, [3], [4], 5, 6] 
 +</code> 
 + 
 +The splicing operator can be also used in the left-hand side of an assignment or definition to separate the head of a table with its rest elements, as shown below. 
 +<code> 
 +>def [first, @rest] := [1,2,3,4] 
 +>>[1, 2, 3, 4] 
 +>rest 
 +>>[2, 3, 4] 
 +</code>
  
 ===== Functions ===== ===== Functions =====
    
-As variables and tables, functions are defined with the keyword **def** in the form of: +Analogous to variables and tables, functions are defined with the keyword **def** in the form of: 
 <code> <code>
 def functionname( <arglist> ) { <body> } def functionname( <arglist> ) { <body> }
 </code> </code>
-The argument list is just a list of local variables which are always evaluated one by one from left to right. A basic function looks like this:+The argument list is just a list of local variables which are always evaluated one by one from left to right. Hence, AmbientTalk employs //applicative-order// function calls, like Scheme. A basic ''square'' function looks like this:
 <code> <code>
 >def square (x) { x*x } >def square (x) { x*x }
Line 81: Line 101:
 >>25 >>25
 </code> </code>
-This example also illustrates how functions are called. Calls to functions without parameters must also include the parenthesis as shown below.+This example also illustrates the //canonical// function calling syntax. Calls to functions without parameters must also include the parentheses as shown below.
 <code> <code>
->def f(){nil}+>def f() { nil }
 >><closure:f> >><closure:f>
 >f() >f()
 >>nil >>nil
 </code> </code>
-The return value of a function is the result of the last statement executed. Functions must always return a value - i.e. they cannot be abstract. The example also illustrates how to create dumb function that doesn't do anything but returning the //nil// object+The return value of a function is the result of the last executed statement. Functions always return a value, but a function can always opt to return the //nil// object 
 + 
 +<note> 
 +A function definition is a statement. The body of a function can contain a list of statements, each separated by '';''. A syntax error often made in AmbientTalk is to write: 
 +<code> 
 +def funA() { 
 +  // do something useful 
 +
 +def funB() { 
 +  // do something else 
 +
 +</code> 
 +The parser will complain saying that ''def'' was an unexpected tokenThe reason is that the function definition statements should be separated by means of '';''. In languages like C and Java, the ''}'' token need not be followed by a semicolon, hence the confusion. 
 +</note>
  
-Functions have access to the enclosing environment of its definition as shown in the following example.  +Functions in AmbientTalk are //lexically scoped//, which means that free variables are looked up in the enclosing environment of the function definition. This is illustrated in the following example:
 <code> <code>
 >def counter := 0 >def counter := 0
Line 104: Line 137:
 >def fac(n) {  >def fac(n) { 
   def inner(n, result) {    def inner(n, result) { 
-    if: (n =0) then: { result } else: { inner( n-1, n * result)  }+    if: (n = 0) then: { result } else: { inner( n-1, n * result)  }
   };    }; 
   inner(n,1)   inner(n,1)
Line 113: Line 146:
 </code> </code>
  
-This example also illustrates how a function can be made private by means of lexical scope. Variables and functions defined locally to functions are only visible in the scope of the function where there were defined. Note that local //inner// function is only visible inside the //fac// function and its nested scopes. Thus, calling //fac.inner(2,3)// will return a lookup failure error.+This example also illustrates how a function can be made "privateby means of lexical scoping rules. Variables and functions defined locally to functions are only visible in the scope of the function where there were defined. Note that the local ''inner'' function is only visible inside the ''fac'' function and its nested scopes.
    
 +
 ==== Variable-Length Argument Functions ==== ==== Variable-Length Argument Functions ====
  
-You can create functions that take an arbitrary number of arguments by means of the splicing operator **@** which splices the table containing the parameters into the argument list.+You can create functions that take an arbitrary number of arguments (also known as a variable arity or polyadic function) by means of the splicing operator ''@'' which collects the actual arguments into a table:
 <code> <code>
->def sum(@args)+>def sum(@args) {
   def total := 0;    def total := 0; 
   foreach: { |el|  total := total + el } in: args;    foreach: { |el|  total := total + el } in: args; 
-  total}+  total 
 +};
 >><closure:sum> >><closure:sum>
 >sum(1,2,3) >sum(1,2,3)
Line 143: Line 178:
 In that case, the //sum// function still accepts an arbitrary number of arguments as long as two arguments are supplied. //a// and //b// are considered as mandatory arguments of the argument list.  In that case, the //sum// function still accepts an arbitrary number of arguments as long as two arguments are supplied. //a// and //b// are considered as mandatory arguments of the argument list. 
  
-A function can also declare optional arguments as shown below. Optional arguments can be omitted in a function call. Internally, the default value provided in their definition is passed as the argument to the function. +A function can also declare optional arguments as shown below. Optional arguments can be omitted in a function call. If this is the case, the default expression provided in their definition is evaluated and passed as argument to the function instead.
 <code> <code>
 >def incr( number, step := 1){ number + step} >def incr( number, step := 1){ number + step}
Line 152: Line 187:
 >>6 >>6
 </code> </code>
 +
 +As is customary in languages with the above parameter passing semantics, AmbientTalk requires mandatory parameters to be defined //before// optional parameters, which should in turn be defined //before// a variable-argument parameter, if any.
  
 ===== Closures ===== ===== Closures =====
Line 169: Line 206:
 </code> </code>
  
-This example also illustrates how a function can make public some of its local fields or functions by returning them as its return value. The get and set could be then passed as arguments to other functions such as //trustedFunction(get,set)// and  //distrustedFunction(get)//+This example also illustrates how a function can make public some of its local fields or functions by returning them as its return value. The ''get'' and ''set'' operations can then be passed separately throughout the application, e.g. an application module that has read-only access to ''val'' only receives the ''get'' closure.
  
 ===== Blocks ===== ===== Blocks =====
Line 197: Line 234:
 >def square := { |x| x * x } >def square := { |x| x * x }
 >><closure:lambda> >><closure:lambda>
->square(1,2+>square(3
->>3+>>9
 </code> </code>
  
Line 304: Line 341:
 </code> </code>
  
-Tables also support some useful iterator methods such as:+Tables also support some useful iterator methods as shown below. 
 <code> <code>
 >def sum:= 0;  >def sum:= 0; 
at/tutorial/basic.txt · Last modified: 2020/02/09 22:05 by elisag