
On Tue, May 06, 2003 at 05:02:56AM -0500, Galen Menzel wrote:
makeList :: IO [Int] makeList = do s <- getLine case read s of 0 -> return [] x -> do xs <- makeList return (x:xs)
I changed the if to a case so that (read s) doesn't get
called twice.
Does the compiler not optimize away identical calls? Or is it not allowed to, for some reason?
Yes, GHC will common up the repeated expression when -O is turned on.
On the other hand, if I write a function like:
long_list = [1..100000] ++ [1..100000] ++ [1..100000] ++ [1..100000]
And then run a
putStr $ unlines $ map show long_list
I would expect this to take very little memory, which would mean that the [1..100000] would need to be calculated four separate times rather than being calculated once and stored...
Well, this is one of the disadvantages of common sub-expression elimination: you have to store the result of the sub-expression between uses. It is a space/time tradeoff, and in cases like the above, a pretty poor one. But GHC does it anyway, because in most (probably all) of the cases we've seen it is a win. Cheers, Simon