8 July 2016
Lenses by example
Deep immutable updates are verbose and repetitive. Lenses — composable pairs of a getter and a pure setter — fix that. A step-by-step walkthrough with Ramda.
Hi! I’m Andrii, a JavaScript developer. In my day-to-day work I often deal with immutable data that has a deep hierarchical structure, and the standard tools for working with it turned out to be rather inconvenient. Looking for something better, I arrived at an interesting concept: lenses.
About immutable data
Immutable data has been going through a surge of popularity on the frontend lately; this article can be considered the starting point. The main reason is the problem of change detection, which every JavaScript framework tries to solve one way or another. Using immutable data everywhere is one way to solve it — and in particular it is the main one in the React community.
However, once you start using immutable data you run into a problem with “deep” updates of nested structures. Let’s look at real examples to see what the problem is and whether we can do something about it.
A simple example
Immutable vs mutable
Here is a very simple function that immutably updates a not-very-complicated structure:
const setProps = (state, action) => ({
...state,
rangeSlider: {
...state.rangeSlider,
...pick(['from', 'to', 'left', 'right'], action.payload),
},
})
Pretty verbose, isn’t it? On top of that, state and rangeSlider are each repeated twice, which goes against good practice.
Even this simple example shows what’s wrong with immutable updates. To set a value deep inside a structure, we first have to take the whole structure apart, and then assemble it again with the new values. Hence all the verbosity.
Compare the code above with a plain mutable assignment:
Object.assign(state.rangeSlider, pick(['from', 'to', 'left', 'right'], action.payload))
So by moving from mutable to immutable structures we lose conciseness and readability. Naturally, the functional programming community couldn’t let that happen — and so lenses were born.
What is a lens
To set a value immutably, you have to know how to read it (how to get to it). So a reasonable idea is to keep the functions for reading and for setting a value together, in a single entity. That entity is called a lens.
A lens consists of:
- a
getter— a function that reads the value; - a
setter— a function that sets the value; it must be pure and perform the update immutably.
Creating a lens
To create lenses we’ll use the lens function from Ramda. Its first argument is the getter, the second is the setter. A simple example is a lensProp lens for an object property:
const lensProp = (prop) =>
lens(
// getter: read the property
(obj) => obj[prop],
// setter: set the property immutably
(newVal, obj) => ({ ...obj, [prop]: newVal }),
)
Using a lens
There are two main operations and one interesting one:
view— read data through a lens. The first argument is the lens, the second is the structure to read from:
const a = { key: 2 },
val = view(lensProp('key'), a) // val is 2
set— write data through a lens. The first argument is the lens, the second is the value to set, the third is the data to set it in:
const a = { key: 2 },
newA = set(lensProp('key'), 4, a) // newA is {key: 4}
over— reads the value through the lens withview, applies a function to it, and sets the result back:
const over = (someLens, func, data) => {
const val = view(someLens, data)
const newVal = func(val)
return set(someLens, newVal, data)
}
Practice
const a = { key: 2 },
changedA = over(lensProp('key'), (val) => val + 1, a) // changedA is {key: 3}
That seems to be everything we need, so let’s go back to our example and rewrite the transformation with lensProp:
const setProps = (state, action) =>
over(
lensProp('rangeSlider'),
(slider) => ({ ...slider, ...pick(['from', 'to', 'left', 'right'], action.payload) }),
state,
)
It’s a little shorter and, importantly, there is no repetition: the property name (rangeSlider) isn’t duplicated anymore. This is simply a consequence of the main property of lenses — composability. Lenses are a great example of a highly composable abstraction.
Now let’s make a lens for the from property of rangeSlider. First, put the lens for rangeSlider into a variable:
const lensRangeSlider = lensProp('rangeSlider')
We can define a lens for the from property of any object with the same lensProp:
const lensFrom = lensProp('from')
And now — the magic of composition! To get a lens for from inside rangeSlider, we just compose the two lenses we already have:
const lensRangeSliderFrom = compose(lensRangeSlider, lensFrom)
Let’s try it:
const state = {
rangeSlider: {
from: 3,
to: 4,
},
}
view(lensRangeSliderFrom, state) // 3
set(lensRangeSliderFrom, 5, state)
/* {
rangeSlider: {
from: 5,
to: 4
}
} */
over(lensRangeSliderFrom, (val) => val * 100, state)
/* {
rangeSlider: {
from: 300,
to: 4
}
} */
Quite terse, right? In fact, this particular lens could be defined with Ramda’s built-in lensPath:
const lensRangeSliderFrom = lensPath(['rangeSlider', 'from'])
The result is exactly the same.
A harder example
Imagine we have a structure like this:
const struct = {
id: 2,
description: 'Some cool thing',
users: [
{
id: 1,
fio: {
name: 'Ivan',
},
familyMembers: [
{
id: 5,
role: 'sister',
fio: {
name: 'Olga',
},
},
],
},
],
}
There is an object that contains users with their data, and the users have family members, who have data of their own. The task: write a function that updates a user’s name by their id. Let’s solve it with lenses.
Getting started
First we need to work with the users key of the object. We’ll use the lensProp function we met earlier:
const lensUsers = lensProp('users')
Next we need to work with a particular user, knowing their id. We need a function that takes a user’s id and returns a lens focused on that user.
Defining the getter and the setter
As we said, a lens consists of two functions — a getter and a setter. Let’s define both:
- the getter receives an array and returns the user with the given
id. Let’s write a function that creates such a getter for a particularid:
const makeGetterById = (id) => (array) => array.find((item) => item.id === id)
- the setter receives a new user and the array, and puts the new user in place of the old one with the given
id:
const makeSetterById = (id) => (newItem, array) =>
array.map((item) => (item.id === id ? newItem : item))
Now the function that creates the lens itself:
const lensById = (id) => lens(makeGetterById(id), makeSetterById(id))
Let’s check that it works:
const users = [
{ id: 1, name: 'Ivan' },
{ id: 2, name: 'Oleg' },
]
view(lensById(1), users)
// {"id": 1, "name": "Ivan"}
set(lensById(2), { id: 2, name: 'Olga' }, users)
// [{"id": 1, "name": "Ivan"}, {"id": 2, "name": "Olga"}]
over(lensById(2), (user) => assoc('name', 'Fillip', user), users)
// [{"id": 1, "name": "Ivan"}, {"id": 2, "name": "Fillip"}]
Continuing
It works! Let’s keep going. :) All that’s left is lenses for the fio and name keys. lensProp again:
const lensFio = lensProp('fio')
const lensName = lensProp('name')
Now let’s bring it all together and define a function that, given a user’s id, creates a lens focused on that user’s name:
const lensUserNameById = (id) => compose(lensUsers, lensById(id), lensFio, lensName)
Looks pretty declarative. Let’s try it out:
view(lensUserNameById(1), struct)
// -> "Ivan"
set(lensUserNameById(1), 'Petr', struct)
/* ->
{
"description": "Some cool thing",
"id": 2,
"users": [
{
"familyMembers": [
{
"fio": {
"name": "Olga"
},
"id": 5,
"role": "sister"
}
],
"fio": {
"name": "Petr"
},
"id": 1
}
]
}
*/
over(lensUserNameById(1), (name) => name + '!!!', struct)
/* ->
{
"description": "Some cool thing",
"id": 2,
"users": [
{
"familyMembers": [
{
"fio": {
"name": "Olga"
},
"id": 5,
"role": "sister"
}
],
"fio": {
"name": "Ivan!!!"
},
"id": 1
}
]
}
*/
Done — and a new task
Hooray, we did it! It would seem we can go and rest with a clear conscience, and watch the new episode of our favourite show. But, out of nowhere, we now need to work with the names of a user’s family members. Let’s try to solve the new task faster, reusing as much of what we’ve written as possible. Which lenses do we need?
First, a lens for the users key — we already have it, lensUsers; then the lens that focuses on a user by id — lensById. So let’s create a lens for familyMembers:
const lensFamilyMembers = lensProp('familyMembers')
Next we need a lens that focuses on a family member by id. Sounds familiar, doesn’t it? Can we reuse lensById? Of course we can. Family members work exactly like users: find by id, replace by id.
Then we need lenses for fio and name. We already have those too — lensFio and lensName.
So we have every piece we need. Let’s define the function that creates the lens:
const lensUserMemberFioNameById = (userId, memberId) =>
compose(lensUsers, lensById(userId), lensFamilyMembers, lensById(memberId), lensFio, lensName)
Testing:
view(lensUserMemberFioNameById(1, 5), struct)
// -> "Olga"
set(lensUserMemberFioNameById(1, 5), 'Tanya', struct)
/* ->
{
"description": "Some cool thing",
"id": 2,
"users": [
{
"familyMembers": [
{
"fio": {
"name": "Tanya"
},
"id": 5,
"role": "sister"
}
],
"fio": {
"name": "Ivan"
},
"id": 1
}
]
}
*/
over(lensUserMemberFioNameById(1, 5), (name) => name + '!!!', struct)
/* ->
{
"description": "Some cool thing",
"id": 2,
"users": [
{
"familyMembers": [
{
"fio": {
"name": "Olga!!!"
},
"id": 5,
"role": "sister"
}
],
"fio": {
"name": "Ivan"
},
"id": 1
}
]
}
*/
Everything works as expected.
More requirements
All good — until we suddenly want to address family members not by id but by role. Let’s assume the role is unique. We can easily write a lens that focuses on an item by role.
A function that creates the getter:
const makeGetterByRole = (role) => (array) => array.find((item) => item.role === role)
A function that creates the setter:
const makeSetterByRole = (role) => (newItem, array) =>
array.map((item) => (item.role === role ? newItem : item))
And the function that creates the lens:
const lensByRole = (role) => lens(makeGetterByRole(role), makeSetterByRole(role))
Getting rid of copy-paste
If you reread the article, you’ll notice this is an almost exact copy of lensById. We can easily get rid of the duplication: just move the name of the attribute used to pick the item into the function’s arguments.
The getter factory:
const makeGetterBy = (attr, val) => (array) => array.find((item) => item[attr] === val)
The setter factory:
const makeSetterBy = (attr, val) => (newItem, array) =>
array.map((item) => (item[attr] === val ? newItem : item))
And the lens factory:
const lensBy = (attr) => (val) => lens(makeGetterBy(attr, val), makeSetterBy(attr, val))
With it, we redefine lensById and lensByRole:
const lensById = lensBy('id')
const lensByRole = lensBy('role')
And, by analogy with lensUserMemberFioNameById, we define lensUserMemberFioNameByRole:
const lensUserMemberFioNameByRole = (userId, memberRole) =>
compose(lensUsers, lensById(userId), lensFamilyMembers, lensByRole(memberRole), lensFio, lensName)
Testing:
view(lensUserMemberFioNameByRole(1, 'sister'), struct)
set(lensUserMemberFioNameByRole(1, 'sister'), 'Tanya', struct)
over(lensUserMemberFioNameByRole(1, 'sister'), (name) => name + '!!!', struct)
The result is exactly the same as in the previous example. Clearly, lenses let us write easily reusable, composable code for working with data — code that is also easy to refactor.
Looking back
Remember what we ended up with in the first example:
const setProps = (state, action) =>
over(
lensProp('rangeSlider'),
(slider) => ({ ...slider, ...pick(['from', 'to', 'left', 'right'], action.payload) }),
state,
)
We cheated a little and used over to merge the value of state.rangeSlider with the values from action.payload. This operation can also be extracted into a lens of its own — in fact, any operation on data can be.
Homework, or DIY
Try it yourself. Write a lensByPick function that works like this:
const data = {
key: 'value',
key1: 'value1',
key2: 'value2',
}
view(lensByPick(['key1', 'key2']), data)
// -> {key1: 'value1', key2: 'value2'}
set(lensByPick(['key1', 'key2']), { key1: 'newValue1', key2: 'newValue2', key3: 'newValue3' }, data)
/* ->
{
key: 'value',
key1: 'newValue1',
key2: 'newValue2',
}
*/
over(lensByPick(['key1', 'key2']), (obj) => mapObjIndexed((val) => val + '!!!', obj), data)
/* ->
{
key: 'value',
key1: 'value1!!!',
key2: 'value2!!!',
}
*/
With your lens, our example can be rewritten like this:
const lensRangeSliderByPick = (keys) => compose(lensProp('rangeSlider'), lensByPick(keys))
const setProps = (state, action) =>
set(lensRangeSliderByPick(['from', 'to', 'left', 'right']), action.payload, state)
Further reading
- Ramda — a functional utility library for JavaScript (think Lodash);
- Partial.lenses — an alternative implementation of lenses for JavaScript with a more convenient and consistent API;
- Immutable.js and Mori — good implementations of purely functional data structures that use structural sharing to reduce the memory overhead of writing code in an immutable style;
- DataScript — a data structure that resembles an in-memory database (with indexes, relations and a rich query language). It may suit you if your data is really, really complex (lots of relations) and ordinary data structures are inconvenient even with lenses;
- Immutability is not enough — a good article on how many data-management bugs from mutable code carried over into immutable code.
Thanks for reading!