我试图创建一个查询 average(X, A)
如果X存在于prolog数据库中,并且A是商店内商品的平均价格,则返回true。
样品输出
?- average(best_smoothies,A).
A = 2.66667
No
Prolog数据库
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)])
无法查询商品价格?
希望得到任何帮助。非常感谢!我试图创建一个查询average(X, A),如果X在prolog数据库中存在,并且A是平均价格,则返回true。
根据输出,很明显,我没有访问商店的价格元素。为什么会这样?
store(_,_,[smoothie(_,_,C)])
无效,才能获取商品价格?
这样只能和一个只有一个顺口溜的店铺统一。
即如果你在你的KB中添加。
store(single_smothie_shop, [p1,p2,p3],
[ smoothie(berry, [orange, blueberry, strawberry], 2)]).
到你的KB,然后查询。
?-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.