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