[Haskell-cafe] file line operation perhaps need loop

Sun Yi Ming yimings at cgogo.com
Wed Jul 20 04:15:29 EDT 2005

Arthur van Leeuwen <arthurvl at cs.uu.nl> worte:
> Ah, but this is exactly where lazyness wins bigtime: a smart
> implementation
> of readFile will lazily read the actual file for as far as needed. Thus,
> reading with readFile will not read the entire file into memory at once.
> What will happen is that writeFile starts writing, and upon discovery of
> needing the value of urls it will then start reading. Any value already
> written in this case obviously turns into garbage and will be garbage
> collected. I would be slightly surprised if this code uses more than
> constant memory.
>> so i need to read the file
>> line by line but stunned by the loop in IO Monad:
>> ---
>> main = do h1 <- openFile "url1.txt" ReadMode
>>           h2 <- openFile "url2.txt" ReadMode
>>           line1 <- hGetLine h1
>>           line2 <- hGetLine h2
>>           print $ line1 : line2 : [] -- i don't howto do
>>           hClose h1
>>           hClose h2
>> --
>> any ideas? thank you all.
> Yes. You need to split the lines
>        line1 <- hGetLine h1
>        line2 <- hGetLine h2
>        print $ line1 : line2: []
> into a separate function that will then recurse over the file.
ah, readFile is lazy,that's great! my hat's off to the haskell
design/implement teams for their robust and elegant work. thank all you
BTW, sorry to Doei Arthur for my reply to you by mistake.
Sun Yi Ming

More information about the Haskell-Cafe mailing list