Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling events in Haskell

I would like to implement the following scenario in Haskell. I have an enumerable set of 'events' defined like this:

data MyEvent = Event1
             | Event2
             | Event3

I want to define handlers for these events to be used in the following way:

eventLoop :: Handler h => h -> IO ()
eventLoop currentHandler = do
    event <- getNextEvent
    nextHandler <- currentHandler event
    eventLoop nextHandler

Basically I want handlers to be able to return themselves or another handler to handle future events. It's the type of handlers I'm not sure about.

My first idea was to define handlers as simple functions, but their type would get infinitely long:

myHandler :: Event -> IO (Event -> IO (Event -> ... ))

I suspect this can be solved with a type class, where each handler would need to implement a function to handle events (which in turn returns another type of the same class), but the recursive definition would still apply. Can someone more well versed in the type system point me in the right direction? I also welcome any different takes on this.

Thanks!

like image 345
akosch Avatar asked Jan 08 '12 18:01

akosch


1 Answers

Well, "infinite" types usually amount to unrolled recursive types. So one thing you could do is make the recursion explicit using a newtype:

newtype Handler = Handler { runHandler :: Event -> IO Handler }

This is also probably the simplest solution, because it avoids the need to juggle type classes and different instances in order to get different behaviors--each handler can pick what it returns, since they have a uniform interface.

Note that, in many cases, defining a type class to solve this kind of problem is completely superfluous. If you're dealing with a polymorphic type Handler h => h, all you can do with that type is use the type class's functions on it. If the functions defined on that type class are simple, you can save yourself a lot of hassle by conceptually "pre-applying" them.

like image 113
C. A. McCann Avatar answered Sep 19 '22 07:09

C. A. McCann