如何使这个 Haskell 幂函数尾递归?
turboPower a 0 = 1
turboPower a b
| even b = turboPower (a*a) (b `div` 2)
| otherwise = a * turboPower a (b-1)
如何使这个 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)
基本上,您想要做的是将您在“ otherwise
”步骤中所做的乘法(因为这就是阻止它最初是尾递归的原因)移动到另一个参数。
编辑添加一行严格评估所有三个参数,而不是懒惰,因为这是众所周知的懒惰会伤害我们的情况之一。