[Haskell-cafe] file line operation perhaps need loop

yin yin at atom.sk
Wed Jul 20 05:22:12 EDT 2005


Sun Yi Ming wrote:

> Hello,

Hello,

> this works fine, but i think if the two file are very big, and the
> readFile will consume too many mem.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

Don't worry about memory... GNU tools differs from unix-like systems:
they don't utilizing IO by computing, they "slurp", or mmap entire file
into memory and then process it.

main = do
h1 <- openFile "url1.lsm"
h2 <- openFile "url2.lsm"
print (zipFiles h1 h2)

zipFiles :: Handle -> Handle -> IO [String]
zipFiles h1 h2 = do
eof1 <- hIsEOF h
eof2 <- hIsEOF h
case (eof1, eof2) of
(False, False) -> do
l1 <- hGetLine h1
l2 <- hGetLine h2
return l1:l2:(zipFiles h1 h2)
(False, True) -> return (readFile h1)
(True, False) -> return (readFile h2)
_ -> []

I didn't tested it, but.... it should work... (I like fixed-width font
and text-only mails... please, if you mail me, then send me only text,
not html).

Matej 'Yin' Gagyi



More information about the Haskell-Cafe mailing list