prolog中的幂函数 [英] power function in prolog
本文介绍了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
推荐答案
你的 Y 没有递减,你不能使用函数之类的谓词.您还必须将 Z 与乘法的结果统一.
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.
还要注意 pow 不是最后一次调用,不能优化为只使用一个堆栈帧.您应该将其重新表述为:
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).
这篇关于prolog中的幂函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文