Reputation: 31
If I have a list:
food_price(banana,2).
food_price(apple,1).
food_price(chocolate,5).
food_price(milk,3).
food_price(coffee,4).
And if I want to sum up the price like this using 'total_price/2':
?- total_price([banana, apple, milk], Price).
Price = 6.
How can I get it work? I only know adding up number in a list in prolog can be written like this:
sum([H|T], Price) :- sum(T, H, Price).
sum([], Acc, Acc).
sum([H|T], Acc, Price) :- NewAcc is H + Acc, sum(T, NewAcc, Price).
But how can I match the price with the name of food? Thanks.
Upvotes: 3
Views: 71
Reputation: 58324
This can easily be done with maplist/3
:
total_price(FoodList, TotalPrice) :-
maplist(food_price, FoodList, PriceList),
sumlist(PriceList, TotalPrice).
maplist/3
applies the food_price
call to each element of FoodList
and provides the corresponding success arguments in PriceList
. Then you just add them up with sumlist/2
.
If you don't want to use maplist
or sumlist
, you can create what these do easily with simple list recursion.
Upvotes: 1