tags:

views:

910

answers:

2

What is wrong with my power function?

pow(_,0,1).

pow(X,Y,Z) :-
    pow(X,Y-1,X*Z).

?- pow(2,3,Z). ERROR: Out of global stack

+6  A: 

Your Y does not get decremented, you can not use predicates like functions. You also have to unify Z with the result of the multiplication.

pow(_,0,1).

pow(X,Y,Z) :- Y1 is Y - 1,
              pow(X,Y1,Z1), Z is Z1*X.

There is also a builtin power function which will be much faster:

pow2(X,Y,Z) :- Z is X**Y.

Also note that pow is not a last call and can not be optimized to use only one stack frame. You should reformulate it to:

pow3(X,Y,Z) :- powend(X,Y,1,Z).

powend(_,0,A,Z) :- Z is A.
powend(X,Y,A,Z) :- Y1 is Y - 1, A1 is A*X, powend(X,Y1,A1,Z).
ebo
Well the point of doing this myself is to learn Prolog. :)
Absolute0
Try solving http://projecteuler.net problems in prolog...
ebo
A: 

could you please explain why pow is not good enough? thanx

crash