[英]Prolog: Find out if sum of all list elements equals N
I want to check if all values in a list add up to some value. 我想检查列表中的所有值是否合计为某个值。 So far, I have written the following:
到目前为止,我写了以下内容:
list_sum([Head|Tail], Sum) :-
list_sum(Tail, Sum1),
Sum is Head + Sum1.
However, when I try list_sum([1,2,3,4], 10)
Prolog returns false
. 但是,当我尝试
list_sum([1,2,3,4], 10)
Prolog返回false
。 Could someone help me out? 有人可以帮帮我吗? I don't know what I'm doing wrong.
我不知道我做错了什么。
:- use_module(library(clpfd)).
For calculating the sum of a list of integers simply use clpfd library predicate sum/3
: 要计算整数列表的总和,只需使用clpfd库谓词
sum/3
:
?- sum([1,2,3,4], #=, S). % Q: What is 1+2+3+4? S = 10. % A: Sum is 10 ?- sum([1,2,3,4], #=, 10). % Q: Does 1+2+3+4 equal 10? true. % A: yes, it does ?- sum([1,2,3,4], #=, 11). % Q: Does 1+2+3+4 equal 11? false. % A: no, it doesn't
A use case showing the benefits of using clpfd instead of (is)/2
, suggested by @CapelliC: 一个用例,显示使用clpfd而不是
(is)/2
的好处,由@CapelliC建议:
?- [A,B,C] ins 1..sup, sum([A,B,C,A], #=, 12), labeling([], [A,B,C]). A = B, B = 1, C = 9 ; A = 1, B = 2, C = 8 ; A = 1, B = 3, C = 7 ; A = 1, B = 4, C = 6 ; A = 1, B = C, C = 5 ; A = 1, B = 6, C = 4 ; A = 1, B = 7, C = 3 ; A = 1, B = 8, C = 2 ; A = C, B = 9, C = 1 ; A = 2, B = 1, C = 7 ; A = B, B = 2, C = 6 ; A = 2, B = 3, C = 5 ; A = 2, B = C, C = 4 ; A = 2, B = 5, C = 3 ; A = C, B = 6, C = 2 ; A = 2, B = 7, C = 1 ; A = 3, B = 1, C = 5 ; A = 3, B = 2, C = 4 ; A = B, B = C, C = 3 ; A = 3, B = 4, C = 2 ; A = 3, B = 5, C = 1 ; A = 4, B = 1, C = 3 ; A = 4, B = C, C = 2 ; A = 4, B = 3, C = 1 ; A = 5, B = C, C = 1.
It seems to me that this is rather simple. 在我看来,这很简单。
Try this: 试试这个:
list_sum([], 0).
list_sum([Head|Tail], Sum):-
list_sum(Tail, Sum1),
Sum is Head + Sum1.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.