Why isn't this recursive function being optimized? (Haskell)

haskell, recursion

Solution

You're probably hoping that the compiler will perform tail call optimization on your method. Unfortunately, this definition of `mySum` is not tail-call optimizable. What is required for it to be is for the last function being called to be the recursive call, so in this case you'd want `mySum` to be the last function called. However, the last function being called in your definition is `(+)`, not `mySum`. You could instead write it as @DonStewart has suggested, who managed to type out that solution before I was able to.

Problem

I wrote my own 'sum' function in Haskell: ``` mySum [a] = a mySum (a:as) = a + mySum as ``` And tested it with ``` main = putStrLn . show $ mySum [1 .. 400000000] ``` Only to receive a stack overflow error. Using the Prelude's sum in the same manner: ``` main = putStrLn . show $ sum [1 .. 400000000] ``` I get no stack overflow. It could be the huge list I'm evaluating, especially if the list passed to my function is being evaluated strictly, though my only reason for not suspecting this is that using the Prelude's sum with the same list I get no error.

Original source

Related problems