Type-safe events



Published on October 16, 2011 under the tag Type-safe event-based programming in HaskellPublished on October 16, 2011 under the tag haskell

This is some code I wrote a while ago. It is (mostly) based upon Data Types a la Carte, a great pearl by Wouter Swierstra. It uses some ideas discussed in this paper to create a type-safe, extensible event-based framework in Haskell.

This blogpost is written in Literate Haskell, meaning you should be able to download and run it. It also means we’re going to have some (relatively common) language extentions and imports:

An extensible sum type

The first job is to write an extensible sum type, which will be how we represent events. Think of it as an extended

where we can add more constructors in different files, so it’s somewhat more flexible. The Contains a typeclass means that a value of type s optionally contains a value of type a . We can wrap and unwrap this type:

Our main instance is a sum type combining two other types:

Later, we will chain this sum type to a list like:

We need instances of Contains so we can wrap and unwrap these lists:

An event-aware monad

Now, let’s go back to our extensible, event-based framework. We’ll assume all clients of the framework can be implemented as a monad. We can abstract over this monad, creating a typeclass for monads which can respond to an event of type e :

As you probably guessed, the fire method fires an event. We implement an instance which is a ReaderT . This way, the underlying monad can access a function which triggers an event:

By using this trigger, our RespondsT becomes an instance of MonadResponds .

Now, all we need in order to write clients is some more syntactic sugar:

A logging client

Let’s start out by implementing a very simple logger as client for the framework:

A ping client

The logging client received events using client … let’s see how we can actually send events by writing an artificial ping-pong protocol. This client uses features from the logger, so we can really compose clients by just listing the required instances in the type signature (as is commonly done with monad transformers), which is a pretty cool thing.

Actually running it

If you’ve followed this blogpost until now, you probably want to see how we can, in the end, combine a number of clients and run them.

To this end, we’ll write a small utility function which combines a number of handlers (our clients) by sequentially applying them to the same event).

Now, let’s use this to compose our clients. At this point, we’re required to fix the type for our client:

And then we can write a program which uses these features:

I hope you’ve enjoyed this blogpost – all criticism is welcome. If someone feels like turning this into a proper library, you’re also welcome.