Hacker News new | ask | show | jobs
by hota_mazi 3296 days ago
Wow, I didn't realize that record field names have to be unique in Haskell. The following:

    data Human = Human {name :: String}
    data Dog = Dog {name :: String}
is illegal, because they can't both have a field accessor called `name`.

That's... crazy.

2 comments

Yea... in theory it makes sense. In Haskell, field names are functions. If you have an instance of Human and you want it's name you do 'name human' not 'human.name()'. Polymorphism is done through type classes, not by ad-hoc overloading. So if you want the name function to take a Human or a Dog you need to define a type class with name and have both implement it (kind of like interfaces, but not really).

Pragmatically, it's really annoying. There's a solution in the space between pure (a la Haskell) and magical (a la Scala) that makes sense. I think Idris might have found it.

AFAIK -XDuplicateRecordFields and -XOverloadedRecordFields solve this now, creating a typeclass for each of the record labels. In this case, the compiler would generate a HasName class. (This is conceptually similar to classy lenses, but minus the TH.)
They only have to be unique per module. As of GHC 8.0, there is a flag that enables duplicate record names.