Importance for a rigorous estimate in the tail recursive definition of a power function

I understand this function and tail recursion, but I cannot understand why strict evaluation is important. Without a rigorous evaluation, it would still be tail-recursive, right? So, when will this function fail without a rigorous evaluation?

turboPower ab = turboPower' 1 ab where turboPower' xa 0 = x turboPower' xab | x `seq` a `seq` b `seq` False = undefined | even b = turboPower' x (a*a) (b `div` 2) | otherwise = turboPower' (x*a) a (b-1) 
+4
source share
1 answer

It will not fail (if the exponent is not huge, so the volume can become large enough to fill the stack), it will (maybe) be less effective, because without a strict assessment, the arguments become loud, which leads to

 turboPower' (let xN = let x(N-1) = ...; a(N-1) = ... in x(N-1)*a(N-1)) (let aN = let a(N-1) = ... in a(N-1)*a(n-1)) (let bN = ...) 

It should not be too dramatic, since the level of nesting is logarithmic in the exponent and, thus, remains small for all practical calculations, but this can be of great importance, for example, in

 foo :: Integer -> Integer foo n = go 0 n where go acc m | m < 1 = acc | otherwise = go (acc + m^3 + m `mod` 7) (m-1) 

where the nesting level is linear in n .

+5
source

Source: https://habr.com/ru/post/1437977/


All Articles