正确使用 findall/3,尤其是最后一个结果参数

编程入门 行业动态 更新时间:2024-10-09 23:21:09
本文介绍了正确使用 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 中的谓词不返回任何内容.您有满足或不满足的目标,您可以将其解释为返回 true 或 false.

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,尤其是最后一个结果参数

本文发布于:2023-06-06 10:50:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/539044.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:尤其是   正确   参数   findall

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!