-
-
Save pwm/fc01806bacccaaa997b28e28f27554a8 to your computer and use it in GitHub Desktop.
Generic Lens Labels
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# LANGUAGE DeriveGeneric #-} | |
{-# LANGUAGE DerivingStrategies #-} | |
{-# LANGUAGE OverloadedLabels #-} | |
module A where | |
import Control.Lens | |
import Data.Generics.Labels () | |
import GHC.Generics (Generic) | |
import Prelude | |
data Person = MkPerson | |
{ name :: String, | |
age :: Int | |
} | |
deriving stock (Show, Generic) | |
getName :: Person -> String | |
getName p = p ^. #name | |
getAge :: Person -> Int | |
getAge p = p ^. #age | |
dAdams :: Person | |
dAdams = MkPerson "Douglas Adams" 42 | |
{- | |
λ> getName dAdams | |
"Douglas Adams" | |
λ> getAge dAdams | |
42 | |
-} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# LANGUAGE DataKinds #-} | |
{-# LANGUAGE DeriveGeneric #-} | |
{-# LANGUAGE DerivingStrategies #-} | |
{-# LANGUAGE DuplicateRecordFields #-} | |
{-# LANGUAGE FlexibleContexts #-} | |
{-# LANGUAGE OverloadedLabels #-} | |
module B where | |
import Control.Lens | |
import Data.Generics.Labels () | |
import Data.Generics.Product | |
import GHC.Generics (Generic) | |
import Prelude | |
data Person = MkPerson | |
{ name :: String, | |
age :: Int | |
} | |
deriving stock (Show, Generic) | |
data Group = MkGroup | |
{ name :: String, | |
members :: [Person] | |
} | |
deriving stock (Show, Generic) | |
_name :: (HasField "name" s t a b) => Lens s t a b | |
_name = #name | |
dAdams :: Person | |
dAdams = MkPerson "Douglas Adams" 42 | |
greatWriters :: Group | |
greatWriters = | |
MkGroup | |
{ name = "Great writers", | |
members = [dAdams] | |
} | |
{- | |
λ> view _name dAdams | |
"Douglas Adams" | |
λ> view _name greatWriters | |
"Great writers" | |
-} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment