O'Reilly logo

Haskell Design Patterns by Ryan Lemmer

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required