Records in Haskell

Barney Hilken b.hilken at ntlworld.com
Sat Feb 25 23:49:57 CET 2012


> My objection is that I'm not sure if there is ever a case where "you
> really want things to be polymorphic over all records".

Well, I don't have a simple, really convincing example, but there are certainly things I want to play with.
More importantly, DORF automatically attaches one class to each label, but this is often not what you want. For example, if you have two fields "firstname" and "lastname" the associated classes are less useful: what you really want is 

>      class (Has r "firstname" String, Has r "lastname" String) => HasPersonalName r

so that you can define

>	fullname :: HasPersonalName r => r -> String
>	fullname r = r.firstname ++ " " ++ r.lastname

You may also want to define subclasses to express more specific conditions. In general, the compiler cannot automatically deduce what is semantically important: you need to define it yourself. The Has class is the base on which you can build.

> It doesn't seem like the
> Haskell way to have the less safe thing as the one that's default and
> convenient, and to allow the programmer to layer a more-safe thing on
> top of it if he or she wants to. It seems more like the Haskell way to
> have the safer thing be the default and to require extra work if you
> want to do something less safe*.

I think you are using the word "safe" in a slightly misleading way. None of this is mathematically unsafe, because projections are natural (truly polymorphic). The "safety" that is broken here is nothing to do with the semantics of the language, it is to do with the semantics of the system being implemented, and that is something the compiler cannot infer. As my example above shows, it doesn't always correspond one to one with the labels.
 
The Haskel way is to make things as polymorphic as is mathematically safe, even when this goes beyond the programmers original intention. You can then restrict this polymorphism by giving explicit less general types in the same way as in my examples. I think my approach is more Haskel like.

Another important Haskel design consideration is to reuse parts of the language where possible, rather than introduce new structures. Type classes were originally introduced to deal with equality and numeric functions, but were reused for many things including monads. My approach achieves the same as DORF (and more), but using existing language features instead of introducing new ones.

Barney.




More information about the Glasgow-haskell-users mailing list