无法做简单的Prolog

时间:2019-05-20 06:12:33

标签: prolog

我在Prolog中有多个递归,但是当我对结果块中的pow执行类似的递归时,它会说:

  

is / 2:参数没有被充分实例化。

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 个答案:

答案 0 :(得分:0)

可能是因为

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

适用于 any 第3个(和第1个)参数,其中第二个为0,所以在

result(X, N2, RS1)

RS1为0时,无法计算N2变量。(就像问一个问题,当 0 * x = 0 <时,找到 x / strong>。)

如果您在RS1时固定N2=0的值,例如使用这样的条件

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

它将起作用。

答案 1 :(得分:0)

Prolog中的常见模式是使用 helper 谓词和 accumulator

X n 重复乘法。它是1 * X * X ...的简写,重复 n 次,对吗?这为您提供了所需的序言谓语。

尝试这样的事情:

% ---------------------------------------------------------
% 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!