简体   繁体   English

在prolog中将两个列表相乘

[英]Multiplying two lists in prolog

I am currently working with prolog and want to multiply two lists together but in a certian way. 我目前正在与prolog合作,并希望以证书方式将两个列表相乘。 For example: 例如:

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

I want to preform the following actions: 我想要执行以下操作:

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

Such that the first element of each list is multiplied to each other then added with the second elements multiplied together etc. 这样每个列表的第一个元素相互相乘,然后加上第二个元素相乘等。

Is this possible to go in Prolog? 这有可能进入Prolog吗?

I know in other languages you can do a recursive function with takes the head of the list and the tail (the rest of the entries). 我知道在其他语言中你可以做一个递归函数,带有列表的头部和尾部(其余的条目)。 This allows for a simple multiplication but I do not think that is possible in prolog? 这允许简单的乘法,但我不认为这是可能的prolog?

Using built-ins: 使用内置插件:

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

Using simple recursion: 使用简单的递归:

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

Using tail recursion: 使用尾递归:

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

If all items of your lists are integers and your Prolog implementation offers , you can simply use the clpfd built-in predicate scalar_product/4 , like this: 如果列表中的所有项都是整数,并且Prolog实现提供了 ,则只需使用clpfd内置谓词scalar_product/4 ,如下所示:

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

Edit: You may also be interested in the related question " Prolog: Multiplying 2 lists with 1 of them not instantiated? ", particularly in this answer . 编辑:您可能也对相关问题“ Prolog:乘以2个列表,其中1个没有实例化? ”感兴趣,特别是在这个答案中

as an alternative to 'hand coded' loops, using library( aggregate ) and nth1 /3: 作为'手动编码'循环的替代,使用库( 聚合 )和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).

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM