Loops

## 4.2 Loops

To reduce the need for auxiliary recursive predicates, ECLiPSe allows the use of an iteration construct

>     ( IterationSpecs do Goals )

Typical applications are: Iteration over a list

>     ?- ( foreach(X,[1,2,3]) do writeln(X) )
>     1
>     2
>     3
>     Yes (0.00s cpu)

Process all elements of one list and construct another:

>     ?- ( foreach(X,[1,2,3]), foreach(Y,List) do Y is X+3 ).
>     List = [4, 5, 6]
>     Yes (0.00s cpu)

Process a list to compute the sum of its elements:

>     ?- ( foreach(X,[1,2,3]), fromto(0,In,Out,Sum) do Out is In+X ).
>     Sum = 6
>     Yes (0.00s cpu)

Note that the variables X, Y, In and Out are local variables in the loop, while the input list and Sum are shared with the context.
If a parameter remains constant across all loop iterations it must be specified explicitly (via param), for example when iterating over an array:

>     ?- Array = [](4,3,6,7,8),
>        (
>            for(I,1,5),
>            fromto(0,In,Out,Sum),
>            param(Array)
>        do
>            Out is In + Array[I]
>        ).

> fromto(First,In,Out,Last) iterate Goals starting with In=First until Out=Last. foreach(X,List) iterate Goals with X ranging over all elements of List. foreacharg(X,StructOrArray) iterate Goals with X ranging over all arguments of StructOrArray. foreacharg(X,StructOrArray,Idx) same as before, but Idx is set to the argument position of X in StructOrArray. foreachelem(X,Array) like foreacharg/2, but iterates over all elements of an array of arbitrary dimension. foreachelem(X,Array,Idx) same as before, but Idx is set to the index position of X in Array. foreachindex(Idx,Array) like foreachelem/3, but returns just the index position and not the element. for(I,MinExpr,MaxExpr) iterate Goals with I ranging over integers from MinExpr to MaxExpr. for(I,MinExpr,MaxExpr,Increment) same as before, but Increment can be specified (it defaults to 1). multifor(List,MinList,MaxList) like for/3, but allows iteration over multiple indices (saves writing nested loops). multifor(List,MinList,MaxList,IncrementList) same as before, but IncrementList can be specified (i.e. how much to increment each element of List by). count(I,Min,Max) iterate Goals with I ranging over integers from Min up to Max. param(Var1,Var2,...) for declaring variables in Goals global, i.e. shared with the context.

> Figure 4.1: Iteration Specifiers for Loops

⊙
  For details and more examples see the description of the do/2 built-in predicate. Additional background can be found in [24].