简体   繁体   English

Prolog中的总和计算

[英]Sum Calculation in Prolog

Say I have two 'tables' in Prolog, eg: 假设我在Prolog中有两个“表”,例如:

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) 现在,我想编写一个谓词来计算购物车内商品的总和,例如total_sum(Person,Sum)

How would i do this? 我该怎么办? I can't wrap my head around coding this in Prolog. 我无法全神贯注地在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).

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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