prologswi-prologunification

SWI-Prolog predicates member and nth1 without unification?


If I use the predicates member or the nt1 in SWI-Prolog as follows:

?- member(X, [A]).
X = A.

or

nth1(N, [A], X).
N = 1,
A = X.

The interpreter unifies the variable A as X.

Is their some alternative version of this functions which does not use the unification. Means, if I call something like this:

?- _member(X, [A]).

it would give

 false

as long as the call is not

?- member(X, [X]).

which would lead to

true

And in the same way

_nth1(N, [A], X).

would give false

but

_nth1(N, [X], X).

would give

N = 1

Solution

  • Seems like you just need to roll your own using ==/2 instead of =/2:

    See https://swish.swi-prolog.org/p/DqhYGuEf.pl

    is_member_of( X , [Y|_]  ) :- X == Y .
    is_member_of( X , [_|Ys] ) :- is_member_of(X,Ys) .
    
    is_nth0( N , L , E ) :- is_nth(0,L,E,N) . 
    
    is_nth1( N , L , E ) :- is_nth(1,L,E,N) .
    
    is_nth( N , [Y|_]  , X , N ) :- X == Y .
    is_nth( I , [_|Ys] , X , N ) :- J is I+1, is_nth(J,Ys,X,N) .