lens package:lens

Lenses, Folds and Traversals This package comes "Batteries Included" with many useful lenses for the types commonly used from the Haskell Platform, and with tools for automatically generating lenses and isomorphisms for user-supplied data types. The combinators in Control.Lens provide a highly generic toolbox for composing families of getters, folds, isomorphisms, traversals, setters and lenses and their indexed variants. An overview, with a large number of examples can be found in the README. An introductory video on the style of code used in this library by Simon Peyton Jones is available from Internet Archive. A video on how to use lenses and how they are constructed is available on youtube. Slides for that second talk can be obtained from comonad.com. More information on the care and feeding of lenses, including a brief tutorial and motivation for their types can be found on the lens wiki. A small game of pong and other more complex examples that manage their state using lenses can be found in the example folder. Lenses, Folds and Traversals With some signatures simplified, the core of the hierarchy of lens-like constructions looks like: (Local Copy) You can compose any two elements of the hierarchy above using (.) from the Prelude, and you can use any element of the hierarchy as any type it linked to above it. The result is their lowest upper bound in the hierarchy (or an error if that bound doesn't exist). For instance: Minimizing Dependencies If you want to provide lenses and traversals for your own types in your own libraries, then you can do so without incurring a dependency on this (or any other) lens package at all. e.g. for a data type:
data Foo a = Foo Int Int a
You can define lenses such as
-- bar :: Lens' (Foo a) Int
bar :: Functor f => (Int -> f Int) -> Foo a -> f (Foo a)
bar f (Foo a b c) = fmap (\a' -> Foo a' b c) (f a)
-- quux :: Lens (Foo a) (Foo b) a b
quux :: Functor f => (a -> f b) -> Foo a -> f (Foo b)
quux f (Foo a b c) = fmap (Foo a b) (f c)
without the need to use any type that isn't already defined in the Prelude. And you can define a traversal of multiple fields with Control.Applicative.Applicative:
-- traverseBarAndBaz :: Traversal' (Foo a) Int
traverseBarAndBaz :: Applicative f => (Int -> f Int) -> Foo a -> f (Foo a)
traverseBarAndBaz f (Foo a b c) = Foo <$> f a <*> f b <*> pure c
What is provided in this library is a number of stock lenses and traversals for common haskell types, a wide array of combinators for working them, and more exotic functionality, (e.g. getters, setters, indexed folds, isomorphisms).
Build a Lens from a getter and a setter.
lens :: Functor f => (s -> a) -> (s -> b -> t) -> (a -> f b) -> s -> f t
>>> s ^. lens getter setter
getter s
>>> s & lens getter setter .~ b
setter s b
>>> s & lens getter setter %~ f
setter s (f (getter s))
lens :: (s -> a) -> (s -> a -> s) -> Lens' s a
Control.Exception provides an example of a large open hierarchy that we can model with prisms and isomorphisms. Additional combinators for working with IOException results can be found in System.IO.Error.Lens. The combinators in this module have been generalized to work with MonadCatch instead of just IO. This enables them to be used more easily in Monad transformer stacks.
You can derive lenses automatically for many data types:
import Control.Lens

data FooBar a
= Foo { _x :: [Int], _y :: a }
| Bar { _x :: [Int] }
makeLenses ''FooBar
This defines the following lenses:
x :: Lens' (FooBar a) [Int]
y :: Traversal (FooBar a) (FooBar b) a b
You can then access the value of _x with (^.), the value of _y – with (^?) or (^?!) (since it can fail), set the values with (.~), modify them with (%~), and use almost any other combinator that is re-exported here on those fields. The combinators here have unusually specific type signatures, so for particularly tricky ones, the simpler type signatures you might want to pretend the combinators have are specified as well. More information on how to use lenses is available on the lens wiki: http://github.com/ekmett/lens/wiki
A Lens is actually a lens family as described in http://comonad.com/reader/2012/mirrored-lenses/. With great power comes great responsibility and a Lens is subject to the three common sense Lens laws: 1) You get back what you put in:
view l (set l v s)  ≡ v
2) Putting back what you got doesn't change anything:
set l (view l s) s  ≡ s
3) Setting twice is the same as setting once:
set l v' (set l v s) ≡ set l v' s
These laws are strong enough that the 4 type parameters of a Lens cannot vary fully independently. For more on how they interact, read the "Why is it a Lens Family?" section of http://comonad.com/reader/2012/mirrored-lenses/. There are some emergent properties of these laws: 1) set l s must be injective for every s This is a consequence of law #1 2) set l must be surjective, because of law #2, which indicates that it is possible to obtain any v from some s such that set s v = s 3) Given just the first two laws you can prove a weaker form of law #3 where the values v that you are setting match:
set l v (set l v s) ≡ set l v s
Every Lens can be used directly as a Setter or Traversal. You can also use a Lens for Getting as if it were a Fold or Getter. Since every Lens is a valid Traversal, the Traversal laws are required of any Lens you create:
l purepure
fmap (l f) . l g ≡ getCompose . l (Compose . fmap f . g)
type Lens s t a b = forall f. Functor f => LensLike f s t a b
A Lens s t a b is a purely functional reference. While a Traversal could be used for Getting like a valid Fold, it wasn't a valid Getter as a Getter can't require an Applicative constraint. Functor, however, is a constraint on both.
type Lens s t a b = forall f. Functor f => (a -> f b) -> s -> f t
Every Lens is a valid Setter. Every Lens can be used for Getting like a Fold that doesn't use the Applicative or Contravariant. Every Lens is a valid Traversal that only uses the Functor part of the Applicative it is supplied. Every Lens can be used for Getting like a valid Getter. Since every Lens can be used for Getting like a valid Getter it follows that it must view exactly one element in the structure. The Lens laws follow from this property and the desire for it to act like a Traversable when used as a Traversal. In the examples below, getter and setter are supplied as example getters and setters, and are not actual functions supplied by this package.
A Lens or Traversal can be used to take the role of Traversable in Control.Parallel.Strategies, enabling those combinators to work with monomorphic containers.
A Fold can be used to take the role of Foldable in Control.Seq.
Lazy ByteString lenses.
Lenses and traversals for complex numbers
Smart and naïve generic traversals given Data instances. template, uniplate, and biplate each build up information about what types can be contained within another type to speed up Traversal.
Traversals for manipulating parts of a list. Additional optics for manipulating lists are present more generically in this package. The Ixed class allows traversing the element at a specific list index.
>>> [0..10] ^? ix 4
Just 4
>>> [0..5] & ix 4 .~ 2
[0,1,2,3,2,5]
>>> [0..10] ^? ix 14
Nothing
>>> [0..5] & ix 14 .~ 2
[0,1,2,3,4,5]
The Cons and AsEmpty classes provide Prisms for list constructors.
>>> [1..10] ^? _Cons
Just (1,[2,3,4,5,6,7,8,9,10])
>>> [] ^? _Cons
Nothing
>>> [] ^? _Empty
Just ()
>>> _Cons # (1, _Empty # ()) :: [Int]
[1]
Additionally, Snoc provides a Prism for accessing the end of a list. Note that this Prism always will need to traverse the whole list.
>>> [1..5] ^? _Snoc
Just ([1,2,3,4],5)
>>> _Snoc # ([1,2],5)
[1,2,5]
An instance of Plated allows for finding locations in the list where a traversal matches.
>>> [Nothing, Just 7, Just 3, Nothing] & deep (ix 0 . _Just) +~ 10
[Nothing,Just 17,Just 3,Nothing]
An instance of Reversing provides an Iso between a list and its reverse.
>>> "live" & reversed %~ ('d':)
"lived"
It's possible to work under a prefix or suffix of a list using Prefixed and Suffixed.
>>> "preview" ^? prefixed "pre"
Just "view"
>>> suffixed ".o" # "hello"
"hello.o"
At present, Data.List.Lens re-exports Prefixed and Suffixed for backwards compatibility, as prefixed and suffixed used to be top-level functions defined in this module. This may change in a future major release of lens. Finally, it's possible to traverse, fold over, and map over index-value pairs thanks to instances of TraversableWithIndex, FoldableWithIndex, and FunctorWithIndex.
>>> imap (,) "Hello"
[(0,'H'),(1,'e'),(2,'l'),(3,'l'),(4,'o')]
>>> ifoldMap replicate "Hello"
"ellllloooo"
>>> itraverse_ (curry print) "Hello"
(0,'H')
(1,'e')
(2,'l')
(3,'l')
(4,'o')
One of most commonly-asked questions about this package is whether it provides lenses for working with Map. It does, but their uses are perhaps obscured by their genericity. This module exists to provide documentation for them. Map is an instance of At, so we have a lenses on values at keys:
>>> Map.fromList [(1, "world")] ^.at 1
Just "world"
>>> at 1 .~ Just "world" $ Map.empty
fromList [(1,"world")]
>>> at 0 ?~ "hello" $ Map.empty
fromList [(0,"hello")]
We can traverse, fold over, and map over key-value pairs in a Map, thanks to its TraversableWithIndex, FoldableWithIndex, and FunctorWithIndex instances.
>>> imap const $ Map.fromList [(1, "Venus")]
fromList [(1,1)]
>>> ifoldMap (\i _ -> Sum i) $ Map.fromList [(2, "Earth"), (3, "Mars")]
Sum {getSum = 5}
>>> itraverse_ (curry print) $ Map.fromList [(4, "Jupiter")]
(4,"Jupiter")
>>> itoList $ Map.fromList [(5, "Saturn")]
[(5,"Saturn")]
A related class, Ixed, allows us to use ix to traverse a value at a particular key.
>>> ix 2 %~ ("New " ++) $ Map.fromList [(2, "Earth")]
fromList [(2,"New Earth")]
>>> preview (ix 8) $ Map.empty
Nothing
Additionally, Map has TraverseMin and TraverseMax instances, which let us traverse over the value at the least and greatest keys, respectively.
>>> preview traverseMin $ Map.fromList [(5, "Saturn"), (6, "Uranus")]
Just "Saturn"
>>> preview traverseMax $ Map.fromList [(5, "Saturn"), (6, "Uranus")]
Just "Uranus"