在Prolog中,如何检查列表B中列表A中的N个元素?
我有这两个列表 =
fruits([banana, apple, mangoes, pears]).
foodILike([hamburgers, banana, shakes, fries]).
我想编写一个序言谓词,一旦看到水果列表中的 foodIlike 列表中的 1 个项目,该谓词就会返回 true。我该如何去做呢?
I have these two lists =
fruits([banana, apple, mangoes, pears]).
foodILike([hamburgers, banana, shakes, fries]).
I want to write a prolog predicate that will return true as soon as it sees 1 items in the foodsILike list in the fruits list. How can I go about doing so?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,对于简单的答案:
您可以通过展平水果和食物列表来避免成员资格检查:
也就是说,您似乎尝试使用命令式习语解决 Prolog 中的问题,但这行不通。首先,谓词不返回任何内容。当调用谓词时,Prolog 根据程序中的事实和规则将其参数与有效值统一起来。因此,“返回值”是对未绑定变量的赋值。其次,Prolog 不会“尽快”做某事。它迭代所有可能的解决方案。您会得到第一个解决方案,然后是第二个解决方案,依此类推。
First, for the plain answer:
You could avoid the membership check by flattening the fruits and foods lists:
That said, you seem to try and solve problems in Prolog using imperative idioms, and that won't work. First, predicates do not return anything. When calling a predicate, Prolog unifies its arguments with valid values according to the facts and rules in the program. Therefore, the "returned value" are the assignments to unbound variables. Second, Prolog does not do something "as soon as". It iterates over all possible solutions. You get the first solution, then the second solution, and so on.
member
可以 1) 单独生成给定列表的所有成员和/或 2) 对于特定元素是否在特定列表中给出是/否答案。我相信您想使用fruits
上的第一个表单来生成fruits
的每个元素,并使用foodILike
上的第二个表单来查看是否其中任何一个都存在。member
can 1) individually generate all the members of a given list and/or 2) give a yes/no answer as to whether a particular element is in a particular list. I believe you want to use the first form onfruits
to generate each of the elements offruit
, and the second form onfoodILike
to see if any of those is present.