[Haskell-cafe] Existential Data Types

Richard G. richardg at richardg.name
Fri Jul 4 02:29:23 EDT 2008


I've been doing some stuff with existential data types and came across a 
curious pattern.  If anyone has thoughts, comments, or feedback, it 
would be appreciated.


I'm trying to port and extend the Be messaging scheme to Haskell for use 
in distributed, heterogenous environments.  BeOS was object oriented and 
pervasively threaded.  That, and my background as an OOP programmer, has 
resulted in a very OOP approach.

Because OOP allows for subclassing and the Be API was designed for it, 
I've used a wrapper approach.

class HandlerC h where

data Handler = forall h . HandlerC h => Handler h

instance HandlerC Handler where

data DefaultHandler = DefaultHandler ...

instance HandlerC DefaultHandler where

newDefaultHandler = Handler (DefaultHandler ...)
newHandler h = Handler h

The HandlerC defines the interface.  When Handler implements the 
interface, it mostly passes the functions to the inner Handler that 
actually has the data and the real functions.  The advantage is that I 
can wrap anything that implements the HandlerC interface and have it 
behave in a known and simple way from the outside.


One area where this might have some application is in unit testing to 
make mock objects easier to use.  If I had a Looper ADT that depended on 
the Handler, I would want test the Looper without having to worry about 
the complexity of the Handler interfering with the tests.

I could do this with the following:
data MockHandler = MockHandler ...

instance HandlerC MockHandler where

h = newHandler (MockHandler ...)

where h is passed to the Looper some how.


Overall, this seems very similar to data D = D1 | D2 | D3 | ...
The big difference is that all the Dn constructors don't need to be 
known at compile time, which is very useful when writing libraries.

Also, the wrapped data can include functions and state data, making it 
very easy to create applets.  This is handy when doing message passing 
or request handling, such as in a web server, especially when using STM.


More information about the Haskell-Cafe mailing list