正确使用 findall/3,尤其是最后一个结果参数 [英] Correct use of findall/3, especially the last result argument

查看:80
本文介绍了正确使用 findall/3,尤其是最后一个结果参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Prolog 的初学者,我正在处理一个对您来说可能很愚蠢的问题,但我真的不明白我做错了什么!好的,我有这个文件fruits.pl,里面有这样的东西:

I'm a beginner in Prolog and I am dealing with a problem that might seem stupid to you, but I really can't understand what I'm doing wrong! Ok, I have this file fruits.pl and inside that I have something like this:

fruit(apple,small,sweet).
fruit(lemon,small,nosweet).
fruit(melon,big,sweet).

我已经(在那个文件中创建了一个 coexist(X,Y) 原子来检查两个水果是否可以放在一起放在盘子里.它工作正常!但现在我无法创建一个建议(X)作为参数,一个水果并返回一个可以放在同一个盘子里的水果列表.问题是我正在尝试制作类似的东西

I have already (inside that file made a coexist(X,Y) atom that checks if two fruits can be put together in a plate. It works fine! But now I can't create a suggest(X) that takes as a parameter a fruit and returns a list of fruits that can be put together in the same plate. The thing is I was trying to make something like that

suggest(X) :- findall(Y,fruit(Y,_,_), List), coexist(X,Y).

你怎么看?每次我尝试在 swi prolog 中运行它时,都会有一个警告单例变量",当我按下

What do you think? Every time I try to run this in swi prolog there is a warning 'singleton variable' and when I press

suggest(apple).

然后它说假..对不起我的英语:/

then it says false.. sorry for my english :/

推荐答案

Prolog 中的谓词不返回任何内容.您有满足或不满足的目标,您可以将其解释为返回 truefalse.

Predicates in Prolog do not return anything. You have goals that are satisfied or not and you can interpret that as returning true or false.

您的谓词suggest(X) 应该包含另一个参数,该参数将绑定到与X 一起的水果列表.一个选项是:suggest(X, List),它描述了以下关系:List 表示与 X 一起的所有水果.然后,你可以问:

Your predicate suggest(X) should contain another parameter that will be bound to the list of fruits that go together with X. An option would be: suggest(X, List) which describes the following relation: List represents all the fruits that go together with X. Then, you could ask:

?- suggest(apple, List).
List = [pear, cherry].

目标 findall(Y, ... , ...) 在内部使用了 Y 变量并且 Y 在目标得到满足.因此,您应该将 coexist(X,Y) 移动到 findall/3 的第二个参数中,这是以所有可能的方式满足的目标.下面的规则仅在 X 被实例化时才有效(suggest(+X, -List)).

The goal findall(Y, ... , ...) uses the Y variable internally and Y is still unbound after the goal is satisfied. So, you should move coexist(X,Y) inside the second argument of findall/3 which is the goal that is satisfied in all possible ways. Th rule below works only if X is instantiated (suggest(+X, -List)).

suggest(X, List) :- findall(Y, (fruit(Y,_,_), coexist(X, Y)), List).

你可以这样读:List代表所有与X共存的水果Y".

You can read this as follows: "List represents all fruits Y that coexist with X".

这篇关于正确使用 findall/3,尤其是最后一个结果参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆