Background
I need to write a predicate eval(P,A,R), where:
P represents a list of polynomial coefficients, i.e. 1+2x+3x^2 is represented as [1,2,3].
A represents the value for X.
R is the result of the polynomial at X=A.
Example: eval([3,1,2],3,R) produces R = 24. *edit, previously incorrect example
I am trying to use accumulators from this article and example on Learn Prolog Now.
My Algorithm:
0. Initialize result and exponent variables to 0.
1. Take the head of the list.
2. Multiply the head of the list by A^(exponent).
3. Update result and exponent.
My code:
eval(P,A,R) :- accEval(P,A,0,0,R).
accEval(([H|T]),A,Pow,Accres,R) :-
Rnew is (Accres+H*(A**Pow)),
Pownew is Pow+1,
R = Accres,
accEval(T,A,Pownew,Rnew,Rnew). % *See below
accEval([],A,Pow,Accres,Accres).
% *Previously, when the second Rnew in this line was R instead, output was "no".
Produces trace:
| ?- eval([1,2],3,R).
1 1 Call: eval([1,2],3,_20) ?
2 2 Call: accEval([1,2],3,0,0,_20) ?
3 3 Call: _126 is 0+1*3**0 ?
3 3 Exit: 1.0 is 0+1*3**0 ?
4 3 Call: _157 is 0+1 ?
4 3 Exit: 1 is 0+1 ?
5 3 Call: accEval([2],3,1,1.0,1.0) ?
6 4 Call: _218 is 1.0+2*3**1 ?
6 4 Exit: 7.0 is 1.0+2*3**1 ?
7 4 Call: _249 is 1+1 ?
7 4 Exit: 2 is 1+1 ?
8 4 Call: accEval([],3,2,7.0,7.0) ?
8 4 Exit: accEval([],3,2,7.0,7.0) ? % We have the correct answer.
5 3 Exit: accEval([2],3,1,1.0,1.0) ? % Wait! What are you doing!?
2 2 Exit: accEval([1,2],3,0,0,0) ? % Why is this falling back out?
1 1 Exit: eval([1,2],3,0) ?
R = 0 % Incorrect. The answer should be 7.
As noted in my code, previous attempts have produced no value for R, instead producing "no" or in other implementations "yes".
Question
Why is the result lost and not carried back to the original call?