Traversals as multilenses: What would be an example?
I'm currently working on understanding the lens
library in detail by following the explanation in https://en.wikibooks.org/wiki/Haskell/Lenses_and_functional_references#The_scenic_route_to_lenses, which starts with a Traversal
and then introduces the Lens
. The wiki makes the distinction that a Traversal
can have multiple targets, while a Lens
has a single target.
This arguments is also made in the documentation for Traversal
, "[Traversals] have also been known as multilenses".
What would be example code to illustrate this distinction? E.g. how can I use a Traversal
to get or set multiple values in a way I cannot do with a Lens
?
Suppose you have a type
data Pair a = Pair a a
This offers two natural lenses and two additional natural traversals.
-- Work with the first or second component
_1, _2 :: Lens' (Pair a) a
-- Work with both components, either left to
-- right or right to left
forwards, backwards :: Traversal' (Pair a) a
There are fewer things you can do with a traversal than a lens, but you (often) get more traversals than lenses.