[英]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.