[Haskell-cafe] extensible data types in Haskell?
dons at galois.com
Sun Jul 6 21:18:55 EDT 2008
> Hi all,
> SML conveniently contains the type "exn" which is an instance of an
> "extensible data type". In other words, unlike normal data types that
> are "closed" (can't admit new constructors once defined), SML's exn
> type is "open," allowing programmers to keep adding new alternatives
> as often as they choose. Like normal datatypes, the elimination form
> for an extensible data type is a case statement (or match function).
> Friends have told me that Haskell doesn't have extensible data types.
> However, it seems fairly straightforward to code them up using type
> classes....though the solution I'm thinking of has a little bit of
> boilerplate I'd like to scrap (you have to define a new type
> declaration *and* an instance of a type class with a "match" method)
> and matching occurs through a string comparison (which can lead to
> silly programmer errors if there is accidentally a typo in the
You should probably use Typeable here, for the type matching, rather
than a custom matcher. class Typeable a => Extensible a, this leads to a
fairly straighforward extensible data type, where the open instance
definition lets you add variants on the fly.
> Anyway, it's possible with some thought I could come up with a better
> solution, but before worrying about it, I figured I'd ask if anybody
> else already has a package that does this. It seems like a pretty
> natural feature to want to have.
There's a number of ways to do this, including fully statically via type
classes and existential types, or via the Dynamic type.
Googling for "expression problem Haskell" will turn up some things. Some
implementions of open data types in use can be found in xmonad, and the
extensible exceptions proposal here,
More information about the Haskell-Cafe