Wednesday, April 21, 2010

A Problem I've Encountered with Types

Everyone is familiar with how we can use types to encode checks into our code. For example:

data User
= SystemUser SystemProcessInfo
| AnonUser TimeLoggedIn
| RegisteredUser UserId

data UserId
= PaidUser (..)
| FreeUser (..)


More generally, you can use type witnesses to mix together similar types in the same list, to mimic some aspects of dynamic typing.


The Problem:


Suppose you have a type witness, such that all the witnessed types derive some typeclass (or a similar situation where you are using types to enforce behavior). Is it possible to have the compiler automatically derive that typeclass for the type witness, i.e. something similar to GeneralizedNewtypeDeriving? This kind of boilerplate is yucky:

data A
= A1 X
| A2 Y
| A3 Z

instance Foo A where
getFoo (A1 x) = getFoo x
getFoo (A2 x) = getFoo x
getFoo (A3 x) = getFoo x


One area where this problem seems unavoidable is when you have to deal with collated data of different types. For example, say you have a list of items that were found to be complementary in terms of content, but are of different types. In such cases, type witnesses are unavoidable. If I can get a good solution to this problem, I'll be sure to post it.

1 comment:

mightybyte said...

You can do this with Template Haskell. Happstack does this to derive Serialize instances.