Thursday, October 08, 2009

Haskell strictness

The following Haskell program eats 2GB of memory in about 5 seconds:

index n i (x:xs) = if x == n then i else index n (i+1) xs
main = putStrLn $ show $ index 0 0 [1..]

This seemed odd to me, since it is tail recursive.  The problem is that the i+1 does not get evaluated, and therefore creates a thunk at each recursion step.  Compiling with -O2 fixes this, as does the following fix

index n i (x:xs) = i `seq` if x == n then i else index n (i+1) xs
main = putStrLn $ show $ index 0 0 [1..]

This simple example just shows how you really have to unlearn your most fundamental strict functional  programming beliefs if you start hacking Haskell.

No comments:

Post a Comment