[Haskell-cafe] Basic type classing question.

Karl Grapone kgrapone at gmail.com
Tue Sep 20 22:29:05 EDT 2005


I've just started learning Haskell, and I must admit I'm finding it a
bit hard to get my head around the typing system...

If I wanted to represent Employees and Departments in a Haskell
program I could use data declarations like so:
data Employee = Emp ...
data Department = Dept ...

This seems limited in (at least) two ways:
I can't dynamically add fields to an employee or department, and
once I pull a field out of an instance I lose type information.

What I want to be able to do is add and remove fields while the system
is running, I suppose via hs-plugins, and I should be prevented from,
for example, accidentally taking an employees first name and using it
as a departments address.

My first attempt was the following, which isn't even valid and doesn't
appear to buy me much anyway.

class DataContainer c

class DataContainer c => DataField f c a where
  extract :: f -> a
  apply :: (a -> a -> a) -> f -> f -> f

data DataContainer c => Field c a = Fld c a
instance DataField Field c a where
  extract (Fld _ a) = a
  apply f (Fld c a1) (Fld _ a2) = Fld c (f a1 a2)

data Employee = Emp
instance DataContainer Employee

data Department = Dept
instance DataContainer Department

type EmployeeName = Field Employee String
type EmployeeAddress = Field Employee String
type EmployeeIdentifier = Field Employee Integer
type DepartmentAddress = Field Department String
type DepartmentIdentifier = Field Department Integer

The 'DataField instance Field' declaration gives kind errors regarding
how many type arguments Field is applied to.  I don't claim to
understand kinds at this point.
Even if it did work, apply doesn't appear to force the arguments to be
of the same type, and the declared type synonyms aren't enough to
prevent me getting employee names and addresses confused.

Is there a correct way to express what I'm trying to do?  Or is it a
bad idea to start with?


More information about the Haskell-Cafe mailing list