Sunday, February 15, 2009

Adventures in Prolog - Simple computations

This time I present a way to calculate the ith power of some integer j (i is also an integer number). Clearly, this is nothing too sophisticated but it will be helpful for some other program, I want to show later on.

Power is implemented as a simple ternary relation, which uses recursion. The base cases for power are of course the 0th and 1st power of some integer number. All other powers will be dependant on this anchor. The ith power of j means that j is multiplied with itself i times. For instance, the 3rd power of 2 is eigth, which is 2 * 2 * 2 = 8. This is used to implement the recursive core of power, which is ith power of j is the j * (i-1)th power of j.

After the basic power relation, power10 and power2 show how to use existing relations to implement some simple abstractions.


%power/3
power(X, 0, 1).
power(X, 1, X).
power(X, Y, Z) :-
Y1 is Y - 1,
power(X, Y1, Z1),
Z is X * Z1.

%power10/2
power10(P, R) :- power(10, P, R).
%power2/2
power2(P, R) :- power(2, P, R).

No comments: