Download pdf format
Transcript
which can be written as follows without the need for an auxiliary predicate: main :( foreach(X, [1,2,3]) do writeln(X) ). This looks very much like a loop in a procedural language. However, due to the relational nature of logic programming, the same foreach- construct can be used not only to control iteration over an existing list, but also to build a new list during an iteration. For example main :( foreach(X, [1,2,3]), foreach(Y, Negatives) do Y is -X ), writeln(Negatives). will print [-1, -2, -3]. The general form of a do-loop is ( IterationSpecs do Goals ) and it corresponds to a call to an auxiliary recursive predicate of the form do__n(...). do__n(...) :- Goals, do__n(...). The IterationSpecs determine the number of times the loop is executed (i.e. the termination condition), and the way information is passed into the loop, from one iteration to the next, and out of the loop. IterationSpecs is one (or a comma-separated sequence) of the following: fromto(First,In,Out,Last) iterate Goals starting with In=First until Out=Last. In and Out are local variables in Goals. For all but the first iteration, the value of In is the same as the value of Out in the previous iteration. foreach(X,List) iterate Goals with X ranging over all elements of List. X is a local variable in Goals. Can also be used for constructing a list. foreacharg(X,Struct) iterate Goals with X ranging over all elements of Struct. X is a local variable in Goals. Cannot be used for constructing a term. for(I,MinExpr,MaxExpr) iterate Goals with I ranging over integers from MinExpr to MaxExpr. I is a local variable in Goals. MinExpr and MaxExpr can be arithmetic expressions. Can be used only for controlling iteration, ie. MaxExpr cannot be uninstantiated. for(I,MinExpr,MaxExpr,Increment) same as before, but Increment can be specified (it defaults to 1). 30