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.
/* 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) ) ).
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.
:-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) ) ).