Prolog列表中元素的总和 [英] Sum of elements in list in Prolog

查看:180
本文介绍了Prolog列表中元素的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

list_sum([], 0).
list_sum([Head | Tail], TotalSum) :-
    list_sum(Tail, Sum1),
    Total = Head + Sum1.

此代码返回true.如果将Total = Head + Sum1替换为Total is Head + Sum1,则它将返回该值.但是我应该将其替换为这样的结果:

This code returns true. If I replace Total = Head + Sum1 with Total is Head + Sum1, then it will return the value. But what I should replace it with to get the result like this:

?- list_sum([1,2,0,3], Sum).
Sum = 1+2+0+3 ; % not to return value 6!!!

推荐答案

请注意,在过程的第二个子句中,永不实例化TotalSum.在查询您的代码时,您应该已经收到解释器的警告.

Note that in the second clause of your procedure TotalSum is never instantiated. You should have received a warning by the interpreter when consulting your code.

这是我的建议:

list_sum([Item], Item).
list_sum([Item1,Item2 | Tail], Total) :-
    list_sum([Item1+Item2|Tail], Total).

第一个子句处理基本情况,当列表中仅剩一个元素时,即为结果.

The first clause deals with the base case, when there is only one element left in the list, that is your result.

第二个子句处理递归步骤.它获取列表的前两个项目,并执行递归调用,用新的术语Item1 + Item2替换这两个项目.

The second clause deals with the recursion step. It grabs the first two items of the list and performs a recursive call replacing those two items with a new term Item1+Item2.

这篇关于Prolog列表中元素的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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