"callbacks" in Haskell

Tom Pledger Tom.Pledger@peace.com
Thu, 26 Jun 2003 08:44:38 +1200

Robert Vollmert writes:
 | Hello,
 | I've been having a little trouble writing a module that waits for and
 | handles IO events, e.g. by reading from a pipe. It seemed natural to
 | use some form of callbacks here, though that may very well be the
 | wrong approach. I'd be happy to hear of alternatives.
 | Anyway, I got a callback-based approach to work to some extent, but
 | am not happy with the callback's type.

Can the event and handler inhabit the same monad, say IO?  If so, is
the following the sort of thing you had in mind?

    waitAndHandleOneEvent      :: IO e -> (e -> IO ()) -> IO ()
    waitAndHandleOneEvent ioe h = forkIO (do e <- ioe
                                             h e)

But then, because ioe and h always get combined the same way (ioe >>=
h), we can generalise waitAndHandleOneEvent to

    waitAndDoOneThing   :: IO () -> IO ()
    waitAndDoOneThing io = forkIO io

which is equivalent to using forkIO directly, as in

    do ...
       let ioe :: IO MyEvent
           ioe  = ...
           h   :: MyEvent -> IO ()
           h e  = ...
       forkIO (ioe >>= h)