Next: Iteration on array
Up: Programming Concepts
Previous: Iteration on lists
  Contents
  Index
Subsections
Description
We can iterate not only over all elements of a list, as in the previous concept, but also over all arguments of a term. Obviously, this only makes sense if all arguments of the term are of a similar type i.e. the term is used as a vector. The foreacharg keyword of the do loop iterates over each argument of a term.
- T
- a term
:-mode iteration(+).
iteration(T):-
(foreacharg(X,T) do
q(X)
).
We can use multiple foreacharg keywords to scan multiple vectors at the same time, but we cannot use foreacharg to create terms (we do not know the functor of the term). If we want to create a new term, we have to generate it with the right functor and arity before the do loop. The following code segment performs vector addition
.
:-mode vector_add(+,+,-).
vector_add(A,B,C):-
functor(A,F,N),
functor(C,F,N),
(foreacharg(X,A),
foreacharg(Y,B),
foreacharg(Z,C) do
Z is X + Y
).
If the terms A and B do not have the same number of arguments, the predicate will fail.
Example
:-mode interface_mib_add(+,+,-).
interface_mib_add(A,B,C):-
C = interface_mib with [],
(foreacharg(A1,A),
foreacharg(B1,B),
foreacharg(C1,C) do
C1 is A1 + B1
).
This predicate adds vectors with the functor interface_mib and returns such a vector.
Next: Iteration on array
Up: Programming Concepts
Previous: Iteration on lists
  Contents
  Index
Warwick Harvey
2004-08-07