[Haskell-cafe] Re: Silly I/O question

John Goerzen jgoerzen at complete.org
Tue Sep 28 17:19:44 EDT 2004

On 2004-09-28, Peter Simons <simons at cryp.to> wrote:
> John Goerzen writes:
> > That failed, though, because getContents closes the file
> > after it's been completely read (ugh -- why?).
> You could read the contents once, write it to a temporary
> file, and then copy it multiple times from there. Then you
> could do it in blocks. But that's probably not what you want
> to do.

That just moves the problem :-)  If I assume that stdin is redirected,
it is seekable, and I could do the same there.  But the block I/O in
Haskell makes no sense to me (how do I allocate a Ptr type block

> > But I couldn't figure out a way to make this either
> > properly tail-recursive while handling the exception, or
> > to avoid polling for EOF each time through the function.
> You might want to write a function that copies the file
> _once_ and then just call that function several times. Like
> in the examples above. I don't think you need explicit
> recursion at all.

If I load it into memory, yes.  Otherwise, it seems not so easy.

> Hope this is helpful.

Yes, thanks for the insight.

FWIW, this is working for me:

import IO

main = disp 100

disp 0 = return ()
disp n =
    let copy x = do
               eof <- isEOF
               if eof
                  then return ()
                  else do
                       line <- getLine
                       putStrLn line
                       (copy 0)
        in do
           copy 0
           hSeek stdin AbsoluteSeek 0
           disp (n-1)

but it seems wasteful to poll isEOF so much.

-- John

More information about the Haskell-Cafe mailing list