首页 > 解决方案 > 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)])无法访问商品价格?

将不胜感激任何帮助。非常感谢!

标签: prolog

解决方案


根据输出,很明显我没有访问商店
价格元素。为什么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.


推荐阅读