【问题标题】:Multiplying two lists in prolog在prolog中将两个列表相乘
【发布时间】:2014-03-05 19:41:46
【问题描述】:

我目前正在使用 prolog 并希望以某种方式将两个列表相乘。例如:

[1,2,3] and [4,5,6] are my two lists.

我想执行以下操作:

(1*4)+(2*5)+(3*6) = 32

这样每个列表的第一个元素相互相乘,然后与第二个元素相乘,以此类推。

这可以在 Prolog 中使用吗?

我知道在其他语言中,您可以使用列表的头部和尾部(其余条目)来执行递归函数。这允许一个简单的乘法,但我认为这在 prolog 中是不可能的?

【问题讨论】:

  • 你读过prolog教程或书籍吗?为什么您认为在 prolog 中可能无法进行递归列表处理?这是一个很常见的操作。

标签: list prolog


【解决方案1】:

使用内置函数:

mult(X, Y, Z) :- Z is X * Y.

sum_prod(A, B, SumProd) :-
    maplist(mult, A, B, Prods),
    sumlist(Prods, SumProd).   % In GNU Prolog this is sum_list

使用简单递归:

sum_prod([A|As], [B|Bs], SumProd) :-
    sum_prod(As, Bs, SP),
    SumProd is SP + A*B.
sum_prod([], [], 0).

使用尾递归:

sum_prod(A, B, SumProd) :-
    sum_prod(A, B, 0, SumProd).
sum_prod([A|As], [B|Bs], Acc, SumProd) :-
    Acc1 is Acc + A*B,
    sum_prod(As, Bs, Acc1, SumProd).
sum_prod([], [], Acc, Acc).

【讨论】:

  • Lurker看了很多你的回答,真的帮我学习Prolog,谢谢
【解决方案2】:

如果您的列表中的所有项目都是整数并且您的 Prolog 实现提供了,您可以简单地使用 clpfd 内置谓词scalar_product/4,像这样:

?- scalar_product([1,2,3],[4,5,6],#=,Product).
Product = 32.

编辑: 您可能还对相关问题“Prolog: Multiplying 2 lists with 1 of them not instantiated?”感兴趣,尤其是this answer

【讨论】:

    【解决方案3】:

    使用库(aggregate) 和nth1/3 作为“手动编码”循环的替代方案:

    sum_prod(A,B,S) :-
        aggregate(sum(M), I^X^Y^(nth1(I,A,X), nth1(I,B,Y), M is X*Y), S).
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-22
      • 2022-11-28
      • 1970-01-01
      相关资源
      最近更新 更多