Goal a(3, X) should return 6. Based on this code. I have converted it to Prolog code but with a problem in a recursive predicate. First two lines are for 0 and 1 to return the same value.
c=1
for i = 2 to n do
if c > i then
c=c-1
else
c=c+1
end if
end for
return c
But at Step 4 it gets the result and then goes back to step 2 and goes back with the iteration to the wrong result. I think there is a unification problem but can't find where.
a(N, N) :- N < 2, !.
a(N, X) :- a(1, 2, N, X).
Step 2.
a(C1, I, N, C1) :- I > N, !.
Step 3.
a(C, I, N, C1) :- C > I, !,
C1 is C - I,
I1 is I + 1,
a(C1, I1, N, C1).
Step 4.
a(C, I, N, C1) :- C =< I, !,
C1 is C + I,
I1 is I + 1,
a(C1, I1, N, C1).
This is the trace.
[trace] ?- a(3, X).
Call: (8) a(3, _1238) ? creep
Call: (9) 3<2 ? creep
Fail: (9) 3<2 ? creep
Redo: (8) a(3, _1238) ? creep
Call: (9) a(1, 2, 3, _1238) ? creep
Call: (10) 2>3 ? creep
Fail: (10) 2>3 ? creep
Redo: (9) a(1, 2, 3, _1238) ? creep
Call: (10) 1>2 ? creep
Fail: (10) 1>2 ? creep
Redo: (9) a(1, 2, 3, _1238) ? creep
Call: (10) 1=<2 ? creep
Exit: (10) 1=<2 ? creep
Call: (10) _1474 is 1+2 ? creep
Exit: (10) 3 is 1+2 ? creep
Call: (10) _1480 is 2+1 ? creep
Exit: (10) 3 is 2+1 ? creep
Call: (10) a(3, 3, 3, 3) ? creep
Call: (11) 3>3 ? creep
Fail: (11) 3>3 ? creep
Redo: (10) a(3, 3, 3, 3) ? creep
Call: (11) 3>3 ? creep
Fail: (11) 3>3 ? creep
Redo: (10) a(3, 3, 3, 3) ? creep
Call: (11) 3=<3 ? creep
Exit: (11) 3=<3 ? creep
Call: (11) _1486 is 3+3 ? creep
Exit: (11) 6 is 3+3 ? creep
Call: (11) _1492 is 3+1 ? creep
Exit: (11) 4 is 3+1 ? creep
Call: (11) a(6, 4, 3, 6) ? creep
Call: (12) 4>3 ? creep
Exit: (12) 4>3 ? creep
Exit: (11) a(6, 4, 3, 6) ? creep !!! SHOULD STOP HERE !!!
Exit: (10) a(3, 3, 3, 3) ? creep
Exit: (9) a(1, 2, 3, 1) ? creep
Exit: (8) a(3, 1) ? creep
X = 1 .
c=c-1should bec=c-iandc=c+1should bec=c+i. - lurker