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.
vvaluelens :: (s -> a) -> (s -> b -> t) -> Lensstab
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]
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
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.