liveBook · Manning

Lens

As explained in Functional Design and Architecture: Examples in Haskell

The lens library is a Haskell library for composable querying and updating of focused parts of data structures.

Updating an immutable value means creating a replacement. For a deeply nested record or tuple, manually unwrapping each layer, changing one field, and rebuilding every layer creates boilerplate that hides the intent. A lens focuses on part of a structure so querying or changing that part can stay concise and readable. section 2.1.2

Lenses compose: a lens for a person name can be combined with a lens for the first element of that name. The composed focus expresses the path directly, rather than exposing each intermediate structure to application code. section 2.1.2

Focus a nested first name

Given a title paired with a name, `view _2` selects the name and `view (_2 . _1)` selects its first-name component in one expression. For records, generated lenses can focus the `_name` field, then compose with `_1` to read the first name. section 2.1.2

data Person = Person { _name :: PersonName       #1
                     , _age :: Age }
  
person = Person ("Jane", "Doe") 31
 
makeLenses ''Person                              #2
  
getFirstName :: Person -> String
getFirstName person = view (name . _1) person    #3
  
-- getFirstName janeDoe == "Jane"

A record example shows generated field lenses composed with a tuple lens to query a nested value. section 2.1.2

How Functional Design and Architecture: Examples in Haskell covers it

How deep it goes
Explains the boilerplate problem and demonstrates composed reads, including generated record lenses, without defining lens internals.
Examples
Uses titled names and Person records to compose tuple and generated field lenses with `view`.
What it assumes
Assumes familiarity with immutable hierarchical data, tuples, records, and function composition.
What you can do after
Apply it via Haskell lens operations to read focused nested values and avoid manual unwrapping.
How it connects
Connects immutable data structures with records, tuples, composition, and metaprogramming.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Functional Design and Architecture: Examples in Haskell. The section links point to the parts of the book it draws on.