Power function in prolog
Exactly what's the Prolog definition for power function. I w开发者_如何学编程rote this code and it give some errors I wanna know exact code for the power function.
pow(X,0,1).
pow(X,Y,Z):-Y1=Y-1,pow(X,Y1,Z1),Z1=Z*X.
Anything wrong with this code?
There are two problems with the code.
- To do arithmetics in prolog you have to use is/2 instead of =
- The variables in the multiplication had to be swapped (Z is Z1*X)
- You should place a guard to ensure that the exponent is positive, otherwise you can have situations where the program won't terminate
Here is the fixed code:
pow(_,0,1).
pow(B,E,R) :- E > 0,!, E1 is E -1, pow(B,E1,R1), R is B * R1.
Here is a second, tail recursive version using an accumulator
powa(B,E,R) :- powa(B,E,1,R).
powa(_,0,A,A).
powa(B,E,A,R) :- E > 0, !, E1 is E - 1, A1 is B * A, powa(B,E1,A1,R).
Have a look here - power function in prolog. The built-in pow predicate is not implemented in prolog for efficiency reason - as most arithmetic predicates.
精彩评论