I am a bit confused about this function definition in Prolog:
sample(X,[X|Tail]) :- member(X,Tail).
this function checks if X is at the first position of the given list and if X is also found in the tail of the list.
sample(1,[1,2,3]).
false.
% because 1 is not found in the tail
sample(1,[1,2,1]).
true.
But how does it work? X is the parameter given by the user but it seems to be overwriten by the head|tail extraction from the list. So it seems X new value is the first element in the list.
You’re thinking too hard. In the first case:
Prolog is able to bind X, because 1 is 1:
Prolog then checks the body of the clause:
This is obviously false, so
sample(1, [1,2,3])doesn’t succeed.In the next case, the binding still works, but Tail is bound to something else:
So we check the body:
which is obviously true, so
sample(1, [1,2,1])succeeds.Now, if you were to try this call:
You’ll still get false, because in this case, 1 isn’t equal to 2, so there’s no way to bind X at the beginning, so the body never gets checked.
sample(1, [2,3,1])is false even though 1 appears in both places, because it didn’t appear at the beginning of the list as well.I have no idea why you’d want such a function, but it is working as one would expect. There’s no overwriting of variables happening here.