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 a value deep inside an immutable structure can mean taking the structure apart layer by layer, changing the value, then rebuilding it. A lens gives a concise way to focus on that value without writing the unwrapping and rewrapping by hand. section 2.1.2

type Suffix  = String
type PersonTitle = (Suffix, PersonName)
  
personName :: PersonTitle -> PersonName
personName title = view _2 title                 #1
  
getFirstName1 :: PersonTitle -> String
getFirstName1 title = view _1 (personName title) #2  
  
getFirstName2 :: PersonTitle -> String
getFirstName2 title = view (_2 . _1) title       #3
  
-- getFirstName ("Mr.", johnDoeName) == "John"

The tuple example contrasts two separate `view` calls with one composed focus, `_2 . _1`, for reading a 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"

For a `Person` record, `makeLenses` supplies a `name` lens; `view (name . _1)` then reads the first name. These examples show querying, not an update. section 2.1.2

How Functional Design and Architecture: Examples in Haskell covers it

How deep it goes
Explains the update problem and demonstrates composed queries, but does not show an update or lens internals.
Examples
Compares separate tuple queries with a composed query and reads a first name from a record.
What it assumes
Assumes familiarity with Haskell tuples and records while explaining why immutable nested updates become cumbersome.
What you can do after
Apply it via the Haskell lens library to query nested tuple and record fields with `view`.
How it connects
Connects lenses to immutable data structures, tuples, records, composition, and generated accessors.

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.