fold on Monad?
Jon Fairbairn
Jon.Fairbairn@cl.cam.ac.uk
Wed, 29 May 2002 11:23:26 +0100
Suppose I have a task I want to do to each line of a file,
accumulate a result and output it, I can write
main =3D do stuff <- getContents
print $ foldl process_line initial_value (lines stuff)
ie, it's obviously a fold
I can't see a way of doing the same thing directly on the
IO: I'd like to write something similar to
main =3D do res <- foldX process_line initial_value getLine
print res
foldM almost does it:
main =3D do res <- foldM process initial_value (repeat getLine)
print res
process a g
=3D do line <- g
return (process_line a line)
but that goes on forever (or some fixed amount if (replicate n/repeat))
I feel this ought to be straightforward -- the structure is
obviously some sort of fold, but I shouldn't have to use a
list -- so I must be missing something obvious. What is it?
J=F3n
-- =
J=F3n Fairbairn Jon.Fairbairn@cl.cam.ac.u=
k
31 Chalmers Road jf@cl.cam.ac.uk
Cambridge CB1 3SZ +44 1223 570179 (after 14:00 only, please!)