关于列表操作的Prolog

时间:2013-09-25 13:32:01

标签: list prolog

语句:

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

如何编写prolog谓词total(X)。 X是你摩托车的总和。

我无法将engine = 2000的值与frame = 605的值相关联,如果我咨询总计(摩托车),则应返回答案2605。

2 个答案:

答案 0 :(得分:1)

aggregation这是你的朋友:

total(Kind, X) :-
   vehicle(Kind, Parts),
   aggregate(sum(Price), Part^(member(Part, Parts), value(Part, Price)), X).

答案 1 :(得分:1)

如果您没有CapelliC显示的aggregate谓词,那么这是一个明确地进行求和的版本:

% 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 ).