When you call member(Item, List)
with an uninstanciated list, Prolog unifies and returns a list containing item. I want a rule that returns true
/false
and does not try to unify. Is there such a rule?
Member predicate
768 views Asked by mrk At
2
There are 2 answers
2
On
Quick answer: Use \+ \+ 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". Well, that is not entirely true. List
is unified with partial lists, that is List = [Item|_Rest] ; List = [_,Item|_Rest] ; ...
with _Rest
being an uninstantiated variable. That is, the goal member(Item, List)
does not guarantee that (upon success) List
is a list. Here is a counterexample: member(Item, List), List = [_|nonlist]
I would use a guard, like
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. Cannot act as a generator, but it's more efficient. The guard is required anyway.