如何在Prolog中将两个列表的所有元素彼此相乘 [英] How to multiply all elements of two lists with each other in Prolog

查看:84
本文介绍了如何在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] .

这篇关于如何在Prolog中将两个列表的所有元素彼此相乘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆