如何使这个 Haskell 幂函数尾递归?
我如何使这个 Haskell 幂函数尾递归?
turboPower a 0 = 1
turboPower a b
| even b = turboPower (a*a) (b `div` 2)
| otherwise = a * turboPower a (b-1)
How would I make this Haskell power function tail recursive?
turboPower a 0 = 1
turboPower a b
| even b = turboPower (a*a) (b `div` 2)
| otherwise = a * turboPower a (b-1)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
基本上,您想要做的是将您在“
otherwise
”步骤中执行的乘法移动到另一个参数(因为这就是阻止尾递归的原因)。编辑添加一行,使所有三个参数严格评估,而不是惰性,因为这是惰性会伤害我们的众所周知的情况之一。
Basically, what you want to do is move the multiplication that you're doing in the "
otherwise
" step (since that's what keeps this from being tail-recursive initially) to another parameter.Edited to add a line making all three parameters strictly evaluated, instead of lazy, since this is one of those well-known situations where laziness can hurt us.