简体   繁体   中英

Sum Calculation in Prolog

Say I have two 'tables' in Prolog, eg:

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM