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

[ bsd3, data, library ] [ Propose Tags ] [ Report a vulnerability ]

(see README.md)


[Skip to Readme]

Downloads

Maintainer's Corner

Package maintainers

For package maintainers and hackage trustees

Candidates

Versions [RSS] 0.1.0.0, 0.2.0.0, 0.2.0.1, 0.3.0.0, 0.4.0.0, 0.4.1.0, 0.5.0.0, 0.5.0.1, 0.5.0.2, 0.5.1.0, 0.5.2.0, 0.5.2.1, 0.5.3.0, 0.5.3.1
Change log ChangeLog.md
Dependencies base (>=4.9 && <5), template-haskell (>=2.11 && <2.22) [details]
Tested with ghc ==9.8.1, ghc ==9.6.3, ghc ==9.4.8, ghc ==9.2.8, ghc ==9.0.2, ghc ==8.10.7, ghc ==8.8.4, ghc ==8.6.5, ghc ==8.4.4, ghc ==8.2.2, ghc ==8.0.2
License BSD-3-Clause
Copyright (c) Dan Burton 2012-2020
Author Dan Burton
Maintainer danburton.email@gmail.com
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 2024-01-16T00:08:09Z
Distributions NixOS:0.5.3.1, Stackage:0.5.3.1
Reverse Dependencies 8 direct, 61 indirect [details]
Downloads 15298 total (69 in the last 30 days)
Rating (no votes yet) [estimated by Bayesian average]
Your Rating
  • λ
  • λ
  • λ
Status Docs available [build log]
Last success reported on 2024-01-16 [all 1 reports]

Readme for lens-family-th-0.5.3.1

[back to package description]

lens-family-th

build status

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

Usage:

{-# 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))