前言中的幂函数 [英] power function in prolog

查看:113
本文介绍了前言中的幂函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的幂函数有什么问题?

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).

这篇关于前言中的幂函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆