简体   繁体   English

成员谓词

[英]Member predicate

When you call member(Item, List) with an uninstanciated list, Prolog unifies and returns a list containing item. 当您使用未实例化的列表调用member(Item, List)时,Prolog统一并返回包含item的列表。 I want a rule that returns true / false and does not try to unify. 我想要一个返回true / false且不尝试统一的规则。 Is there such a rule? 有这样的规则吗?

Quick answer: Use \\+ \\+ member(Item, List) . 快速解答:使用\\+ \\+ member(Item, List)

Please note that such tests often do not make a lot of sense when your programs represent logical relations. 请注意,当程序表示逻辑关系时,此类测试通常没有多大意义。

You stated that member(Item, List) "returns a list". 您说member(Item, List) “返回列表”。 Well, that is not entirely true. 好吧,这并非完全正确。 List is unified with partial lists , that is List = [Item|_Rest] ; List = [_,Item|_Rest] ; ... List部分列表统一,即List = [Item|_Rest] ; List = [_,Item|_Rest] ; ... List = [Item|_Rest] ; List = [_,Item|_Rest] ; ... List = [Item|_Rest] ; List = [_,Item|_Rest] ; ... with _Rest being an uninstantiated variable. List = [Item|_Rest] ; List = [_,Item|_Rest] ; ... _Rest是未实例化的变量。 That is, the goal member(Item, List) does not guarantee that (upon success) List is a list. 也就是说,目标member(Item, List)不能保证(成功时) List是列表。 Here is a counterexample: member(Item, List), List = [_|nonlist] 这是一个反例: member(Item, List), List = [_|nonlist]

I would use a guard, like 我会用一个警卫

is_member(E, L) :- nonvar(L), memberchk(E, L).

memberchk/2 it's a deterministic version of member/2, to be used to find if the list contains at least 1 occurrence of element. memberchk/2是member / 2的确定性版本,用于查找列表中是否至少包含1个元素。 Cannot act as a generator , but it's more efficient. 无法充当生成器 ,但效率更高。 The guard is required anyway. 无论如何都需要警卫。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM