lens-family-th: Generate lens-family style lenses

[ bsd3, data, library ] [ Propose Tags ]

(see README.md)

[Skip to Readme]
Versions [faq],,,,,,,,
Dependencies base (>=4.9 && <4.14), template-haskell (>=2.11 && <2.16) [details]
License BSD-3-Clause
Copyright (c) Dan Burton 2012-2018
Author Dan Burton
Maintainer danburton.email@gmail.com
Revised Revision 1 made by DanBurton at Tue Sep 24 13:02:38 UTC 2019
Category Data
Home page http://github.com/DanBurton/lens-family-th#readme
Bug tracker http://github.com/DanBurton/lens-family-th/issues
Source repo head: git clone git://github.com/DanBurton/lens-family-th.git
Uploaded by DanBurton at Tue Jul 3 03:25:07 UTC 2018
Distributions LTSHaskell:, NixOS:, Stackage:
Downloads 7962 total (312 in the last 30 days)
Rating (no votes yet) [estimated by Bayesian average]
Your Rating
  • λ
  • λ
  • λ
Status Hackage Matrix CI
Docs available [build log]
Last success reported on 2018-07-03 [all 1 reports]




Note: This package has metadata revisions in the cabal description newer than included in the tarball. To unpack the package including the revisions, use 'cabal get'.

Maintainer's Corner

For package maintainers and hackage trustees

Readme for lens-family-th-

[back to package description]


build status

Template Haskell to generate lenses for lens-family and lens-family-core.


{-# LANGUAGE TemplateHaskell, Rank2Types #-}

import Lens.Family2
import Lens.Family2.TH

data Foo a = Foo { _bar :: Int, _baz :: a }
         deriving (Show, Read, Eq, Ord)
$(makeLenses ''Foo)

This will create lenses bar and baz.

You can instead create these lenses by hand as explained by documentation at Lens.Family.Unchecked.

makeLenses merely generates the following definition for each field, making use of Haskell's record update syntax:

lensName f a = (\x -> a { fieldName = x }) `fmap` f (fieldName a)

makeLenses will refuse to create lenses for data declarations with more than 1 constructor.

For data types with multiple constructors, you can use makeTraversals. For example:

{-# LANGUAGE TemplateHaskell, Rank2Types #-}

import Lens.Family2
import Lens.Family2.TH

data T a c d = A a | B | CD c d Int
$(makeTraversals ''T)

Will create traversals _A, _B, and _C in this fashion:

_A k (A a) = fmap (\a -> A a) (k a)
_A _  B    = pure B
_A _ (C c d i) = pure (C c d i)

_B _ (A a) = pure (A a)
_B k B = fmap (\() -> B) (k ())
_B _ (C c d i) = pure (C c d i)

_C _ (A a) = pure (A a)
_C _ B = pure B
_C k (C c d i) = fmap (\(c',d',i') -> C c' d' i') (k (c,d,i))