Reputation: 7249
This is just kind of general question, steming from something else.
Say you want the product table from a matrix ( I think thats what its called).
Example i put in
outer([1,2,3],[4,5,6],L).
Then L = [[4,5,6],[8,10,12],[12,14,18]]
So i want to iterate through two lists and create a new list.
I got this:
outer(L1,L2,L3) :-
append(LL,[L|RL],L1),
append(LE,[E|RE],L2),
Prod is L * E, !,
append(LE,[Prod|RE], NewL),
append(LL,[NewL|RL], L3).
which is kind of close. I know i can use append to iterate through both Lists, not sure how to create a new list. Always have trouble when it comes to creating a completely new list.
Thanks.
Upvotes: 3
Views: 1298
Reputation: 1782
Here's another, it uses map instead of append. Dot-products are produced for products involving a non number. It's also deterministic.
The multiplier:
amul([], _Other_Row,[]).
amul([X|Xs],Other_Row,[Row_Out|Rest_Out]) :-
maplist(mul(X),Other_Row, Row_Out),
amul(Xs,Other_Row, Rest_Out).
The product predicate:
mul(X,Y, Prod) :-
( number(X), number(Y)
-> Prod is X * Y
; true
-> Prod = dot(X,Y)
).
[1,3,5] X [2,4,6]
?- amul([1,3,5], [2,4,6],Prod).
Prod = [[2, 4, 6], [6, 12, 18], [10, 20, 30]].
[a,b,c] X [1,2,3,4]
?- amul([a,b,c],[1,2,3,4],Prod).
Prod = [[dot(a, 1), dot(a, 2), dot(a, 3), dot(a, 4)],
[dot(b, 1), dot(b, 2), dot(b, 3), dot(b, 4)],
[dot(c, 1), dot(c, 2), dot(c, 3), dot(c, 4)]].
Upvotes: 1
Reputation: 5157
product([],_,[]).
product([H1|T1],L2,R):- mul(H1,L2,R1),product(T1,L2,R2),append([R1],R2,R).
mul(X,[],[]).
mul(X,[H|T],[Z|R]):-Z is X*H, mul(X,T,R).
Upvotes: 2