
GüŸnther Schmidt wrote:
the point I wanted to stress though is that the stack overflow does actually not occur doing the recursive algorithm, just a build-up of thunks.
You can also observe this with suitable "trace" statements. For example:
import Debug.Trace import System.Environment
my_foldl f z [] = trace "o" z my_foldl f z (x:xs) = trace "^" (my_foldl f (f z x) xs)
my_plus x y = trace "+" (x + y)
main = do [n] <- getArgs print (my_foldl my_plus 0 [1..read n])
Compile and execute with suitable options, including a reduced maximum stack size. This works for me: $ ghc --make stack.hs $ ./stack 20 +RTS -K100 Also try the strict version:
my_foldl' f z [] = trace "o" z my_foldl' f z (x:xs) = trace "^" (z' `seq` my_foldl' f z' xs) where z' = f z x