如何在Prolog中将两个列表的所有元素彼此相乘

问题描述:

我正在考虑如何将两个列表的所有元素彼此相乘.然后,我想将所有结果都放在List3中.例如

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].
List2 = [2,6,7]. 

List3应包含[1x2、1x6、1x7、3x2、3x6、3x7、5x2、5x6、5x7]. 最后;

List3should contain [1x2, 1x6, 1x7, 3x2, 3x6, 3x7, 5x2, 5x6, 5x7]. In the end;

List3 = [2, 6, 7, 6, 18, 21, 10, 30, 35].

有可能这样做吗?怎么做?我找不到正确的方法.

Is it possible to do that? How to do that? I couldn't find a right way.

首先,请看一下这个问题对每个执行操作列出swi-prolog等中的元素,以了解如何在lists上执行for-each操作.
其次,这是代码:

Well,First take a look on this question executing operation for each list element in swi-prolog and others to know how to do for-each operation on lists.
Second, here is the code:

prod(X,[],[]).
prod(X,[HEAD|TAIL],L) :-  prod(X,TAIL,L1), W is X * HEAD, L = [W|L1].

prod2([],Y,[]).
prod2([HEAD|TAIL],Y,L) :- prod(HEAD,Y,L1), prod2(TAIL,Y,L2), append(L1,L2,L).

输出:

?- prod2([1,3,5] ,[2,6,7],G).
G = [2, 6, 7, 6, 18, 21, 10, 30, 35] .