陈述:
value(engine,2000).
value(frame,605).
vehicle(motorbike,[engine,frame]).
如何编写序言谓词total(X)
。X 是您购买摩托车的总金额。
我无法关联 engine=2000 加上 frame=605 的值,如果我咨询总(摩托车),应该返回答案 2605。
如果您没有aggregate
CapelliC 显示的谓词,这是一个显式求和的版本:
% This says total is sum of the parts
total( Item, Amt ) :-
vehicle( Item, PartList ),
sum_parts( PartList, 0, Amt ).
% This says the sum of the parts is the sum of current part in list plus the sum
% of the rest
sum_parts( [Part|PartList], Acc, Amt ) :-
value( Part, PartAmt ), % This statement will relate the part to its price for you
Acc1 is Acc + PartAmt, % This will accumulate the price to the running total
sum_parts( PartList, Acc1, Amt ).
sum_parts( [], Amt, Amt ).
聚合它是你的朋友:
total(Kind, X) :-
vehicle(Kind, Parts),
aggregate(sum(Price), Part^(member(Part, Parts), value(Part, Price)), X).