简体   繁体   English

使用Prolog中的printlist / 1谓词对列表中的所有数字求和

[英]Using the printlist/1 predicate in Prolog to sum up all numbers in a list

I am trying to use the printlist/1 predicate to sum up all the numbers in a list but kind of got stuck.... tried to come up with the code for this but I keep getting false . 我想使用printlist/1谓词来总结所有清单,但那种被困人数....试图想出这个代码,但我不断收到false

Here is what I've come up with: 这是我想出的:

printlist([]).
printlist([H|T], Totalsum) :- 
   print (H+Totalsum),
   nl,
   printlist(T, Totalsum).

I know it's wrong and it's probably the last part. 我知道这是错误的,可能是最后一部分。 Any help is appreciated! 任何帮助表示赞赏!

I query it this way: 我这样查询:

?- printlist([1,2,3]).
false.

As Paulo already said, you are defining two predicates here, which is incorrect. 正如Paulo所说,您在此处定义两个谓词,这是不正确的。

Here is the solution: 解决方法如下:

printlist([], 0).
printlist([H|T], Sum) :-
   printlist(T, Subsum),
   Sum is Subsum + H.

Sample query: 查询样例:

?- printlist([1,2,3,5], L).
L = 11.

@ Paulo requested), a tail recursive version: @ Paulo要求),尾递归版本:

printlist(L, Sum) :-
   sumac(L, 0, Sum).

sumac([], Acc, Acc).
sumac([H|T], Acc, Sum) :-
   Nacc is Acc + H,
   sumac(T, Nacc, Sum). 

You're defining not one but two predicates: printlist/1 and printlist/2 . 您定义的不是一个谓词,而是两个谓词: printlist/1printlist/2 Likely a typo. 可能是错字。 The printlist/2 predicate is a recursive rule but there isn't a base case. printlist/2谓词是一个递归规则,但没有基本情况。 Change the printlist/1 clause to: printlist/1子句更改为:

printlist([], _).

But there are other errors in your code. 但是您的代码中还有其他错误。 Hint: Prolog is not a functional language. 提示:Prolog不是功能语言。

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

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