[Haskell-beginners] Type constructors sharing a common field
Frerich Raabe
raabe at froglogic.com
Tue Apr 29 12:08:27 UTC 2014
On 2014-04-28 20: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)?
Since you already have dedicated types for the school and the job, why not
have a descriptive name for the age as well so that you can drop the accessor
functions altogether? E.g.
type Age = Int
data Person = Child Age School
| Adult Age Job
If needed, you could of course still define
age :: Person -> Age
age (Child x _) = x
age (Adult x _) = x
but you may also find that you don't even need such a function in the first
place, pattern matching may do the job just fine:
mayRideRollerCoaster :: Person -> Bool
mayRideRollerCoaster (Child age _) = age > 12
mayRideRollerCoaster _ = True
--
Frerich Raabe - raabe at froglogic.com
www.froglogic.com - Multi-Platform GUI Testing
More information about the Beginners
mailing list