[Haskell-beginners] Type constructors sharing a common field
Lorenzo Tabacchini
lortabac at gmx.com
Mon Apr 28 18:26:21 UTC 2014
Imagine the following data type:
data Person = Child { childAge :: Int, school :: School }
| Adult { adultAge :: Int, job :: Job }
Both the alternatives share an "age" field, but in order to access it we
are obliged to match all the constructors:
personAge :: Person -> Int
personAge (Child {childAge = age}) = age
personAge (Adult {adultAge = age}) = age
Is there a way to define a common field in a data type (somehow like
inheritance in the OOP world)?
It would be practical if we could define "age :: Int" as a common field
and do something like:
personAge (_ {age = age}) = age
An alternative solution could be extracting the varying fields in a
different type:
data WorkingPerson = Child School | Adult Job
data Person = Person { age :: Int, workingPerson :: WorkingPerson }
Or to make Person a type class (which would probably require existential
types in order to be useful).
But the first one looks simpler and more natural.
Does this feature exist (maybe in other forms) and, if not, is there a
reason?
Would it make sense to have a GHC extension (or even to make a Template
Haskell hack) for this feature?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/beginners/attachments/20140428/01373aa9/attachment.html>
More information about the Beginners
mailing list