I have the next function from the book:
% Signature: select (X,HasXs,OneLessXs)/3
% purpose: The list OneLessXs is the result of removing
one occurrence of X from the list HasXs.
select(X,[X|Xs],Xs). *rule number 1*
select(X,[Y|Ys],[Y|Zs]) :- select(X,Ys,Zs). * rule number 2*
?- select(4,[2,3,2,4,5,2,4],X].
X=[2,3,2,5,2,4]
But I didn’t understand how it finds the correct answer. After it removes all the Y=!X, It come to a rule number 1, with: Xs=4,5,2,4, then it return true. and what then? If it continue to rule 2, then he also remove the next “4”. If it doesn’t continue to rule 1, then How Zs is [2,3,2,5,2,4]? I think Im missing a basic rule.
You can understand why this is happening by thinking of how it’s going to be executed.
So you have:
First, it will check rule 1, but
4 != 2so it will continue to rule 2. At rule 2, you have these “bindings”:And
Kis binded to[2 | Zs]and not justZs. The nextselectcall which will beselect(4, [3, 2, 4, 5, 2, 4], Zs)findsZsand so on. That’s why the returned result is:K=[2,3,2,5,2,4]and notK=[5, 2, 4]as you was expecting.