foreach on matrices (idea from BProlog)

This commit is contained in:
Vítor Santos Costa
2013-09-20 01:16:25 +01:00
parent 28ff95f8de
commit 0f45b3dc42
2 changed files with 59 additions and 18 deletions

View File

@@ -1,5 +1,6 @@
:- use_module(library(matrix)).
:- use_module(library(maplist)).
t1 :-
X <== matrix([1,2,3,4,5,6],[dim=[3,2]]),
@@ -27,3 +28,32 @@ numbers(I0, I1, Vals) :-
( I0 =< I1 -> Vals = [I0|MVals], I01 is I0+1, numbers(I01, I1, MVals) ;
Vals = [] ).
t5 :-
numbers(1, 100, L),
X <== matrix(L, [dim=[10,10]]),
writeln('diagonal:'),
foreach([I in 0..9, J in I..I], Y^(Y <== X[I,J], writeln(Y) ) ).
t6 :-
Len = 10,
LenSq is Len*Len,
Len1 is Len-1,
numbers(1, LenSq, L),
X <== matrix(L, [dim=[Len,Len]]),
Y <== matrix(L, [dim=[Len,Len]]),
Z <== matrix(L, [dim=[Len,Len]]),
writeln('product:'),
foreach([I in 0..Len1, J in 0..Len1], step(X,Y,Z,I,J) ),
O <== list(Z),
writeln(O).
step(X,Y,Z,I,J) :-
Xs <== X[I,_],
Ys <== Y[_,J],
foldl(addprod, Xs, Ys, 0, P), % scalar product
Z[I,J] <== P.
addprod(X, Y, S0, S) :-
S is S0+X*Y.