Download User Manual

Transcript
Unless you use :-pragma(noexpand) or :-dbgcomp, the do-construct is compiled into an efficient
auxiliary predicate named do nnn, where nnn is a unique integer. This will be visible during
debugging. To make debugging easier, it is possible to give the loop a user-defined name by
adding loop name(Name) to the iteration specifiers. Name must be an atom, and is used as
the name of the auxiliary predicate into which the loop is compiled (instead of do nnn). The
name should therefore not clash with other predicate names in the same module.
5.2.1
Examples
Iterate over list
foreach(X,[1,2,3]) do writeln(X).
Maplist (construct a new list from an existing list)
(foreach(X,[1,2,3]), foreach(Y,List) do Y is X+3).
Sumlist
(foreach(X,[1,2,3]), fromto(0,In,Out,Sum) do Out is In+X).
Reverse list
(foreach(X,[1,2,3]), fromto([],In,Out,
Rev) do Out=[X|In]). % or:
(foreach(X,[1,2,3]), fromto([],In,[X|In],Rev) do true).
Iterate over integers from 1 up to 5
for(I,1,5) do writeln(I). % or:
count(I,1,5) do writeln(I).
Iterate over integers from 5 down to 1
(for(I,5,1,-1) do writeln(I)).
Make list of integers [1,2,3,4,5]
(for(I,1,5), foreach(I,List) do true). % or:
(count(I,1,5), foreach(I,List) do true).
Make a list of length 3
(foreach(_,List), for(_,1,3) do true). % or:
(foreach(_,List), count(_,1,3) do true).
Get the length of a list
(foreach(_,[a,b,c]), count(_,1,N) do true).
Actually, the length/2 builtin is (almost)
length(List, N) :- (foreach(_,List), count(_,1,N) do true).
Iterate [I,J] over [1,1], [1,2], [1,3], [2,1], ..., [3,3]:
(multifor([I,J],1,3) do writeln([I,J])).
32