在序言中,一旦你綁定變量的值,它停止變量爲。這意味着您需要在調用列表時維護調用堆棧的狀態。所以我會這樣處理這個問題,使用一個助手謂詞和額外的參數來保持狀態。
約定通常是爲幫助者具有與「公共」謂詞相同的函子,並具有維護狀態所需的額外值。我想接近它是這樣的:
sum_of_numbers(Xs,Ys) :- % to sum the numbers in a list,
sum_of_numbers(Xs,0,[],Ys) % we invoke the helper, seeding its two accumulators appropriately.
.
sum_of_numbers([] , T , L , [T|L]) . % when the source list isexhausted, unify the accumulators with the result
sum_of_numbers([X|Xs] , T , L , R ) :- % otherwise,
number(X) , % - if X is numeric
T1 is T+X , % - increment the tally
sum_of_numbers(Xs,T1,L,R) % - and recurse down
. %
sum_of_numbers([X|Xs] , T , L , R ) :- % otherwise,
\+ number(X) , % - if X is non-numeric
sum_of_numbers(Xs,T,[X|L],R) % - add X to the list accumulator
. % - and recurse down.
您也可以使用軟切(隱含的)第2及3組合:
sum_of_numbers([] , T , L , [T|L]) .
sum_of_numbers([X|Xs] , T , L , R ) :-
(number(X) ->
T1 is T+X , L1 = L
;
T1 = T , L1 = [X|L]
) ,
sum_of_numbers(Xs,T1,L1,R)
.
這是否是一種進步與否是由你。
在Prolog中,Z是Z + X只有當X = 0時才爲真 – CapelliC 2014-12-04 22:06:30