0
votes

I have multiple recursions in Prolog but when i do similar recursion to pow in result block it says:

is/2: Arguments are not sufficiently instantiated.

pow(_,0,1):-!.
pow(X,N,XN):-
    N>0,
    N1 is N - 1,
    pow(X, N1, XN1),
    XN is XN1 * X.

result(_,0,_):-!.    
result(X, N, Res):-
    N2 is N - 1,
    N1 is 2*N - 1,
    pow(X, N1, Numer),
    pow(-1, N2, One),
    writeln('before'),
    result(X, N2, RS1),
    writeln('after'),
    writeln('RS1: ' + RS1),
    Res is RS1+One*(Numer/N1).
2

2 Answers

0
votes

It's probably for the reason that because

result(_,0,_):-!.

is true for any 3rd (and 1st) argument where 2nd one is 0, so in

result(X, N2, RS1)

the RS1 variable cannot be computed when N2 is 0. (It's just like to ask a question to find x when 0 * x = 0 is given, for example.)

If you fix the value for RS1 when N2=0, e.g. using a conditional like this

(N2 =:= 0 -> RS1 is 1; result(X, N2, RS1)),

it will work.

0
votes

A common pattern in Prolog is the use of helper predicates with an accumulator.

Xn is repeated multiplication. It's shorthand for 1 * X * X ..., repeated n times, correct? And that gives you the prolog predicate you need.

Try something like this:

% ---------------------------------------------------------
% pow/3 — Our public predicate to raise X to the Nth power,
% unifying the result with R 
% ---------------------------------------------------------
pow( X , N , R ) :-
  pow(X,N,1,R)
  .

% --------------------------------------------------------------
% pow/4 — Our private helper predicate
%
% It also raised X to the Nth power, but uses an accumulator, T,
% in which to accumulate the result.
% --------------------------------------------------------------
pow( _ , 0 , R , R ) .  % Once we hit the 0th power, we're done: just unify the accumulator with R.
pow( X , N , T , R ) :- % To evaluate X to the Nth power...
  N > 0,                % 0. For non-negative, integral values of N.
  T1 is T * X,          % 1. Multiple the accumulator by X
  N1 is N-1,            % 2. Decrement the power N by 1
  pow(X,N1,T1,R)        % 3. Recursively evaluate X to the N-1th power
  .                     % Easy!