How to multiply all elements of two lists with each other in Prolog

后端 未结 5 1130
终归单人心
终归单人心 2021-01-22 00:12

I am thinking how to multiply all elements of two list with each other. Then I want to put all results in List3. For example,

List1 = [1,3,5].
List         


        
5条回答
  •  太阳男子
    2021-01-22 00:49

    Here is a rather straight-forward solution using library(lambda)

    product(Xs, Ys, Ps) :-
       maplist(Ys+\X^maplist({X,Ys}+\Y^YP^(YP=X*Y),Ys), Xs, PPs),
       append(PPs, Ps).
    

    So we have an outer-loop for Xs and an inner loop for Ys.

    ?- product([1,2,3],[4,5,6],Ps).
    Ps = [1*4,1*5,1*6,2*4,2*5,2*6,3*4,3*5,3*6].
    

    Replace (YP=X*Y) by (YP is X*Y) or (YP #= X*Y). Whatever you prefer.

提交回复
热议问题