[Haskell-cafe] Lazy vs correct IO [Was: A round of golf]

David Menendez dave at zednenem.com
Fri Sep 19 15:36:44 EDT 2008


On Fri, Sep 19, 2008 at 2:51 AM,  <oleg at okmij.org> wrote:
>
> Lennart Augustsson wrote
>
>> main = do
>>    name:_ <- getArgs
>>    file <- readFile name
>>    print $ length $ lines file
>
> Given the stance against top-level mutable variables, I have not
> expected to see this Lazy IO code. After all, what could be more against
> the spirit of Haskell than a `pure' function with observable side
> effects. With Lazy IO, one indeed has to choose between correctness
> and performance. The appearance of such code is especially strange
> after the evidence of deadlocks with Lazy IO, presented on this list
> less than a month ago. Let alone unpredictable resource usage and
> reliance on finalizers to close files (forgetting that GHC does not
> guarantee that finalizers will be run at all).
>
> Is there an alternative?
>
> -- Counting the lines in a file
> import IterateeM
>
> count_nl = liftI $ IE_cont (step 0)
>  where
>  step acc (Chunk str)  = liftI $ IE_cont (step $! acc + count str)
>  step acc stream       = liftI $ IE_done acc stream
>  count [] = 0
>  count ('\n':str) = succ $! count str
>  count (_:str) = count str
>
> main = do
>   name:_ <- getArgs
>   IE_done counter _ <- unIM $ enum_file name >. enum_eof ==<< count_nl
>   print counter
>
>
> The function count_nl could have been in the library, but I'm a
> minimalist. It is written in a declarative rather than imperative
> style, and one easily sees what it does. The above code as well as the
> IterateeM library is Haskell98. It does not use any unsafe Haskell
> functions whatsoever.

Is the IterateeM library available on-line anywhere? I'm familiar
enough with your earlier work on enumerators that I can guess what
most of what that code is doing, but I'd like a better idea of what
==<< does.

-- 
Dave Menendez <dave at zednenem.com>
<http://www.eyrie.org/~zednenem/>


More information about the Haskell-Cafe mailing list