2015-04-25 46 views
4

我想檢查一個列表中的所有值是否合計爲某個值。到目前爲止,我寫了下面的:序言:找出所有列表元素的總和是否等於N

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

然而,當我嘗試list_sum([1,2,3,4], 10)的Prolog返回false。 有人可以幫我嗎?我不知道我做錯了什麼。

+5

你只有一個規則,該規則假定第一個參數是至少一個元素的列表。所以它會遞歸直到「Tail」成爲空列表並失敗(沒有匹配的規則)。當第一個參數是空列表時,您需要另一個規則。 – lurker

+1

有庫支持:嘗試'? - sum_list([1,2,3.3],6.3).' – CapelliC

回答

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 

用例顯示使用的,而不是(is)/2 clpfd的好處,通過@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. 
+2

另一個用例:'? - [A,B,C] ins 1..sup,sum([A, B,C,A],#= 12),標籤([A,B,C])。' – CapelliC

1

在我看來,這是相當簡單的。

試試這個:

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