writing a function to build a list of ints from user input

Simon Marlow simonmar@microsoft.com
Tue, 6 May 2003 17:12:26 +0100


=20
> On Tue, May 06, 2003 at 05:02:56AM -0500, Galen Menzel wrote:
> >=20
> > makeList :: IO [Int]
> > makeList =3D do s <- getLine
> > 	      case read s of
> > 		0 -> return []
> > 		x -> do xs <- makeList
> > 			return (x:xs)
> >=20
> > I changed the if to a case so that (read s) doesn't get=20
> called twice.
>=20
> Does the compiler not optimize away identical calls? Or is it=20
> 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:
>=20
> long_list =3D [1..100000] ++ [1..100000] ++ [1..100000] ++ [1..100000]
>=20
> And then run a
>=20
>  putStr $ unlines $ map show long_list
>=20
> I would expect this to take very little memory, which would=20
> mean that the
> [1..100000] would need to be calculated four separate times=20
> 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