Skip to content
Tutorials Center
My learning

Topics

Lesson 43 of 57 ยท Advanced types

Lenses and Optics

Learn what Haskell lenses are: getters and setters as composable values, view, over and set, the lens and optics libraries, plus a runnable JavaScript stand-in.

Updating a field deep inside an immutable record is awkward. In Haskell, records never change in place, so changing the city in person.address.city means rebuilding the person, the address and the city field by hand. With two levels this is annoying; with five it is unreadable.

A lens solves this. It is a first-class value that knows how to read one part of a structure and how to rebuild the structure with a new value in that part. Because lenses are ordinary values, you can compose them with . and focus as deep as you like. This lesson builds the idea from scratch, then shows how the real libraries package it.

Real Haskell is not installed on this site, so Haskell blocks are read-only. The runnable examples are JavaScript stand-ins that follow the same design.

The problem: nested updates

Take a small model built with records:

HASKELL
data Address = Address { street :: String, city :: String }
data Person  = Person  { name :: String, address :: Address }

Record update syntax works for one level:

HASKELL
moveTo :: String -> Person -> Person
moveTo newCity p =
  p { address = (address p) { city = newCity } }

It is already clumsy, and every extra level adds another nested update. Reading is easy (city (address p)), but writing is not.

A lens is a getter plus a setter

The simplest possible lens is a pair of functions:

HASKELL
data Lens s a = Lens
  { getter :: s -> a
  , setter :: a -> s -> s
  }

s is the whole structure and a is the part you focus on. For the city field:

HASKELL
cityL :: Lens Address String
cityL = Lens city (\c a -> a { city = c })

Three operations cover most uses:

  • view reads the focus: view l s = getter l s.
  • set replaces it: set l x s = setter l x s.
  • over transforms it with a function: over l f s = setter l (f (getter l s)) s.

over is the workhorse. set l x is just over l (const x).

Composition is the point

Two lenses compose when the focus of the first is the structure of the second. If addressL focuses a Person on its Address, and cityL focuses an Address on its city, the composition focuses a Person on its city. The getter goes outward-in, and the setter rebuilds inward-out:

HASKELL
compose :: Lens a b -> Lens b c -> Lens a c
compose outer inner = Lens
  { getter = getter inner . getter outer
  , setter = \c a -> setter outer (setter inner c (getter outer a)) a
  }

Read the setter slowly: fetch the middle part, update it with the inner setter, then put that updated middle back with the outer setter. That is exactly the hand-written nested update, but written once.

What a lens holds

Getter Reads the focused part.
Setter Rebuilds the whole with a new part.
1 / 3

A runnable stand-in

Here is the getter/setter version in JavaScript. This is the simple "pair of functions" lens, not the encoding used by the real libraries, but view, set, over and composition behave the same way.

JS Lenses as getter/setter pairs

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The original person is not modified: every update returns a fresh object, just as in Haskell.

Lenses compose with plain .

In the real lens library a lens is not a record of two functions. It is a single function type that works for any Functor:

HASKELL
type Lens s a = forall f. Functor f => (a -> f a) -> s -> f s

That looks odd, but it has a lovely consequence: a lens is a function, so ordinary function composition . composes lenses. You write them in the same left-to-right order as field access:

HASKELL
# LANGUAGE TemplateHaskell #
import Control.Lens

data Address = Address { _street :: String, _city :: String }
data Person  = Person  { _name :: String, _address :: Address }

makeLenses ''Address
makeLenses ''Person

-- makeLenses generated: street, city, name, address

person ^. address . city                       -- view
person & address . city .~ "Paris"             -- set
person & address . city %~ map toUpper         -- over

The operators are terse by design: ^. is view, .~ is set, %~ is over, and & is reverse application so you can pipe a value through several updates. The leading underscore on field names is a convention that tells makeLenses to generate lenses named without it.

Different Functors give different powers. With Identity the lens acts as a setter. With Const it acts as a getter. That is the trick behind the encoding, and why one lens value supports both reading and writing.

Beyond lenses: the optics family

A lens focuses on exactly one part that always exists. Other situations call for other shapes, and together they are called optics:

  • Lens: exactly one focus, such as a record field.
  • Prism: zero or one focus, for one branch of a sum type, such as _Just or _Left.
  • Traversal: zero or more foci, such as every element of a list.
  • Iso: a lossless conversion in both directions, such as String and Text.

They all compose with ., and the result is the weakest of the pieces. A lens followed by a traversal is a traversal.

HASKELL
-- uppercase the city of every person in a list
people & traverse . address . city %~ map toUpper

-- the first element of a list, if any
[10, 20, 30] ^? ix 0          -- Just 10
JS A traversal: update every focus

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Lens or optics library?

Two libraries are common:

  • lens is the original, huge and feature-rich, with a very large dependency list and famously confusing type errors.
  • optics (with optics-core) offers the same concepts with a smaller surface and friendlier error messages, at the price of a slightly different API (optics are composed with % instead of .).
  • microlens is a tiny subset with almost no dependencies, good for libraries.

For a small program, record update syntax or the RecordWildCards extension from GHC Extensions may be enough. Reach for lenses when you have deeply nested immutable state, such as an application model or a configuration tree, and many updates to it.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What two things does the simplest lens bundle?

    A lens knows how to read a focused part and how to rebuild the whole structure with a new value in that part.
  2. 2. What does over do?

    over l f applies f to the focus. set is the special case where f ignores its input and returns a constant.
  3. 3. In the lens library, how do you compose a lens for address with a lens for city?

    The van Laarhoven encoding makes a lens an ordinary function, so plain composition with . works.
  4. 4. Which optic focuses on one branch of a sum type, such as Just?

    A prism has zero or one focus, which fits a single constructor of a sum type.

Summary

  • A lens is a first-class getter/setter pair that focuses on one part of an immutable structure.
  • view reads, set replaces and over transforms the focus; set is over with a constant.
  • Lenses compose, which removes nested record-update boilerplate.
  • The real lens library encodes a lens as a Functor-polymorphic function, so . composes lenses.
  • Prisms, traversals and isos extend the idea to sum types, many foci and conversions.
  • Choose lens, optics or microlens by how much power and how many dependencies you want.

Next: Effect Systems and Free Monads.