简体   繁体   English

你如何使这个Haskell幂函数尾递归?

[英]How do you make this Haskell power function tail recursive?

How would I make this Haskell power function tail recursive? 我如何使这个Haskell幂函数尾递归?

turboPower a 0 = 1
turboPower a b
    | even b = turboPower (a*a) (b `div` 2)
    | otherwise = a * turboPower a (b-1)
turboPower a b = turboPower' 1 a b
  where
    turboPower' x a 0 = x
    turboPower' x a b
        | x `seq` a `seq` b `seq` False = undefined
        | even b = turboPower' x (a*a) (b `div` 2)
        | otherwise = turboPower' (x*a) a (b-1)

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. 基本上,你想要做的是在“ otherwise ”步骤中移动你正在进行的乘法(因为这是使得这不能最初是尾递归的)到另一个参数。

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. 编辑添加一行,使所有三个参数严格评估,而不是懒惰,因为这是众所周知的懒惰会伤害我们的情况之一。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM