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

Ezra Cooper ezra at ezrakilty.net
Tue Jan 3 13:53:09 EST 2006


On Jan 3, 2006, at 6:30 PM, Sebastian Sylvan wrote:

> On 1/3/06, Daniel Carrera <daniel.carrera at zmsl.com> wrote:
>> 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.
>>
>> Some day I'll get the hang of this lazy evaluation thing. :)
>
> It does, in a sense, but since unlines is lazy (just like *everything
> else* in Haskell) it won't actually *do* anything until putStr demands
> an element from the result.

... and, significantly, putStr will demand those elements one at a 
time; each element of the list is, in turn, evaluated lazily, producing 
(a) a next element and (b) a thunk representing the rest of the list.

In your example 'join' function,

   join [] = ""
   join (x:xs) = (show x) ++ "\n" ++ join xs

the caller will demand the first element of the list, which will force 
the evaluation of (show x) but it will not immediately force the 
evaluation of (join xs). That part stays as it is, living life as a 
thunk, until the caller has demanded all the preceding elements and 
still wants more.

hth,
Ezra



More information about the Haskell-Cafe mailing list