Lenses

A Lens provides access to a particular part of a data structure.

Lenses express a high-level pattern for composition and in that sense belong firmly in Chapter 3, Patterns for Composition. However, the concept of Lens is also deeply entwined with Foldable and Traversable, and so we describe it in this chapter instead.

Lenses relate to the getter and setter functions, which also describe access to parts of data structures. To find our way to the Lens abstraction (as per Edward Kmett's Lens library), we'll start by writing a getter and setter to access the root node of a tree.

Deriving Lens

Let's return to our Tree type from earlier:

data Tree a = Node a (Tree a) (Tree a) | Leaf a deriving Show intTree = Node 2 (Leaf 3) (Node 5 (Leaf 7) (Leaf ...

Get Haskell Design Patterns now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.