In functional programming, a lens is a composable field accessor. Lenses allow nested data structures to be manipulated in a concise and side-effect-free way.
In functional programming, a lens is a composable field accessor. Lenses allow nested data structures to be manipulated in a concise and side-effect-free way.
Lenses define a set
function and a get
function. Given a value a
of type A
and a value b
of type B
, set b a
returns a new value a'
of type A
with some field inside set to b
. Given a value a
of type A
, get a
returns the value b
of type B
contained in a
.
To constitute a lens, get
and set
must follow a few straightforward laws:
Given
a
andb
,get (set b a) = b
.Given
a
,b
, andb'
,get (set b' (set b a)) = b'
.Given
a
andb
,set (get a) a = a
.
Because lenses follow these laws, they are safe to compose. This makes them suitable for manipulating nested data structures in a concise way.