Retrieve Items in Prolog

|▌冷眼眸甩不掉的悲伤 提交于 2020-12-13 07:46:29

问题


Say I have this knowledge base:

step('pancakes', 1, 'mix butter and sugar in a bowl', [butter, sugar], [bowl]). 
step('pancakes', 2, 'add eggs', [eggs], []). 
step('pancakes', 3, 'mix flour and baking powder', [flour, baking powder], []).

How do I make a predicate that retrieves all the ingredients for all the steps of the recipe?

So if I would make a rule retrieveIngredients(X,Y). and ask retrieveIngredients('pancakes',Y)., how would I be able to make it retrieve Y = ['butter','eggs','flour', 'baking powder'].?


回答1:


Simply using findall/3:

retrieveIngredients(R,Y):-
    findall(A,step(R,_,_,A,_),Y).

?- retrieveIngredients('pancakes',Y).
Y = [[butter, sugar], [eggs], [flour, baking_powder]]

If you want to get the list flattened, add a call to flatten/2. If you want to remove duplicates, add a call to sort/2. Note that you need to rewrite baking powder as baking_powder (without space) in the third step/5 fact.



来源:https://stackoverflow.com/questions/64914187/retrieve-items-in-prolog

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!