Member predicate

775 views Asked by At

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?

2

There are 2 answers

3
CapelliC On BEST ANSWER

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. Cannot act as a generator, but it's more efficient. The guard is required anyway.

2
false 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]