member(
?Element,
?List)
member(
?Element,
?List)
is true when List is a (possibly partial) list, and Element is one of
its elements. It may be used to check whether a particular element
occurs in a given list, or to enumerate all of the elements of a list
by backtracking. member/2
may also be used to generate a list.
| ?- member(a, [b,e,a,r]). yes | ?- member(e, [s,e,e,n]). yes /* this will succeed twice */ | ?- member(e, [t,o,l,d]). no | ?- member(X-Y, [light-dark,near-far,wet-dry]). X = light, Y = dark ; X = near, Y = far ; X = wet, Y = dry | ?- member(a-X, [b-2,Y-3,X-Y]). X = 3, Y = a ; X = a, Y = a | ?- member(a, L), member(b, L), member(c, L), | length(L, N). L = [a,b,c], N = 3
The last example will generate
lists of increasing length whose first three members are a
, b
, and c
.
If L is a proper list of length n, member(
X,
L)
has at most n solutions, whatever X is. But if
L is a partial list, member/2
will backtrack indefinitely,
trying to place X ever farther to the right. For example,
| ?- member(a, L). L = [a|_879] ; L = [_878,a|_881] ; L = [_878,_880,a|_883] ; . . .
until you stop it.
In general, you should only use member/2
when the second argument
is a proper list. This list need not be ground; however, it must not
end with a variable.