问题
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