Item
is a member of
a list or not. This might be written as:
member(Item, [Item|_]). member(Item, [_|List]) :- member(Item, List). |
Item
and the list are ground. In
such cases, the above predicate does indeed check if Item
occurs in
the list given as a second argument. However, if either of the arguments are
not ground, then potentially unexpected behaviour might occur. Consider
the case where Item
is a variable, then the above predicate will
enumerate the elements of the list successively through backtracking. On
the other hand, if any of the list elements of the list is a variable, they
would be unified with Item
. Other instantiation patterns for either
arguments can produce even more complex results. Item
is a member of
a list, this can be done by:
% is_member(+Element, +List) % check if Element is an element that occurs in a List of % ground elements is_member(Item, [Element|_]) :- Item == Element. is_member(Item, [_|List]) :- nonvar(List), is_member(Item, List). |
is_member/2
example,
the predicate can be coded using the cut, as follows:
is_member(Item, [Element|_]) :- Item == Element, !. is_member(Item, [_|List]) :- nonvar(List), is_member(Item, List). |
is_member(Item, [Element|List]) :- ( Item == Element -> true ; nonvar(List), is_member(Item, List) ). |