-1

陈述:

value(engine,2000).
value(frame,605).
vehicle(motorbike,[engine,frame]).

如何编写序言谓词total(X)。X 是您购买摩托车的总金额。

我无法关联 engine=2000 加上 frame=605 的值,如果我咨询总(摩托车),应该返回答案 2605。

4

2 回答 2

1

如果您没有aggregateCapelliC 显示的谓词,这是一个显式求和的版本:

% 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 ).
于 2013-09-25T14:31:13.310 回答
1

聚合它是你的朋友:

total(Kind, X) :-
   vehicle(Kind, Parts),
   aggregate(sum(Price), Part^(member(Part, Parts), value(Part, Price)), X).
于 2013-09-25T14:19:28.253 回答