Input Processing Loops in Haskell

Keith Wansbrough Keith.Wansbrough@cl.cam.ac.uk
Tue, 13 Nov 2001 17:59:19 +0000


Simon writes:

> You can paraphrase this in Haskell, in the IO monad, like this:
> =

>    loop =3D do {
> 	a <- get_input;
> 	if (a =3D=3D gET_OUT) then return () else loop;
>      }
> =

> In GHC this won't grow any stack each time around the loop, even with
> optimisation off.  It depends on the actual implementation of the IO
> monad, but I imagine the other Haskell implementations will also have
> this property.

It's worth adding that Mark's initial code,

  f a =

   | a =3D=3D GET_OUT   =3D a
   | otherwise      =3D f ( g a)

will also not grow the stack, on any decent Haskell implementation.  Tail=
 recursion is always implemented properly here - tail recursion simply me=
ans that the result of the function is the result of the recursive call t=
o the function, i.e., no more computation need be done once the result of=
 the recursive call is known.

http://wombat.doc.ic.ac.uk/foldoc/foldoc.cgi?tail+recursion

Of course, laziness may well bite you and you may run out of *heap*, but =
that's another story for another evening!

--KW 8-)
-- =

Keith Wansbrough <kw217@cl.cam.ac.uk>
http://www.cl.cam.ac.uk/users/kw217/
University of Cambridge Computer Laboratory.