Lens s t a b is the lowest common denominator of a setter and a getter, something that has the power of both; it has a Functor constraint, and since both Const and Identity are functors, it can be used whenever a getter or a setter is needed.
a is the type of the value inside of structure
b is the type of the replaced value
s is the type of the whole structure
t is the type of the structure after replacing a in it with b
Note that at doesn't work for arrays or lists. You can't delete an arbitrary element from an array (what would be left in its place?), and you can't set an arbitrary element in a list because if the index is out of list's bounds, you'd have to somehow fill the stretch between the last element and the element you just inserted (i.e. [1,2,3] & at 10 .~ 5 is undefined). If you want to modify an already existing value in an array or list, you should use ix instead.
at is often used with non. See the documentation of non for examples.
Note that at isn't strict for Map, even if you're using Data.Map.Strict:
Example1 expression
>>> Data.Map.Strict.size (Data.Map.Strict.empty & at 1 .~ Just undefined)1
The reason for such behavior is that there's actually no “strict Map” type; Data.Map.Strict just provides some strict functions for ordinary Maps.
This package doesn't actually provide any instances for at, but there are instances for Map and IntMap in microlens-ghc and an instance for HashMap in microlens-platform.
each tries to be a universal Traversal – it behaves like traversed in most situations, but also adds support for e.g. tuples with same-typed values:
Example1 expression
>>> (1,2) & each %~ succ(2,3)
Example1 expression
>>> ["x", "y", "z"] ^. each"xyz"
However, note that each doesn't work on every instance of Traversable. If you have a Traversable which isn't supported by each, you can use traversed instead. Personally, I like using each instead of traversed whenever possible – it's shorter and more descriptive.
This traversal lets you access (and update) an arbitrary element in a list, array, Map, etc. (If you want to insert or delete elements as well, look at at.)
An example for lists:
Example1 expression
>>> [0..5] & ix 3 .~ 10[0,1,2,10,4,5]
You can use it for getting, too:
Example1 expression
>>> [0..5] ^? ix 3Just 3
Of course, the element may not be present (which means that you can use ix as a safe variant of (!!)):
Example1 expression
>>> [0..5] ^? ix 10Nothing
Another useful instance is the one for functions – it lets you modify their outputs for specific inputs. For instance, here's maximum that returns 0 when the list is empty (instead of throwing an exception):
ASetter s t a b is something that turns a function modifying a value into a function modifying a structure. If you ignore Identity (as Identity a is the same thing as a), the type is:
type ASetter s t a b = (a -> b) -> s -> t
The reason Identity is used here is for ASetter to be composable with other types, such as Lens.
Technically, if you're writing a library, you shouldn't use this type for setters you are exporting from your library; the right type to use is Setter, but it is not provided by this package (because then it'd have to depend on distributive). It's completely alright, however, to export functions which take an ASetter as an argument.
This is a type alias for monomorphic setters which don't change the type of the container (or of the value inside). It's useful more often than the same type in lens, because we can't provide real setters and so it does the job of both ASetter' and Setter'.
Functions that operate on getters and folds – such as (^.), (^..), (^?) – use Getter r s a (with different values of r) to describe what kind of result they need. For instance, (^.) needs the getter to be able to return a single value, and so it accepts a getter of type Getting a s a. (^..) wants the getter to gather values together, so it uses Getting (Endo [a]) s a (it could've used Getting [a] s a instead, but it's faster with Endo). The choice of r depends on what you want to do with elements you're extracting from s.
StypetypeLensLike (f :: Type -> Type) stab = (a -> fb) -> s -> ft
LensLike is a type that is often used to make combinators as general as possible. For instance, take (<<%~), which only requires the passed lens to be able to work with the (,) a functor (lenses and traversals can do that). The fully expanded type is as follows:
(<<%~) :: ((a -> (a, b)) -> s -> (a, t)) -> (a -> b) -> s -> (a, t)
With LensLike, the intent to use the (,) a functor can be made a bit clearer:
(<<%~) :: LensLike ((,) a) s t a b -> (a -> b) -> s -> (a, t)
A SimpleGetter s a extracts a from s; so, it's the same thing as (s -> a), but you can use it in lens chains because its type looks like this:
type SimpleGetter s a =
forall r. (a -> Const r a) -> s -> Const r s
Since Const r is a functor, SimpleGetter has the same shape as other lens types and can be composed with them. To get (s -> a) out of a SimpleGetter, choose r ~ a and feed Const :: a -> Const a a to the getter:
type Getter s a =
forall f. (Contravariant f, Functor f) => (a -> f a) -> s -> f s
I'm not currently aware of any functions that take lens's Getter but won't accept SimpleGetter, but you should try to avoid exporting SimpleGetters anyway to minimise confusion. Alternatively, look at microlens-contra, which provides a fully lens-compatible Getter.
Lens users: you can convert a SimpleGetter to Getter by applying to . view to it.
Traversal s t a b is a generalisation of Lens which allows many targets (possibly 0). It's achieved by changing the constraint to Applicative instead of Functor – indeed, the point of Applicative is that you can combine effects, which is just what we need to have many targets.
Ultimately, traversals should follow 2 laws:
t pure ≡ pure
fmap (t f) . t g ≡ getCompose . t (Compose . fmap f . g)
The 1st law states that you can't change the shape of the structure or do anything funny with elements (traverse elements which aren't in the structure, create new elements out of thin air, etc.). The 2nd law states that you should be able to fuse 2 identical traversals into one. For a more detailed explanation of the laws, see this blog post (if you prefer rambling blog posts), or The Essence Of The Iterator Pattern (if you prefer papers).
Traversing any value twice is a violation of traversal laws. You can, however, traverse values in any order.
(%~) applies a function to the target; an alternative explanation is that it is an inverse of sets, which turns a setter into an ordinary function. mapped%~reverse is the same thing as fmapreverse.
When (^.) is used with a traversal, it combines all results using the Monoid instance for the resulting type. For instance, for lists it would be simple concatenation:
Example1 expression
>>> ("str","ing") ^. each"string"
The reason for this is that traversals use Applicative, and the Applicative instance for Const uses monoid concatenation to combine “effects” of Const.
A non-operator version of (^.) is called view, and it's a bit more general than (^.) (it works in MonadReader). If you need the general version, you can get it from microlens-mtl; otherwise there's view available in Lens.Micro.Extras.
s ^? t returns the 1st element t returns, or Nothing if t doesn't return anything. It's trivially implemented by passing the First monoid to the getter.
A non-operator version of (^?) is called preview, and – like view – it's a bit more general than (^?) (it works in MonadReader). If you need the general version, you can get it from microlens-mtl; otherwise there's preview available in Lens.Micro.Extras.
Note that the resulting traversal won't be valid unless either both traversals don't touch each others' elements, or both traversals return exactly the same results. To see an example of how failing can generate invalid traversals, see this Stackoverflow question.
& is a reverse application operator. This provides notational
convenience. Its precedence is one higher than that of the forward
application operator $, which allows & to be nested in $.
This is a version of flipid, where id is specialized from a -> a to (a -> b) -> (a -> b)
which by the associativity of (->) is (a -> b) -> a -> b.
flipping this yields a -> (a -> b) -> b which is the type signature of &
Examples
Example1 expression
>>> 5 & (+1) & show"6"
Example1 expression
>>> sqrt $ [1 / n^2 | n <- [1..1000]] & sum & (*6)3.1406380562059946
_Show targets the Haskell value in a String using Read, or nothing if parsing fails. Likewise, setting a Haskell value through this prism renders a String using Show.
_head traverses the 1st element of something (usually a list, but can also be a Seq, etc):
Example1 expression
>>> [1..5] ^? _headJust 1
It can be used to modify too, as in this example where the 1st letter of a sentence is capitalised:
Example1 expression
>>> "mary had a little lamb." & _head %~ toTitle"Mary had a little lamb."
The reason it's a traversal and not a lens is that there's nothing to traverse when the list is empty:
Example1 expression
>>> [] ^? _headNothing
This package only lets you use _head on lists, but if you use microlens-ghc you get instances for ByteString and Seq, and if you use microlens-platform you additionally get instances for Text and Vector.
_tail gives you access to the tail of a list (or Seq, etc):
Example1 expression
>>> [1..5] ^? _tailJust [2,3,4,5]
You can modify the tail as well:
Example1 expression
>>> [4,1,2,3] & _tail %~ reverse[4,3,2,1]
Since lists are monoids, you can use _tail with plain (^.) (and then it'll return an empty list if you give it an empty list):
Example1 expression
>>> [1..5] ^. _tail[2,3,4,5]
Example1 expression
>>> [] ^. _tail[]
If you want to traverse each element of the tail, use _tail with each:
Example1 expression
>>> "I HATE CAPS." & _tail.each %~ toLower"I hate caps."
This package only lets you use _tail on lists, but if you use microlens-ghc you get instances for ByteString and Seq, and if you use microlens-platform you additionally get instances for Text and Vector.
And now combine them into a traversal that conditionally traverses the value it's given, and you get filtered:
filtered :: (a -> Bool) -> Traversal' a a
filtered p f s = if p s then f s else pure s
By the way, note that filtered can generate illegal traversals – sometimes this can bite you. In particular, an optimisation that should be safe becomes unsafe. (To the best of my knowledge, this optimisation never happens automatically. If you just use filtered to modify/view something, you're safe. If you don't define any traversals that use filtered, you're safe too.)
Unfortunately, in case of evens this isn't a correct optimisation:
the left-side variant applies g to all even numbers, and then applies f to all even numbers that are left after f (because f might've turned some even numbers into odd ones)
the right-side variant applies f and g to all even numbers
Of course, when you are careful and know what you're doing, you won't try to make such an optimisation. However, if you export an illegal traversal created with filtered and someone tries to use it, they might mistakenly assume that it's legal, do the optimisation, and silently get an incorrect result.
If you are using filtered with some another traversal that doesn't overlap with -whatever the predicate checks-, the resulting traversal will be legal. For instance, here the predicate looks at the 1st element of a tuple, but the resulting traversal only gives you access to the 2nd:
traverseOf_ with flipped arguments. Useful if the “loop body” is a lambda
or a do block, or in some other cases – for instance, you can avoid
accidentally using for_ on a tuple or Either by switching
to forOf_each. Or you can write custom loops like these:
lens creates a Lens from a getter and a setter. The resulting lens isn't the most effective one (because of having to traverse the structure twice when modifying), but it shouldn't matter much.
A (partial) lens for list indexing:
ix :: Int -> Lens' [a] a
ix i = lens (!! i) -- getter
(\s b -> take i s ++ b : drop (i+1) s) -- setter
Usage:
>>> [1..9] ^. ix 3
4
>>> [1..9] & ix 3 %~ negate
[1,2,3,-4,5,6,7,8,9]
When getting, the setter is completely unused; when setting, the getter is unused. Both are used only when the value is being modified. For instance, here we define a lens for the 1st element of a list, but instead of a legitimate getter we use undefined. Then we use the resulting lens for setting and it works, which proves that the getter wasn't used:
Example1 expression
>>> [1,2,3] & lens undefined (\s b -> b : tail s) .~ 10[10,2,3]
mapped is a setter for everything contained in a functor. You can use it to map over lists, Maybe, or even IO (which is something you can't do with traversed or each).
Here mapped is used to turn a value to all non-Nothing values in a list:
non lets you “relabel” a Maybe by equating Nothing to an arbitrary value (which you can choose):
Example1 expression
>>> Just 1 ^. non 01
Example1 expression
>>> Nothing ^. non 00
The most useful thing about non is that relabeling also works in other direction. If you try to set the “forbidden” value, it'll be turned to Nothing:
Example1 expression
>>> Just 1 & non 0 .~ 0Nothing
Setting anything else works just fine:
Example1 expression
>>> Just 1 & non 0 .~ 5Just 5
Same happens if you try to modify a value:
Example1 expression
>>> Just 1 & non 0 %~ subtract 1Nothing
Example1 expression
>>> Just 1 & non 0 %~ (+ 1)Just 2
non is often useful when combined with at. For instance, if you have a map of songs and their playcounts, it makes sense not to store songs with 0 plays in the map; non can act as a filter that wouldn't pass such entries.
Decrease playcount of a song to 0, and it'll be gone:
Example1 expression
>>> fromList [("Soon",1),("Yesterday",3)] & at "Soon" . non 0 %~ subtract 1fromList [("Yesterday",3)]
Try to add a song with 0 plays, and it won't be added:
Example1 expression
>>> fromList [("Yesterday",3)] & at "Soon" . non 0 .~ 0fromList [("Yesterday",3)]
But it will be added if you set any other number:
Example1 expression
>>> fromList [("Yesterday",3)] & at "Soon" . non 0 .~ 1fromList [("Soon",1),("Yesterday",3)]
non is also useful when working with nested maps. Here a nested map is created when it's missing:
Example1 expression
>>> Map.empty & at "Dez Mona" . non Map.empty . at "Soon" .~ Just 1fromList [("Dez Mona",fromList [("Soon",1)])]
and here it is deleted when its last entry is deleted (notice that non is used twice here):
Example1 expression
>>> fromList [("Dez Mona",fromList [("Soon",1)])] & at "Dez Mona" . non Map.empty . at "Soon" . non 0 %~ subtract 1fromList []
To understand the last example better, observe the flow of values in it:
the map goes into at "Dez Mona"
the nested map (wrapped into Just) goes into non Map.empty
Just is unwrapped and the nested map goes into at "Soon"
Just 1 is unwrapped by non 0
Then the final value – i.e. 1 – is modified by subtract 1 and the result (which is 0) starts flowing backwards:
non 0 sees the 0 and produces a Nothing
at "Soon" sees Nothing and deletes the corresponding value from the map
the resulting empty map is passed to non Map.empty, which sees that it's empty and thus produces Nothing
at "Dez Mona" sees Nothing and removes the key from the map
Rewrite by applying a rule everywhere you can. Ensures that the rule cannot be applied anywhere in the result.
Usually transformOf is more appropriate, but rewriteOf can give better compositionality. Given two single transformations f and g, you can construct \a -> f a <|> g a which performs both rewrites until a fixed point.
It's most useful in chains, because it lets you mix lenses and ordinary functions. Suppose you have a record which comes from some third-party library and doesn't have any lens accessors. You want to do something like this:
value ^. _1 . field . at 2
However, field isn't a getter, and you have to do this instead:
field (value ^. _1) ^. at 2
but now value is in the middle and it's hard to read the resulting code. A variant with to is prettier and more readable:
Apply an action to all targets and discard the result (like mapM_ or traverse_):
Example1 expression
>>> traverseOf_ both putStrLn ("hello", "world")helloworld
Works with anything that allows getting, including lenses and getters (so, anything except for ASetter). Should be faster than traverseOf when you don't need the result.
Lens s t a b is the lowest common denominator of a setter and a getter, something that has the power of both; it has a Functor constraint, and since both Const and Identity are functors, it can be used whenever a getter or a setter is needed.
a is the type of the value inside of structure
b is the type of the replaced value
s is the type of the whole structure
t is the type of the structure after replacing a in it with b
Note that at doesn't work for arrays or lists. You can't delete an arbitrary element from an array (what would be left in its place?), and you can't set an arbitrary element in a list because if the index is out of list's bounds, you'd have to somehow fill the stretch between the last element and the element you just inserted (i.e. [1,2,3] & at 10 .~ 5 is undefined). If you want to modify an already existing value in an array or list, you should use ix instead.
at is often used with non. See the documentation of non for examples.
Note that at isn't strict for Map, even if you're using Data.Map.Strict:
Example1 expression
>>> Data.Map.Strict.size (Data.Map.Strict.empty & at 1 .~ Just undefined)1
The reason for such behavior is that there's actually no “strict Map” type; Data.Map.Strict just provides some strict functions for ordinary Maps.
This package doesn't actually provide any instances for at, but there are instances for Map and IntMap in microlens-ghc and an instance for HashMap in microlens-platform.
each tries to be a universal Traversal – it behaves like traversed in most situations, but also adds support for e.g. tuples with same-typed values:
Example1 expression
>>> (1,2) & each %~ succ(2,3)
Example1 expression
>>> ["x", "y", "z"] ^. each"xyz"
However, note that each doesn't work on every instance of Traversable. If you have a Traversable which isn't supported by each, you can use traversed instead. Personally, I like using each instead of traversed whenever possible – it's shorter and more descriptive.
This traversal lets you access (and update) an arbitrary element in a list, array, Map, etc. (If you want to insert or delete elements as well, look at at.)
An example for lists:
Example1 expression
>>> [0..5] & ix 3 .~ 10[0,1,2,10,4,5]
You can use it for getting, too:
Example1 expression
>>> [0..5] ^? ix 3Just 3
Of course, the element may not be present (which means that you can use ix as a safe variant of (!!)):
Example1 expression
>>> [0..5] ^? ix 10Nothing
Another useful instance is the one for functions – it lets you modify their outputs for specific inputs. For instance, here's maximum that returns 0 when the list is empty (instead of throwing an exception):
ASetter s t a b is something that turns a function modifying a value into a function modifying a structure. If you ignore Identity (as Identity a is the same thing as a), the type is:
type ASetter s t a b = (a -> b) -> s -> t
The reason Identity is used here is for ASetter to be composable with other types, such as Lens.
Technically, if you're writing a library, you shouldn't use this type for setters you are exporting from your library; the right type to use is Setter, but it is not provided by this package (because then it'd have to depend on distributive). It's completely alright, however, to export functions which take an ASetter as an argument.
This is a type alias for monomorphic setters which don't change the type of the container (or of the value inside). It's useful more often than the same type in lens, because we can't provide real setters and so it does the job of both ASetter' and Setter'.
Functions that operate on getters and folds – such as (^.), (^..), (^?) – use Getter r s a (with different values of r) to describe what kind of result they need. For instance, (^.) needs the getter to be able to return a single value, and so it accepts a getter of type Getting a s a. (^..) wants the getter to gather values together, so it uses Getting (Endo [a]) s a (it could've used Getting [a] s a instead, but it's faster with Endo). The choice of r depends on what you want to do with elements you're extracting from s.
StypetypeLensLike (f :: Type -> Type) stab = (a -> fb) -> s -> ft
LensLike is a type that is often used to make combinators as general as possible. For instance, take (<<%~), which only requires the passed lens to be able to work with the (,) a functor (lenses and traversals can do that). The fully expanded type is as follows:
(<<%~) :: ((a -> (a, b)) -> s -> (a, t)) -> (a -> b) -> s -> (a, t)
With LensLike, the intent to use the (,) a functor can be made a bit clearer:
(<<%~) :: LensLike ((,) a) s t a b -> (a -> b) -> s -> (a, t)
A SimpleGetter s a extracts a from s; so, it's the same thing as (s -> a), but you can use it in lens chains because its type looks like this:
type SimpleGetter s a =
forall r. (a -> Const r a) -> s -> Const r s
Since Const r is a functor, SimpleGetter has the same shape as other lens types and can be composed with them. To get (s -> a) out of a SimpleGetter, choose r ~ a and feed Const :: a -> Const a a to the getter:
type Getter s a =
forall f. (Contravariant f, Functor f) => (a -> f a) -> s -> f s
I'm not currently aware of any functions that take lens's Getter but won't accept SimpleGetter, but you should try to avoid exporting SimpleGetters anyway to minimise confusion. Alternatively, look at microlens-contra, which provides a fully lens-compatible Getter.
Lens users: you can convert a SimpleGetter to Getter by applying to . view to it.
Traversal s t a b is a generalisation of Lens which allows many targets (possibly 0). It's achieved by changing the constraint to Applicative instead of Functor – indeed, the point of Applicative is that you can combine effects, which is just what we need to have many targets.
Ultimately, traversals should follow 2 laws:
t pure ≡ pure
fmap (t f) . t g ≡ getCompose . t (Compose . fmap f . g)
The 1st law states that you can't change the shape of the structure or do anything funny with elements (traverse elements which aren't in the structure, create new elements out of thin air, etc.). The 2nd law states that you should be able to fuse 2 identical traversals into one. For a more detailed explanation of the laws, see this blog post (if you prefer rambling blog posts), or The Essence Of The Iterator Pattern (if you prefer papers).
Traversing any value twice is a violation of traversal laws. You can, however, traverse values in any order.
(%~) applies a function to the target; an alternative explanation is that it is an inverse of sets, which turns a setter into an ordinary function. mapped%~reverse is the same thing as fmapreverse.
When (^.) is used with a traversal, it combines all results using the Monoid instance for the resulting type. For instance, for lists it would be simple concatenation:
Example1 expression
>>> ("str","ing") ^. each"string"
The reason for this is that traversals use Applicative, and the Applicative instance for Const uses monoid concatenation to combine “effects” of Const.
A non-operator version of (^.) is called view, and it's a bit more general than (^.) (it works in MonadReader). If you need the general version, you can get it from microlens-mtl; otherwise there's view available in Lens.Micro.Extras.
s ^? t returns the 1st element t returns, or Nothing if t doesn't return anything. It's trivially implemented by passing the First monoid to the getter.
A non-operator version of (^?) is called preview, and – like view – it's a bit more general than (^?) (it works in MonadReader). If you need the general version, you can get it from microlens-mtl; otherwise there's preview available in Lens.Micro.Extras.
Note that the resulting traversal won't be valid unless either both traversals don't touch each others' elements, or both traversals return exactly the same results. To see an example of how failing can generate invalid traversals, see this Stackoverflow question.
& is a reverse application operator. This provides notational
convenience. Its precedence is one higher than that of the forward
application operator $, which allows & to be nested in $.
This is a version of flipid, where id is specialized from a -> a to (a -> b) -> (a -> b)
which by the associativity of (->) is (a -> b) -> a -> b.
flipping this yields a -> (a -> b) -> b which is the type signature of &
Examples
Example1 expression
>>> 5 & (+1) & show"6"
Example1 expression
>>> sqrt $ [1 / n^2 | n <- [1..1000]] & sum & (*6)3.1406380562059946
_Show targets the Haskell value in a String using Read, or nothing if parsing fails. Likewise, setting a Haskell value through this prism renders a String using Show.
_head traverses the 1st element of something (usually a list, but can also be a Seq, etc):
Example1 expression
>>> [1..5] ^? _headJust 1
It can be used to modify too, as in this example where the 1st letter of a sentence is capitalised:
Example1 expression
>>> "mary had a little lamb." & _head %~ toTitle"Mary had a little lamb."
The reason it's a traversal and not a lens is that there's nothing to traverse when the list is empty:
Example1 expression
>>> [] ^? _headNothing
This package only lets you use _head on lists, but if you use microlens-ghc you get instances for ByteString and Seq, and if you use microlens-platform you additionally get instances for Text and Vector.
_tail gives you access to the tail of a list (or Seq, etc):
Example1 expression
>>> [1..5] ^? _tailJust [2,3,4,5]
You can modify the tail as well:
Example1 expression
>>> [4,1,2,3] & _tail %~ reverse[4,3,2,1]
Since lists are monoids, you can use _tail with plain (^.) (and then it'll return an empty list if you give it an empty list):
Example1 expression
>>> [1..5] ^. _tail[2,3,4,5]
Example1 expression
>>> [] ^. _tail[]
If you want to traverse each element of the tail, use _tail with each:
Example1 expression
>>> "I HATE CAPS." & _tail.each %~ toLower"I hate caps."
This package only lets you use _tail on lists, but if you use microlens-ghc you get instances for ByteString and Seq, and if you use microlens-platform you additionally get instances for Text and Vector.
And now combine them into a traversal that conditionally traverses the value it's given, and you get filtered:
filtered :: (a -> Bool) -> Traversal' a a
filtered p f s = if p s then f s else pure s
By the way, note that filtered can generate illegal traversals – sometimes this can bite you. In particular, an optimisation that should be safe becomes unsafe. (To the best of my knowledge, this optimisation never happens automatically. If you just use filtered to modify/view something, you're safe. If you don't define any traversals that use filtered, you're safe too.)
Unfortunately, in case of evens this isn't a correct optimisation:
the left-side variant applies g to all even numbers, and then applies f to all even numbers that are left after f (because f might've turned some even numbers into odd ones)
the right-side variant applies f and g to all even numbers
Of course, when you are careful and know what you're doing, you won't try to make such an optimisation. However, if you export an illegal traversal created with filtered and someone tries to use it, they might mistakenly assume that it's legal, do the optimisation, and silently get an incorrect result.
If you are using filtered with some another traversal that doesn't overlap with -whatever the predicate checks-, the resulting traversal will be legal. For instance, here the predicate looks at the 1st element of a tuple, but the resulting traversal only gives you access to the 2nd:
traverseOf_ with flipped arguments. Useful if the “loop body” is a lambda
or a do block, or in some other cases – for instance, you can avoid
accidentally using for_ on a tuple or Either by switching
to forOf_each. Or you can write custom loops like these:
lens creates a Lens from a getter and a setter. The resulting lens isn't the most effective one (because of having to traverse the structure twice when modifying), but it shouldn't matter much.
A (partial) lens for list indexing:
ix :: Int -> Lens' [a] a
ix i = lens (!! i) -- getter
(\s b -> take i s ++ b : drop (i+1) s) -- setter
Usage:
>>> [1..9] ^. ix 3
4
>>> [1..9] & ix 3 %~ negate
[1,2,3,-4,5,6,7,8,9]
When getting, the setter is completely unused; when setting, the getter is unused. Both are used only when the value is being modified. For instance, here we define a lens for the 1st element of a list, but instead of a legitimate getter we use undefined. Then we use the resulting lens for setting and it works, which proves that the getter wasn't used:
Example1 expression
>>> [1,2,3] & lens undefined (\s b -> b : tail s) .~ 10[10,2,3]
mapped is a setter for everything contained in a functor. You can use it to map over lists, Maybe, or even IO (which is something you can't do with traversed or each).
Here mapped is used to turn a value to all non-Nothing values in a list:
non lets you “relabel” a Maybe by equating Nothing to an arbitrary value (which you can choose):
Example1 expression
>>> Just 1 ^. non 01
Example1 expression
>>> Nothing ^. non 00
The most useful thing about non is that relabeling also works in other direction. If you try to set the “forbidden” value, it'll be turned to Nothing:
Example1 expression
>>> Just 1 & non 0 .~ 0Nothing
Setting anything else works just fine:
Example1 expression
>>> Just 1 & non 0 .~ 5Just 5
Same happens if you try to modify a value:
Example1 expression
>>> Just 1 & non 0 %~ subtract 1Nothing
Example1 expression
>>> Just 1 & non 0 %~ (+ 1)Just 2
non is often useful when combined with at. For instance, if you have a map of songs and their playcounts, it makes sense not to store songs with 0 plays in the map; non can act as a filter that wouldn't pass such entries.
Decrease playcount of a song to 0, and it'll be gone:
Example1 expression
>>> fromList [("Soon",1),("Yesterday",3)] & at "Soon" . non 0 %~ subtract 1fromList [("Yesterday",3)]
Try to add a song with 0 plays, and it won't be added:
Example1 expression
>>> fromList [("Yesterday",3)] & at "Soon" . non 0 .~ 0fromList [("Yesterday",3)]
But it will be added if you set any other number:
Example1 expression
>>> fromList [("Yesterday",3)] & at "Soon" . non 0 .~ 1fromList [("Soon",1),("Yesterday",3)]
non is also useful when working with nested maps. Here a nested map is created when it's missing:
Example1 expression
>>> Map.empty & at "Dez Mona" . non Map.empty . at "Soon" .~ Just 1fromList [("Dez Mona",fromList [("Soon",1)])]
and here it is deleted when its last entry is deleted (notice that non is used twice here):
Example1 expression
>>> fromList [("Dez Mona",fromList [("Soon",1)])] & at "Dez Mona" . non Map.empty . at "Soon" . non 0 %~ subtract 1fromList []
To understand the last example better, observe the flow of values in it:
the map goes into at "Dez Mona"
the nested map (wrapped into Just) goes into non Map.empty
Just is unwrapped and the nested map goes into at "Soon"
Just 1 is unwrapped by non 0
Then the final value – i.e. 1 – is modified by subtract 1 and the result (which is 0) starts flowing backwards:
non 0 sees the 0 and produces a Nothing
at "Soon" sees Nothing and deletes the corresponding value from the map
the resulting empty map is passed to non Map.empty, which sees that it's empty and thus produces Nothing
at "Dez Mona" sees Nothing and removes the key from the map
Rewrite by applying a rule everywhere you can. Ensures that the rule cannot be applied anywhere in the result.
Usually transformOf is more appropriate, but rewriteOf can give better compositionality. Given two single transformations f and g, you can construct \a -> f a <|> g a which performs both rewrites until a fixed point.
It's most useful in chains, because it lets you mix lenses and ordinary functions. Suppose you have a record which comes from some third-party library and doesn't have any lens accessors. You want to do something like this:
value ^. _1 . field . at 2
However, field isn't a getter, and you have to do this instead:
field (value ^. _1) ^. at 2
but now value is in the middle and it's hard to read the resulting code. A variant with to is prettier and more readable:
Apply an action to all targets and discard the result (like mapM_ or traverse_):
Example1 expression
>>> traverseOf_ both putStrLn ("hello", "world")helloworld
Works with anything that allows getting, including lenses and getters (so, anything except for ASetter). Should be faster than traverseOf when you don't need the result.
This is an equivalent of local which lets you apply a getter to your environment instead of merely applying a function (and it also lets you change the type of the environment).
When you're in a state monad, this function lets you operate on a part of your state. For instance, if your state was a record containing a position field, after zooming position would become your whole state (and when you modify it, the bigger structure would be modified as well).
(Your State / StateT or RWS / RWST can be anywhere in the stack, but you can't use zoom with arbitrary MonadState because it doesn't provide any methods to change the type of the state. See this issue for details.)
For the sake of the example, let's define some types first:
data Position = Position {
_x, _y :: Int }
data Player = Player {
_position :: Position,
... }
data Game = Game {
_player :: Player,
_obstacles :: [Position],
... }
concat <$> mapM makeLenses [''Position, ''Player, ''Game]
Now, here's an action that moves the player north-east:
moveNE :: State Game ()
moveNE = do
player.position.x += 1
player.position.y += 1
With zoom, you can use player.position to focus just on a part of the state:
moveNE :: State Game ()
moveNE = do
zoom (player.position) $ do
x += 1
y += 1
You can just as well use it for retrieving things out of the state:
getCoords :: State Game (Int, Int)
getCoords = zoom (player.position) ((,) <$>use x <*>use y)
Or more explicitly:
getCoords = zoom (player.position) $ do
x' <- use x
y' <- use y
return (x', y')
When you pass a traversal to zoom, it'll work as a loop. For instance, here we move all obstacles:
moveObstaclesNE :: State Game ()
moveObstaclesNE = do
zoom (obstacles.each) $ do
x += 1
y += 1
If the action returns a result, all results would be combined with <> – the same way they're combined when ^. is passed a traversal. In this example, moveObstaclesNE returns a list of old coordinates of obstacles in addition to moving them:
moveObstaclesNE = do
xys <- zoom (obstacles.each) $ do
-- Get old coordinates.
x' <- use x
y' <- use y
-- Update them.
x .= x' + 1
y .= y' + 1
-- Return a single-element list with old coordinates.
return [(x', y')]
...
Finally, you might need to write your own instances of Zoom if you use newtyped transformers in your monad stack. This can be done as follows:
import Lens.Micro.Mtl.Internal
type instance Zoomed (MyStateT s m) = Zoomed (StateT s m)
instance Monad m => Zoom (MyStateT s m) (MyStateT t m) s t where
zoom l (MyStateT m) = MyStateT (zoom l m)
This can be used to chain lens operations using op= syntax
rather than op~ syntax for simple non-type-changing cases.
>>> (10,20) & _1 .~ 30 & _2 .~ 40
(30,40)
Example1 expression
>>> (10,20) &~ do _1 .= 30; _2 .= 40(30,40)
This does not support type-changing assignment, e.g.
preuse is (^?) (or preview) which implicitly operates on the state – it takes the state and applies a traversal (or fold) to it to extract the 1st element the traversal points at.
view is a synonym for (^.), generalised for MonadReader (we are able to use it instead of (^.) since functions are instances of the MonadReader class):
Example1 expression
>>> view _1 (1, 2)1
When you're using Reader for config and your config type has lenses generated for it, most of the time you'll be using view instead of asks:
doSomething :: (MonadReader Config m) => m Int
doSomething = do
thingy <- view setting1 -- same as “asks (^. setting1)”
anotherThingy <- view setting2
...
lensField is more complicated – it takes fields which are prefixed with the name of the type they belong to (e.g. “fooFieldName” for “Foo”), strips that prefix, and generates a class called “HasFieldName” with a single method called “fieldName”. If some fields are prefixed with underscores, underscores would be stripped too, but then fields without underscores won't have any lenses generated for them. Also note that e.g. “foolish” won't have a lens called “lish” generated for it – the prefix must be followed by a capital letter (or else it wouldn't be camel case).
lensClass isn't used (i.e. defined as const Nothing)
lensClass just adds “Has” to the name of the type (so for “Person” the generated class would be called “HasPerson” and the type-specific lens in that class would be called “person”)
Decide whether generation of classes is allowed at all.
If this is disabled, neither makeFields nor makeClassy would work, regardless of values of lensField or lensClass. On the other hand, if lensField and lensClass don't generate any classes, enabling this won't have any effect.
This option is disabled by default. The downside of enabling it is that it can lead to space-leaks and code-size/compile-time increases when lenses are generated for large records.
When you have a lazy lens, you can get a strict lens from it by composing with ($!):
This option is enabled by default. Disable it if you want to write the signature by yourself – for instance, if the signature should be more restricted, or if you want to write haddocks for the lens (as haddocks are attached to the signature and not to the definition).
Generate “updateable” optics. When turned off, SimpleFolds will be generated instead of Traversals and SimpleGetters will be generated instead of Lenses.
This option is enabled by default. Disabling it can be useful for types with invariants (also known as “types with smart constructors”) – if you generate updateable optics, anyone would be able to use them to break your invariants.
This lets you choose whether a class would be generated for the type itself (like makeClassy does). If so, you can choose the name of the class and the name of the type-specific lens.
This lets you choose which fields would have lenses generated for them and how would those lenses be called. To do that, you provide a function that would take a field name and output a list (possibly empty) of lenses that should be generated for that field.
Here's the full type of the function you have to provide:
Name -> -- The datatype lenses are being generated for
[Name] -> -- A list of all fields of the datatype
Name -> -- The current field
[DefName] -- A list of lens names
Most of the time you won't need the first 2 parameters, but sometimes they are useful – for instance, the list of all fields would be useful if you wanted to implement a slightly more complicated rule like “if some fields are prefixed with underscores, generate lenses for them, but if no fields are prefixed with underscores, generate lenses for all fields”.
As an example, here's a function used by default. It strips “_” off the field name, lowercases the next character after “_”, and skips the field entirely if it doesn't start with “_”:
lensField strips “_” off the field name, lowercases the next character after “_”, and skips the field entirely if it doesn't start with “_” (you can see how it's implemented in the docs for lensField)
lensClass isn't used (i.e. defined as const Nothing)
Generate overloaded lenses without ad-hoc classes; useful when there's a collection of fields that you want to make common for several types.
Like makeFields, each lens is a member of a class. However, the classes are per-type and not per-field. Let's take the following type:
data Person = Person {
_name :: String,
_age :: Double }
makeClassy would generate a single class with 3 methods:
class HasPerson c where
person :: Lens' c Person
age :: Lens' c Double
age = person.age
name :: Lens' c String
name = person.name
And an instance:
instance HasPerson Person where
person = id
name = ...
age = ...
So, you can use name and age to refer to the _name and _age fields, as usual. However, the extra lens – person – allows you to do a kind of subtyping. Let's say that there's a type called Worker and every worker has the same fields that a person has, but also a job. If you were using makeFields, you'd do the following:
However, with makeClassy you can say “every worker is a person” in a more principled way:
data Worker = Worker {
_workerPerson :: Person,
_job :: String }
makeClassy ''Worker
instance HasPerson Worker where person = workerPerson
Now you can use age and name to access name/age of a Worker, but you also can use person to “downgrade” a Worker to a Person (and e.g. apply some Person-specific function to it).
Unlike makeFields, makeClassy doesn't make use of prefixes. _workerPerson could've just as well been named _foobar.
This lets you deal with several data types having same fields. For instance, let's say you have Foo and Bar, and both have a field named x. To avoid those fields clashing, you would have to use prefixes:
data Foo a = Foo {
fooX :: Int,
fooY :: a }
data Bar = Bar {
barX :: Char }
However, if you use makeFields on both Foo and Bar now, it would generate lenses called x and y – and x would be able to access both fooX and barX! This is done by generating a separate class for each field, and making relevant types instances of that class:
class HasX s a | s -> a where
x :: Lens' s a
instance HasX (Foo a) Int where
x :: Lens' (Foo a) Int
x = ...
instance HasX Bar Char where
x :: Lens' Bar Char
x = ...
class HasY s a | s -> a where
y :: Lens' s a
instance HasY (Foo a) a where
y :: Lens' (Foo a) a
y = ...
(There's a minor drawback, though: you can't perform type-changing updates with these lenses.)
If you only want to make lenses for some fields, you can prefix them with underscores – the rest would be untouched. If no fields are prefixed with underscores, lenses would be created for all fields.
The prefix must be the same as the name of the name of the data type (not the constructor). If you don't like this behavior, use makeLensesWithabbreviatedFields – it allows any prefix (and even different prefixes).
If you want to use makeFields on types declared in different modules, you can do it, but then you would have to export the Has* classes from one of the modules – makeFields creates a class if it's not in scope yet, so the class must be in scope or else there would be duplicate classes and you would get an “Ambiguous occurrence” error.
To use it, you have to enable Template Haskell first:
{-# LANGUAGE TemplateHaskell #-}
Then, after declaring the datatype (let's say Foo), add makeLenses ''Foo on a separate line (if you do it before the type is declared, you'll get a “not in scope” error – see the section at the top of this page):
This would generate the following lenses, which can be used to access the fields of Foo:
x :: Lens' Foo Int
x f foo = (\x' -> foo {_x = x'}) <$> f (_x foo)
y :: Lens' Foo Bool
y f foo = (\y' -> foo {_y = y'}) <$> f (_y foo)
(If you don't want a lens to be generated for some field, don't prefix it with “_”.)
If you want to create lenses for many types, you can do it all in one place like this (of course, instead you just can use makeLenses several times if you feel it would be more readable):
data Foo = ...
data Bar = ...
data Quux = ...
concat<$>mapMmakeLenses [''Foo, ''Bar, ''Quux]
When the data type has type parameters, it's possible for a lens to do a polymorphic update – i.e. change the type of the thing along with changing the type of the field. For instance, with this type
data Foo a = Foo {
_x :: a,
_y :: Bool }
the following lenses would be generated:
x :: Lens (Foo a) (Foo b) a b
y :: Lens' (Foo a) Bool
However, when there are several fields using the same type parameter, type-changing updates are no longer possible:
Finally, when the type has several constructors, some of fields may not be always present – for those, a Traversal is generated instead. For instance, in this example y can be present or absent:
data FooBar
= Foo { _x :: Int, _y :: Bool }
| Bar { _x :: Int }
So, to get _y, you'd have to either use (^?) if you're not sure it's there, or (^?!) if you're absolutely sure (and if you're wrong, you'll get an exception). Setting and updating _y can be done as usual.
Like makeLenses, but lets you choose your own names for lenses:
data Foo = Foo {foo :: Int, bar :: Bool}
makeLensesFor [("foo", "fooLens"), ("bar", "_bar")] ''Foo
would create lenses called fooLens and _bar. This is useful, for instance, when you don't want to prefix your fields with underscores and want to prefix lenses with underscores instead.
If you give the same name to different fields, it will generate a Traversal instead:
To see what exactly you can customise, look at the “Configuring lens rules” section. Usually you would build upon the lensRules configuration, which is used by makeLenses:
Generate simple (monomorphic) lenses even when type-changing lenses are possible – i.e. Lens' instead of Lens and Traversal' instead of Traversal. Just in case, here's an example of a situation when type-changing lenses would be normally generated:
Rules used to generate lenses. The fields are intentionally not exported; to create your own rules, see lenses in the “Configuring lens rules” section. You'd have to customise one of the existing rulesets; for an example of doing that, see makeLensesWith.
packed lets you convert between String and Text (strict or lazy). It can be used as a replacement for pack or as a way to modify some String if you have a function like Text -> Text.