next up previous contents index
Next: Transformation Up: Programming Concepts Previous: Iteration on terms   Contents   Index

Subsections


Iteration on array


Description

The next concept is iteration on an array structure. We often want to perform some action on each element of a two-dimensional array.

Again, we present two implementations. The first uses nested foreacharg do loops to perform some operation q on each element of an array. The second uses nested for loops to iterate over all index combinations I and J. This second variant is more complex, and should be used only if we require the index values I and J as well as the matrix element X.

Parameters

Matrix
a matrix

Schema

/* version 1 */

:-mode iteration(+).
iteration(Matrix):-
        (foreacharg(Line,Matrix) do
            (foreacharg(X,Line) do
                q(X)
            )
        ).

/* version 2 */

:-mode iteration(+).
iteration(Matrix):-
        dim(Matrix,[N,M]),
        (for(I,1,N),
         param(M,Matrix) do
            (for(J,1,M),
             param(I,Matrix) do
                subscript(Matrix,[I,J],X),
                q(X,I,J)
            )
        ).

Comments

The dim predicate can not only be used to create arrays, but also to find the size of an existing array.

Note the strange way in which parameters M, I and Matrix are passed through the nested for loops with param arguments. But if we do not do this, then the variable Matrix outside and inside the do loop are unrelated.

Example

The example calls the predicate fill_empty/3 for each index combination of entries in a matrix PMatrix.
:-mode fill_rest_with_empty(+,+).
fill_rest_with_empty(N,PMatrix):-
        (for(I,1,N),
         param(PMatrix,N) do
            (for(J,1,N),
             param(PMatrix,I) do
                fill_empty(PMatrix,I,J)
            )
        ).


next up previous contents index
Next: Transformation Up: Programming Concepts Previous: Iteration on terms   Contents   Index
Warwick Harvey
2004-08-07