Information Technology Reference
In-Depth Information
If L is a nonempty list, and the variable X is not instantiated, the member(X,L) query
will succeed, with X getting the head of the list as its value. If the query p(X) then
fails, the program will backtrack, and X will be assigned to the next element of the
list, and so on, until an element of L is found for which p(X) succeeds. Here is an
example of this generate-and-test in a query:
?- member(N,[1,2,3,-3,5,-5,7]),N<0.
N=-3 ;
% The first element that is < 0
N=-5 ;
% The second element that is < 0
No
However, when using list predicates to generate values in this way, one must be
careful not to generate an infinite set of candidates. Consider the following:
?- member(3,L). % What list has 3 as an element?
L = [3|_G214] ; % Any list whose first element is 3,
L = [_G213, 3|_G217] ; % any list whose second element is 3,
L = [_G213, _G216, 3|_G220] % and so on.
Yes
?- member(3,L), 1=2.
ERROR: Out of global stack
% This query causes an error.
In the second query, each time the subquery 1=2 , fails, the program backtracks to try
to find a new value for L . Since there will always be another value to consider (that is,
a bigger list), the process runs until L gets so large that it causes an error. This caveat
aside, variables can be used in either argument of the member predicate:
?- member(a,[X,b,Y]).
X = a,
Y = _G163
;
X = _G157,
Y = a
;
No
?- L=[a,X,b], member(3,L).
L = [a, 3, b],
X = 3
;
No
?- L=[X,b,Y], member(a,L), member(X,[b,c]).
L = [b, b, a],
X = b,
Y = a
;
L = [c, b, a],
X = c,
Y = a
;
No
So unlike numbers, variables that are not instantiated can be used within lists. Prolog
finds their values when it needs to.
 
Search WWH ::




Custom Search