[Haskell-cafe] reversing big list with constant heap space used

Sergey Perminov sv.perminov at gmail.com
Wed May 16 03:09:28 EDT 2007


How to solve task of reversing big list with constant heap space used?

Amount of heap space used grows exponentially in following examples:

1:
main = putStrLn.show.head $reverse [1..10000000]

2 (GHC):
import Data.List
main = putStrLn.show.head $foldl' (flip (:)) [] [1..10000000]

3 (GHC):
import Control.Monad
main = foldM (\x y -> return $ y:x) [] [1..10000000] >>= putStrLn.show.head

-- 
Best regards,
Sergey Perminov


More information about the Haskell-Cafe mailing list