Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

power function in prolog

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
like image 953
TheOne Avatar asked Sep 19 '09 15:09

TheOne


People also ask

How do you write power in Prolog?

power(X,P,F):-X>0,P1=P-1,power(X,P1,F1),F=X*F1.

What is the syntax of power function?

Syntax: double pow(double x, double y); Parameters: The method takes two arguments: x : floating point base value.

What are functions in Prolog?

Defining four functions (it's called predicates in prolog), addition, subtraction, multiplication, and division. Each of them takes three parameters, the result is saved to the third parameter.


2 Answers

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).
like image 67
ebo Avatar answered Sep 18 '22 02:09

ebo


Predicates
fac(Integer,Integer,Integer).
Clauses
fac(X,N,X):- N=1,!.
fac(X,N,M):- N1=N-1,fac(X,N1,M1), M= X*M1.
Goal
fac(5,3,X).
like image 21
Maik Avatar answered Sep 19 '22 02:09

Maik