This module provides the essential functionality. There are other packages in the microlens family – mix and match them at will. If you're writing an app, you want microlens-platform – it provides the most functionality.
& 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
This operator is useful when you want to modify something several times. For instance, if you want to change 1st and 3rd elements of a tuple, you can write this:
It's often useful when writing lenses. For instance, let's say you're writing ix for Map; if the key is found in the map, you have to apply a function to it and then change the map based on the new value – which requires a lambda, like this:
ix key f map = case Map.lookup key map of
Just val -> (\val' -> Map.insert key val' map) <$> f val
Nothing -> pure map
With (<&>) you can get rid of parentheses and move the long lambda expression to the right of the value (like when you use >>=):
ix key f map = case Map.lookup key map of
Just val -> f val <&> \val' -> Map.insert key val' map
Nothing -> pure map
Setter: modifies something in a structure
20 declarations
A setter is, broadly speaking, something that lets you modify a part of some value. Most likely you already know some setters:
(modifies every element in a list; corresponds to mapped)
As you see, a setter takes a function, a value, and applies the function to some part (or several parts) of the value. Moreover, setters can be pretty specific – for instance, a function that modifies the 3rd element of a list is a setter too:
-- Modify 3rd element in a list, if present.
modify3rd :: (a -> a) -> [a] -> [a]
modify3rd f (a:b:c:xs) = a : b : f c : xs
modify3rd _ xs = xs
A nice thing about setters is that they compose easily – you can write map.left and it would be a function that takes a list of Eithers and modifies all of them that are Lefts.
This library provides its own type for setters – ASetter; it's needed so that some functions in this library (like _1) would be usable both as setters and as getters. You can turn an ordinary function like map to a “lensy” setter with sets.
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'.
(%~) 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.
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:
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.
Transform every element by recursively applying a given ASetter in a bottom-up manner with a monadic effect.
Getter: extracts a value from a structure
4 declarations
A getter extracts something from a value; in fact, any function is a getter. However, same as with setters, this library uses a special type for getters so that functions like _1 would be usable both as a setter and a getter. An ordinary function can be turned into a getter with to.
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.
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.
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.
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:
value ^. _1 . to field . at 2
Fold: extracts multiple elements
14 declarations
Folds are getters that can return more than one element (or no elements at all). Except for some rare cases, a fold is the same thing as (s -> [a]); you can use folding to turn any function of type (s -> f a) (where f is Foldable) into a fold.
Folds can be applied to values by using operators like (^..), (^?), etc:
Example1 expression
>>> (1,2) ^.. both[1,2]
A nice thing about folds is that you can combine them with (<>) to concatenate their outputs:
Example1 expression
>>> (1,2,3) ^.. (_2 <> _1)[2,1]
When you need to get all elements of the same type in a complicated structure, (<>) can be more helpful than each:
(Just like setters and getters before, folds can be composed with (.).)
The (<>) trick works nicely with (^?), too. For instance, if you want to get the 9th element of the list, but would be fine with 5th too if the list is too short, you could combine ix 9 and ix 5:
Example3 expressions
>>> [0..9] ^? (ix 9 <> ix 5)Just 9>>> [0..8] ^? (ix 9 <> ix 5)Just 5>>> [0..3] ^? (ix 9 <> ix 5)Nothing
(Unfortunately, this trick won't help you with setting or modifying.)
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.
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.
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:
Returns True if no value returned by a getter (any getter, including lenses,
traversals, and folds) satisfies a predicate.
Example3 expressions
>>> noneOf each (=='x') ['x','x']False>>> noneOf each (=='x') ['x','y']False>>> noneOf each (=='x') ['y','y']True
Lens: a combined getter-and-setter
9 declarations
Lenses are composable “pointers” at values inside some bigger structure (e.g. _1 points at the first element of a tuple). You can use (^.) to get, (.~) to set, and (%~) to modify:
To apply a monadic action (or an Applicative action, or even a Functor action) to the pointed value, just apply the lens directly or use traverseOf (or traverseOf_ if you don't need the result):
Example1 expression
>>> traverseOf_ _1 print (1,2)1
Example2 expressions
>>> _1 id (Just 1, 2)Just (1, 2)>>> _1 id (Nothing, 2)Nothing
A Lens can only point at a single value inside a structure (unlike a Traversal).
(.) composes lenses (i.e. if a B is a part of A, and a C is a part of B, then b.c lets you operate on C inside A). You can create lenses with lens, or you can write them by hand.
There are several ways to get lenses for some datatype:
They can already be provided by the package, by microlens, or by some other package like microlens-platform.
They can be provided by some unofficial package (like microlens-aeson).
You can get them by combining already existing lenses.
You can derive them with Template Haskell (with microlens-th).
You can write them with lens if you have a setter and a getter. It's a simple and good way.
You can write them manually (sometimes it looks a bit better than the variant with lens, sometimes worse). The generic template is as follows:
somelens :: Lens s t a b
-- “f” is the “a -> f b” function, “s” is the structure.
somelens f s =
let
a = ... -- Extract the value from “s”.
rebuildWith b = ... -- Write a function which would
-- combine “s” and modified value
-- to produce new structure.
in
rebuildWith <$> f a -- Apply the structure-producing
-- function to the modified value.
_1 :: Lens (a, x) (b, x) a b
_1 f (a, x) = (\b -> (b, x)) <$> f a
Here's a more complicated lens, which extracts several values from a structure (in a tuple):
type Age = Int
type City = String
type Country = String
data Person = Person Age City Country
-- This lens lets you access all location-related information about a person.
location :: Lens' Person (City, Country)
location f (Person age city country) =
(\(city', country') -> Person age city' country') <$> f (city, country)
You even can choose to use a lens to present all information contained in the structure (in a different way). Such lenses are called Iso in lens's terminology. For instance (assuming you don't mind functions that can error out), here's a lens which lets you act on the string representation of a value:
string :: (Read a, Show a) => Lens' a String
string f s = read <$> f (show s)
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
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]
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.
Isos (or isomorphisms) are lenses that convert a value instead of targeting a part of it; in other words, inside of every list lives a reversed list, inside of every strict Text lives a lazy Text, and inside of every (a, b) lives a (b, a). Since an isomorphism doesn't lose any information, it's possible to reverse it and use it in the opposite direction by using from from the lens library:
from :: Iso' s a -> Iso' a s
However, it's not possible for microlens to export isomorphisms, because their type depends on Profunctor, which resides in the profunctors library, which is a somewhat huge dependency. So, all isomorphisms included here are lenses instead (and thus you can't use them in the opposite direction).
Should you find yourself in need of true lens-compatible isos, consider microlens-pro, or just lens :^).
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
Traversal: a lens iterating over several elements
19 declarations
Traversals are like lenses but they can point at multiple values. Use (^..) to get all values, (^?) to get the 1st value, (.~) to set values, (%~) to modify them. (.) composes traversals just as it composes lenses. (^.) can be used with traversals as well, but don't confuse it with (^..) – (^..) gets all traversed values, (^.) combines traversed values using the (<>) operation (if the values are instances of Monoid; if they aren't, it won't compile). traverseOf and traverseOf_ apply an action to all pointed values of a traversal.
Traversals don't differ from lenses when it comes to setting – you can use usual (%~) and (.~) to modify and set values. Getting is a bit different, because you have to decide what to do in the case of multiple values. In particular, you can use these combinators (as well as everything else in the “Folds” section):
(^?) gets the 1st value (or Nothing if there are no values)
(^?!) gets the 1st value and throws an exception if there are no values
If you are sure that the traversal will traverse at least one value, you can convert it to a lens with singular.
traversed is a universal traversal for anything that belongs to the Traversable typeclass. However, in many cases each works as well and is shorter and nicer-looking.
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.
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.
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:
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):
_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.
Given a Traversal that knows how to locate immediate children, traverse all of the transitive descendants of a node, including itself.
Prism: a traversal iterating over at most 1 element
5 declarations
Prisms are traversals that always target 0 or 1 values. Moreover, it's possible to reverse a prism, using it to construct a structure instead of peeking into it. Here's an example from the lens library:
>>> over _Left (+1) (Left 2)
Left 3
>>> _Left # 5
Left 5
However, it's not possible for microlens to export prisms, because their type depends on Choice from profunctors. So, all prisms included here are traversals instead (and you can't reverse them).
Should you find yourself in need of true lens-compatible prisms, consider microlens-pro, or just lens :^).
_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.
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)