[英]Sum Calculation in Prolog
假设我在Prolog中有两个“表”,例如:
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)
我该怎么办? 我无法全神贯注地在Prolog中进行编码。
提前致谢!
尝试以下代码:
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.