next up previous
Next: append/3 Up: Recursion and lists Previous: Recursion

member/2

A classical example of recursion in list-processing is identifying whether some item is an element of a list. This predicate is commonly called member/2. It is true if the item is on the list, and false otherwise. The base is that situation where we can be sure that we have found the item in question on the list. The limiting case here would be if the item sought is the first one on the list. We can generalise from this to the following clause:
 member(Item, List):-
   List = [Item|Rest].
This is OK if the item sought is indeed the first item, but what if it isn't? In that case, we need to ignore the first item and proceed to check the remainder (i.e. the tail) of the list (note the use of the anonymous variable for the item we aren't interested in):
member(Item, [_|Tail]):-
   member(Item, Tail).
If the item sought is on the list, this procedure will find it, and Prolog will respond with 'yes'; if not, it will fail, and Prolog will respond with 'no'.[*] Note that, as usual with many Prolog predicates, member/2 can be used to generate solutions; if the second argument is instantiated to a list and the first is a variable, the predicate can to used to select items off the list:
|?- member(X, [a, b, c]).

X = a ? ;

X = b ? ;

X = c ? ;

no

next up previous
Next: append/3 Up: Recursion and lists Previous: Recursion
Steve Harlow 2001-11-26