在序言中将两个列表相乘 [英] Multiplying two lists in prolog

查看:181
本文介绍了在序言中将两个列表相乘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用序言,并且希望将两个列表以乘方方式相乘.例如:

I am currently working with prolog and want to multiply two lists together but in a certian way. For example:

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

我要执行以下操作:

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

有可能进入Prolog吗?

Is this possible to go in 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?

推荐答案

使用内置功能:

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

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

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