[Haskell-beginners] Type constructors sharing a common field

Daniel Trstenjak daniel.trstenjak at gmail.com
Tue Apr 29 10:13:04 UTC 2014


Hi Lorenzo,

I don't think that the first one is more natural, because you could define
a child like: Child { childAge = 99, ... }, but you also might have
someone quite old still studying, so I might go with something like:

   data Occupation = Student School
                   | Employee Job

   data Person = Person { age :: Int, occupation :: Occupation }


But if you really want the first one, then you're most likely only one "lens"[1] away from a solution:

   age :: Lens' Person Int
   age = lens getAge setAge
      where
         getAge Child { childAge = age } = age
         getAge Adult { adultAge = age } = age

         setAge (c at Child {}) newAge = c { childAge = newAge }
         setAge (a at Adult {}) newAge = a { adultAge = newAge }


To get the age of a person you could now write:

   person ^. age

And to modify it:
   
   person & age .~ 22


But I wouldn't prefer the lens solution.


Greetings,
Daniel


[1] https://hackage.haskell.org/package/lens


More information about the Beginners mailing list