Reputation: 6756
I don't understand, why the second doesn't work. I thought in first example, the II variable isn't needed, but looks like it is, but i don't know why?
If i call findex([1,2,5,4], 5, I)
, than first example returns correct index 3
and second returns false
. Can somebody help me to understand it?
findex([X|_], X, 1).
findex([_|T], MAX, INDEX) :- findex(T, MAX, II), INDEX is II +1.
findex([X|_], X, 1).
findex([_|T], MAX, INDEX) :- findex(T, MAX, INDEX), INDEX is INDEX +1.
Upvotes: 0
Views: 50
Reputation: 7209
The second example will not work.
The key thing to understand is that both INDEX
s in INDEX is INDEX +1
are the same, they must have the same value. It's like variables in algebra - all Xs in an equation means the same value.
Another way to think of it is that all variables in Prolog are "assign once" variables: after a variable has its value it can't be changed without backtracking.
Upvotes: 2