GNU Prolog - Loop and the New List

This is just a general question related to something else.

Suppose the table of products is from a matrix (I think it is called).

Example: enter

outer([1,2,3],[4,5,6],L).

Then L = [[4,5,6],[8,10,12],[12,14,18]]

So, I want to iterate over two lists and create a new list.

I got it:

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 close. I know that I can use append to iterate through both lists, but not sure how to create a new list. There are always problems when creating a completely new list.

Thank.

+3
source share
2 answers
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).
+2
source

Here is another, it uses a map instead of append. Spot products are produced for products with no number. It is also deterministic.

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).

:

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)]].
+1

Source: https://habr.com/ru/post/1780578/


All Articles