在序言中,一旦你绑定变量的值,它停止变量为。这意味着您需要在调用列表时维护调用堆栈的状态。所以我会这样处理这个问题,使用一个助手谓词和额外的参数来保持状态。
约定通常是为帮助者具有与“公共”谓词相同的函子,并具有维护状态所需的额外值。我想接近它是这样的:
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