[Haskell-beginners] Type constructors sharing a common field

Thomas Hallgren hallgren at chalmers.se
Wed Apr 30 10:02:44 UTC 2014


Hi,

On 2014-04-28 19:26, Lorenzo Tabacchini wrote:
> 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)?


Yes, there is:

  data Person = Child { personAge :: Int, school :: School }
              | Adult { personAge :: Int, job :: Job }


No extension needed!

Thomas H



More information about the Beginners mailing list