0
votes

Say I have two 'tables' in Prolog, e.g.:

item_value('Chair', 50).          
item_value('Table', 100).        
item_value('Plant', 75).

And another one:

shopping_cart('Max', ['Chair', 'Chair', 'Table']).            
shopping_cart('Sam', ['Plant', 'Table']).

I now want to write a predicate that calculates the sum of the items inside the shopping cart, something like total_sum(Person, Sum)

How would i do this? I can't wrap my head around coding this in Prolog.
Thanks in advance!

1
Here's a hint... If you have a list of items, Items, and you want to add up their values, you can do it easily with findall(Cost, (member(Item, Items), item_value(Item, Cost)), Costs). then add them up, sumlist(Costs, TotalCost).. If you can't use findall/3 or sumlist/2 (seems to be a favorite constraint among Prolog homework assignments), then write a recursive predicate to do it. - lurker
Think of Prolog as being like a query language. If you query, item_value(Item, Cost). it will yield each Item and Cost that is in your data. Another fundamental aspect of Prolog is handling lists. If you aren't comfortable handling lists, I'd suggest a good text book, tutorial, or look at a bunch of example problems such as 99 Prolog Problems. That's all I can give you in this context. This isn't a free, personalized language tutorial site. ;) - lurker

1 Answers

0
votes

Try the following code:

item_value('Chair', 50).          
item_value('Table', 100).        
item_value('Plant', 75).

shopping_cart('Max', ['Chair', 'Chair', 'Table']).            
shopping_cart('Sam', ['Plant', 'Table']).

total_sum(Person, Sum) :-
    shopping_cart(Person, ItemList),
    maplist(item_value, ItemList, CostList),
    foldl(plus, CostList, 0, Sum).