4

How can I code member/2 that has determinism for the last element. Currently I am using:

member(X,[X|_]).
member(X,[_|Y]) :- member(X,Y).

When I query the following:

?- member(X,[1,2]).
X = 1 ;
X = 2 ;
No

The interpreter continues searching after returning 2 since there is still a choice point left. How could I implement member/2 so that this does not happen anymore?

But the full semantic of member/2 should be preserved, i.e. answers such as:

 ?- member(X,Y)
 Y = [X|_1] ;
 Y = [_1,X|_2] ;
 etc..

Should still work as befor.

Bye

  • 1
    Well it would ripple to other predicates. When member is deterministic for the last element, then other predicates that use member do also get more deterministic. Determinism is good since it allows the Prolog interpreter to trim the environment and perform garbage collection. –  Dec 08 '11 at 20:19
  • 1
    seems like you can go look at swi pl's member/2, it's deterministic on the last element. – m09 Dec 08 '11 at 20:33

1 Answers1

3
member(B, [C|A]) :-
    member_(A, B, C).
member_(_, A, A).
member_([C|A], B, _) :-
    member_(A, B, C).

Is the result of two listing calls on swi.

m09
  • 7,490
  • 3
  • 31
  • 58