Prolog:找出所有列表元素的总和是否等于N.

时间:2015-04-25 01:35:43

标签: list prolog

我想检查列表中的所有值是否合计为某个值。到目前为止,我写了以下内容:

list_sum([Head|Tail], Sum) :-
    list_sum(Tail, Sum1),
    Sum is Head + Sum1.

然而,当我尝试list_sum([1,2,3,4], 10) Prolog返回false时。 有人可以帮帮我吗?我不知道自己做错了什么。

2 个答案:

答案 0 :(得分:2)

使用

:- use_module(library(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

@CapelliC建议使用clpfd代替(is)/2的好处的用例:

?- [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.

答案 1 :(得分:1)

在我看来,这很简单。

试试这个:

list_sum([], 0).
list_sum([Head|Tail], Sum):-
    list_sum(Tail, Sum1),
    Sum is Head + Sum1.