[Haskell-beginners] Type constructors sharing a common field
Benjamin Edwards
edwards.benj at gmail.com
Tue Apr 29 15:55:43 UTC 2014
On Tue Apr 29 2014 at 16:42:40, Lorenzo Tabacchini
lortabac at gmx.com<http://mailto: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.Applicativeimport Control.Lens
main :: IO ()main = let p = Child 10
in print $ p ^. age
data Person = Child Int | Adult Int
age :: Lens' Person Intage k (Child x) = Child <$> k xage k (Adult x)
= Adult <$> k x
Yeah it’s boilerplate. You could makeLenses and then not export the
automatically generated selector functions.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/beginners/attachments/20140429/9d8960f6/attachment.html>
More information about the Beginners
mailing list