我的 Prolog 文件中的数据库如下所示 ->
stage('crepe',2,'Stir the items into a consistent dough.',[],['pot','blender']).
我想使用下面的查询并得到这个结果 ->
?- equipmentStage(‘crepe’, ‘blender’, Y).
Y = [‘Stir the items into a consistent dough.’] .
我尝试使用以下代码,但是当我尝试查询时,它返回一个空列表。所以 Prolog 断定不存在这样的东西。而当我在数据库中尝试使用列表的第一个元素“pot”进行查询时,它会返回正确的输出。 ->
equipmentStage(Food,Equipment,StageTxt):-
findall(Txt, stage(Food, _, Txt, _, [Equipment]),StageTxt).
所以我的问题是如何使用列表中的第二项也获得正确的结果?我是 Prolog 的新手,非常感谢您的帮助!
最佳答案
这是我使用 findall
(以及类似的谓词,如 setof
或 bagof
)的两个主要规则:
- 不要使用
findall
。您可能不需要结果列表。回溯结果通常是您想要的。定义一个谓词,通过回溯枚举您的解决方案。 - 如果您真的想要一个列表(您可能不需要),请按以下步骤进行:从步骤 1 中获取谓词定义。对其应用
findall
;永远不要将复杂的查询放入findall
。
因此对于您的问题,第 1 步:
food_equipment_stage(Food, Equipment, Stage) :-
stage(Food, _, Stage, _, Equipments),
member(Equipment, Equipments).
这给出了一个单一的答案:
?- food_equipment_stage(crepe, blender, Stage).
Stage = 'Stir the items into a consistent dough.'.
有了更大的知识库,这将逐一列举答案。
您是否绝对确定您需要一个列表,而您很可能不需要?如果是(但可能不是),则在第 2 步中很容易将 findall
应用于第 1 步中的定义(但您可能甚至不想这样做):
food_equipment_stages(Food, Equipment, Stages) :-
findall(Stage, food_equipment_stage(Food, Equipment, Stage), Stages).
这给了你一个列表:
?- food_equipment_stages(crepe, blender, Stages).
Stages = ['Stir the items into a consistent dough.'].
关于prolog - 遍历整个列表并检查 Prolog 中是否存在项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64941772/