prolog - Prolog - 递归访问列表的列表元素并获取总和
问题描述
我正在尝试创建一个查询average(X, A)
,如果 X 存在于 prolog 数据库中并且 A 是商店内商品的平均价格,则返回 true
样本输出
?- average(best_smoothies,A).
A = 2.66667
No
序言数据库
store(best_smoothies, [alan,john,mary],
[ smoothie(berry, [orange, blueberry, strawberry], 2),
smoothie(tropical, [orange, banana, mango, guava], 3),
smoothie(blue, [banana, blueberry], 3) ]).
store(all_smoothies, [keith,mary],
[ smoothie(pinacolada, [orange, pineapple, coconut], 2),
smoothie(green, [orange, banana, kiwi], 5),
smoothie(purple, [orange, blueberry, strawberry], 2),
smoothie(smooth, [orange, banana, mango],1) ]).
store(smoothies_galore, [heath,john,michelle],
[ smoothie(combo1, [strawberry, orange, banana], 2),
smoothie(combo2, [banana, orange], 5),
smoothie(combo3, [orange, peach, banana], 2),
smoothie(combo4, [guava, mango, papaya, orange],1),
smoothie(combo5, [grapefruit, banana, pear],1) ]).
我的尝试:
numSmoothie([_|T],X) :- numSmoothie(T,A), X is A+1.
numSmoothie([], 0).
priceSmoothie([_|T],X) :- priceSmoothie(T,A), X is A+1.
priceSmoothie([], 0).
average(X, A) :- store(X,_,S),
numSmoothie(S, SmoothieCount),
writeln("Number of smoothies is: "),
writeln(SmoothieCount),
store(_,_,[smoothie(_,_,C)]),
priceSmoothie(C, SmoothiePrice),
writeln("Total price of smoothies is: "),
writeln(SmoothiePrice),
A is SmoothiePrice / SmoothieCount.
我可以通过简单地计算每个 S 来获得列表中的项目数。但是,我似乎无法访问列表的列表元素(也就是价格)并能够将其作为一个整体进行总结.
我得到的输出
?- average(smoothies_galore, A).
Number of smoothies is:
5
false.
根据输出,很明显我没有访问商店价格元素。为什么store(_,_,[smoothie(_,_,C)])
无法访问商品价格?
将不胜感激任何帮助。非常感谢!
解决方案
根据输出,很明显我没有访问商店
价格元素。为什么store(_,_,[smoothie(_,_,C)])
无法
访问商品价格?
这只会与只有一个冰沙的商店统一。
即,如果您添加:
store(single_smothie_shop, [p1,p2,p3],
[ smoothie(berry, [orange, blueberry, strawberry], 2)]).
到您的知识库,然后查询:
?-store(What,_,[smoothie(_,_,C)]).
C = 2,
What = single_smothie_shop.
这是该查询的唯一结果。
获得所需内容的一种方法是使用查询:
?-store(Store,_,Smothies), aggregate(r(count,sum(Price)),S^N^member(smoothie(S,N,Price),Smothies),r(Count,TotalPrice)), Average is TotalPrice/Count.
推荐阅读
- flutter - 输入'未来
' 不是类型 'Stream 的子类型 - php - MongoDB PHP 错误:警告:未定义属性:MongoDB\Driver\Manager
- javascript - 将数字转换为单词,但不能使用重复的数字进行转换
- .net - 如何向具有获取属性的类提供数据以进行单元测试
- laravel - 在 Safari 浏览器中从 iOS 移动设备上的 Facebook Messenger 链接重定向时,网站显示空白页
- mongodb - docker-compose 上带有用户密码的 graylog mongdb 配置
- apache-kafka - 融合云kafka集群如何扩容?
- java - 如何忽略一些 Java 的 Files.lines 行尾分隔符
- flutter - 为什么“设置类型的值
' 无法从方法 'toHive' 返回,因为它的返回类型为 'ShProblemHive'。” - ios - Xamarin Forms:防止键盘调整视图大小