writing a function to build a list of ints from user input
Tue, 6 May 2003 07:22:20 -0400
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?
I agree that the case looks nicer, and would do it in general, but have
often wondered how hard the compilers try (or are allowed to try... as it
might mess up space usage) to optimize away multiple identical calls.
Basically, if I write:
thrice_length s = length s + length s + length s
(A very stupid example...)
Is my program really going to run length s three times, or will it just
call it once (assuming I have full optimizations on)? I would have thought
that one of the major advantages of a purely functional language would be
that the compiler could safely eliminate common subexpressions, since it
knows that they will always be identical.
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...