Skip to content

Instantly share code, notes, and snippets.

@pwm
Created December 8, 2020 15:31
Show Gist options
  • Save pwm/fc01806bacccaaa997b28e28f27554a8 to your computer and use it in GitHub Desktop.
Save pwm/fc01806bacccaaa997b28e28f27554a8 to your computer and use it in GitHub Desktop.
Generic Lens Labels
{-# 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
-}
{-# 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