Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell records, cleaner approach?

Tags:

haskell

record

I've read about some of the issues with Haskell records, in particular, the fact that two elements in the same module can not have the same name.

I understand you can work around this by having separate modules, but I didn't want to do that and instead tried this approach:

class HasX a where
  x :: a -> X

data D1 = D1 { d1_x :: X, ... }
instance HasX D1 where
  x = d1_x

data D2 = D2 { d2_x :: X, ... }
instance HasX D2 where
  x = d2_x

(This only does gets, not sets, I'd of course need to write more code to do sets).

However, it seems the class and instance declarations for all this seem like a like of boilerplate which should be able to be eliminated, using template haskell or something else.

Is there a library or extension to GHC that makes such an approach less messy to write?

like image 200
Clinton Avatar asked May 03 '12 07:05

Clinton


1 Answers

It seems Data.Has encapsulates a lot of what you're looking for. In their vocabulary they I think that their Knows type-class is closer to your Has, and it also provides a signature for injection as well.

They also use a labeling mechanism to treat an issue that I don't think you've considered yet: records which contain fields that have the same type. They use type-level labels to do this disambiguation.

For convenience, there also seems to be some support that provides a generator for the Has instance with template Haskell in Has-TH

You can find more type-level labels and other record-relevant material in works of the Oleg the Type Magician, like OOHaskell (also with Ralf Lämmel).

like image 180
ScottWest Avatar answered Sep 18 '22 12:09

ScottWest