next up previous contents
Next: FuncDef Up: Evaluation Rules Previous: Assign   Contents

Iterate

The language includes expressions for iterating over both lists and bindings. There is also a _map primitive defined on lists (Section A.3.4.4) and bindings (Section A.3.4.5). _map is more efficient but less general than the language's Iterate construct.

<

Iterate    ::= foreach Control in Expr do IterBody
Control    ::= Id | `[' Id = Id `]'
IterBody   ::= Stmt | `{' Stmt+; `}'

The two Control forms are used to iterate over lists and bindings, respectively.

<

// iteration with single-statement body
Eval( foreach Control in Expr do Stmt , C) =
  Eval( foreach Control in Expr do { Stmt } , C)

The semantics of a loop are to conceptually unroll the loop n times, where n is the length of the list or binding being iterated over. The evaluation rules for iterating over lists and bindings are shown in Table A.6. Note that the iteration variables (that is, Id, Id1, and Id2 in the Table) are not bound in the binding that results from evaluating the foreach statement. However, any assignments made in the loop body are included in the result binding.


Table A.6: Evaluation rules for iterating over lists and bindings. As defined in Section A.3.4.7, _is_list(l) is true if l is of type t_list, and false otherwise; _is_binding(b) is true if b is of type t_binding, and false otherwise.
\begin{table}{\small\begin{verbatim}// iteration over a list
Eval( foreach Id ...
...Eval( { Stmt_1; ...; Stmt_n } , r1));
}
return r;
}\end{verbatim}}
\end{table}


Iteration statements are typically used to walk over or collect parts of a list or binding. For example, Table A.7 presents functions for reversing a list and for counting the number of leaves in a binding.


Table A.7: Two functions demonstrating the use of foreach to iterate over a list and a binding.
\begin{table}{\small\begin{verbatim}reverse_list(l: list): list
{
res: list =...
...(val)
then count_leaves(val) else 1;
return res;
}\end{verbatim}}
\end{table}



next up previous contents
Next: FuncDef Up: Evaluation Rules Previous: Assign   Contents
Allan Heydon, Roy Levin, Timothy Mann, Yuan Yu