Prolog电源功能

时间:2014-02-08 23:39:51

标签: function prolog exponentiation

我是Prolog的新手,虽然我能理解代码,但我觉得很难创建一个程序。我正在尝试创建一个取整数并返回2 ^(整数)示例的函数pow(4)返回16(2 ^ 4)。我还需要它在一个循环中继续输入,直到用户输入负整数然后它退出。

在这个例子中,C是计数器,X是用户输入,试图包含变量用于输出但是不能考虑如何集成它。

pow(0):- 0.
pow(1):- 2.
pow(X):-
   X > 1, 
   X is X-1,
   power(X),
   C is X-1,
   pow(X1),
   X is 2*2.
pow(X):- X<0, C is 0.
pow(C).

2 个答案:

答案 0 :(得分:2)

在尝试编程之前,你真的需要阅读一些关于Prolog的内容。例如,浏览http://en.wikibooks.org/wiki/Prolog

Prolog没有“功能”:有谓词。所有输入和输出都是通过谓词参数,谓词本身不会返回任何内容。

所以pow(0):- 0.pow(1):- 2.没有任何意义。你想要的是pow(0, 0).pow(1, 2).:让第一个参数作为输入,第二个参数作为输出。

X is X-1也没有意义:在Prolog中变量就像代数变量一样,X在整个方程组中意味着相同的值。变量基本上是一次写入,你必须在这个和类似的情况下引入新的变量:X1 is X-1

希望有足够的信息让你入门。

答案 1 :(得分:1)

[天真]递归解决方案:

pow2(0,1) .     % base case: any number raised to the 0 power is 1, by definition
pow2(N,M) :-    % a positive integral power of 2 is computed thus:
  integer(N) ,  % - verify than N is an inetger
  N > 0 ,       % - verify that N is positive
  N1 is N-1 ,   % - decrement N (towards zero)
  pow2(N1,M1) , % - recurse down (when we hit zero, we start popping the stack)
  M is M1*2     % - multiply by 2
  .             %
pow2(N,M) :-    % negative integral powers of 2 are computed the same way:
  integer(N) ,  % - verify than N is an integer
  N < 0 ,       % - verify than N is negative
  N1 is N+1 ,   % - increment N (towards zero).
  pow2(N1,M) ,  % - recurse down (we we hit zero, we start popping the stack)
  M is M / 2.0  % - divide by 2.
  .             % Easy!

但是,当递归级别足够高时(忽略算术溢出问题),上面的内容将溢出堆栈。 SO ...

尾递归解决方案优化为迭代:

pow2(N,M) :-      %
  integer(N) ,    % validate that N is an integer
  pow2(N,1,M)     % invoke the worker predicate, seeding the accumulator with 1
  .               %

pow2(0,M,M) .     % when we hit zero, we're done
pow2(N,T,M) :-    % otherwise...
  N > 0 ,         % - if N is positive,
  N1 is N-1 ,     % - decrement N
  T1 is T*2 ,     % - increment the accumulator
  pow2(N1,T1,M)   % - recurse down
  .               %
pow2(N,T,M) :-    % otherwise...
  N < 0 ,         % - if N is negative,
  N1 is N+1 ,     % - increment N
  T1 is T / 2.0 , % - increment the accumulator
  pow2(N1,T1,M)   % - recurse down
  .               %