Bλog

Links

Type-safe events

Type-safe event-based programming in Haskell
Published 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

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:

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:

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.