On Tue Apr 29 2014 at 16:42:40, Lorenzo Tabacchini lortabac@gmx.com wrote:
If you could have a single polymorphic "age" function for all types
having an age, you could never have this runtime error, because the
compiler would infer which "age" we are referring to.
The GHC OverloadedRecordFields extension that Michael linked seems to do
what I am looking for (http://www.well-typed.com/blog/84/).
This is accurate. In the meantime avoid partiality as much as possible. If you must have an age accessor, better to define the lens explicitly.
module Main where
import Control.Applicative
import Control.Lens
main :: IO ()
main = let p = Child 10
in print $ p ^. age
data Person = Child Int | Adult Int
age :: Lens' Person Int
age k (Child x) = Child <$> k x
age k (Adult x) = Adult <$> k x
Yeah it’s boilerplate. You could makeLenses
and then not export the automatically generated selector functions.