[Haskell-cafe] How to print a string (lazily)

Wolfgang Jeltsch wolfgang at jeltsch.net
Tue Jan 3 17:12:36 EST 2006

Am Dienstag, 3. Januar 2006 19:15 schrieb Daniel Carrera:
> Neil Mitchell wrote:
> > All Haskell functions are lazy, hence there is no need to "write a
> > lazy version" of your print_list function. I think the function you
> > probably want is:
> >
> > putStr (unlines xs)
> Hhmm... that does work, and I'm a bit surprised that it does. I guess
> I'm still stuck in the eager computation mindset. I would expect putStr
> to have to wait for the (unlines xs) to be finished before doing any
> printing, but it doesn't.

(unlines xs) is only evaluated on demand.  Think of putStr as defined as 

	putStr :: String -> IO ()
	putStr []
		= return ()
	putStr (x : xs)
		= do
			putChar x
			putStr xs

Every character of the string is evaluated when it is needed by putChar x, not 
earlier.  So the argument of putStr is evaluated lazily.

> [...]

> Some day I'll get the hang of this lazy evaluation thing. :)

Yes. :-)  Lazy evaluation is really powerful. ;-)

> > The first one has fewer monads, so I prefer it, but take your pick :)
> Monads scare me, so I'll pick the first :)  Thanks!

It is preferable because it does more of the work without imperative 

> Cheers,
> Daniel.

Best wishes,

More information about the Haskell-Cafe mailing list