generic-lens-0.5.1.0: Generic data-structure operations exposed as lenses.

Copyright(C) 2017 Csongor Kiss
LicenseBSD3
MaintainerCsongor Kiss <kiss.csongor.kiss@gmail.com>
Stabilityexperimental
Portabilitynon-portable
Safe HaskellSafe
LanguageHaskell2010

Data.Generics.Product.Fields

Contents

Description

Derive record field getters and setters generically.

Synopsis

Lenses

Running example:

>>> :set -XTypeApplications
>>> :set -XDataKinds
>>> :set -XDeriveGeneric
>>> :set -XGADTs
>>> :set -XFlexibleContexts
>>> import GHC.Generics
>>> :m +Data.Generics.Internal.Lens
>>> :m +Data.Function
>>> :{
data Human a
  = Human
    { name    :: String
    , age     :: Int
    , address :: String
    , other   :: a
    }
  | HumanNoAddress
    { name    :: String
    , age     :: Int
    , other   :: a
    }
  deriving (Generic, Show)
human :: Human Bool
human = Human { name = "Tunyasz", age = 50, address = "London", other = False }
:}

class HasField (field :: Symbol) s t a b | s field -> a, s field b -> t, t field a -> s where Source #

Records that have a field with a given name.

Minimal complete definition

field

Methods

field :: Lens s t a b Source #

A lens that focuses on a field with a given name. Compatible with the lens package's Lens type.

>>> human ^. field @"age"
50

Type changing

>>> :t human
human :: Human Bool
>>> :t human & field @"other" .~ (42 :: Int)
human & field @"other" .~ (42 :: Int) :: Human Int
>>> human & field @"other" .~ 42
Human {name = "Tunyasz", age = 50, address = "London", other = 42}

Type errors

>>> human & field @"weight" .~ 42
...
... The type Human Bool does not contain a field named 'weight'.
...
>>> human & field @"address" .~ ""
...
... Not all constructors of the type Human Bool
... contain a field named 'address'.
... The offending constructors are:
... HumanNoAddress
...

Instances

(Generic s, ErrorUnless field s (CollectField * field (Rep s)), Generic t, (~) * s' (Proxied * s), (~) * t' (Proxied * t), Generic s', Generic t', GHasField' field (Rep s) a, GHasField' field (Rep s') a', GHasField' field (Rep t') b', GHasField field (Rep s) (Rep t) a b, (~) * t (Infer s a' b), (~) * s (Infer t b' a)) => HasField field s t a b Source # 

Methods

field :: Lens s t a b Source #

type HasField' field s a = HasField field s s a a Source #

getField :: forall f s a. HasField' f s a => s -> a Source #

>>> getField @"age" human
50

setField :: forall f s a. HasField' f s a => a -> s -> s Source #

>>> setField @"age" 60 human
Human {name = "Tunyasz", age = 60, address = "London", other = False}