Thinking in Ramda: Lenses
This post is Part 8 of a series about functional programming called Thinking in Ramda.
In Part 6 and Part 7, we learned how to read, update, and transform object properties and array elements in a declarative, immutable way.
Ramda provides a more general tool for performing these operations, the lens.
What is a Lens?
A lens combines a “getter” function and a “setter” function into a single unit. Ramda provides a set of functions for working with lenses.
We can think of a lens as something that focuses on a specific part of a larger data structure.
How Do I Create a Lens?
The most generic way to create a lens in Ramda is with the
lens takes a getter function and a setter function and returns the new lens.
Here we’re using
path as our getter functions and
assocPath as our setter functions.
Note that we had to duplicate the property and path arguments to these functions. Fortunately, Ramda provides nice shortcuts for the most common uses of lenses:
lensPropcreates a lens that focuses on a property of an object.
lensPathcreates a lens that focuses on a nested property of an object.
lensIndexcreates a lens that focuses on an element of an array.
We could rewrite our lenses above with
That’s a lot simpler and gets rid of the duplication. In practice, I find that I almost never need to use the generic
What Can I Do With It?
OK, great, we’ve created some lenses. What can we do with them?
Ramda provides three functions for working with lenses.
viewreads the value of the lens.
setupdates the value of the lens.
overapplies a transformation function to the lens.
over return the entire object with the lens’ focused property modified as specified.
Lenses can be handy if we have a somewhat complex data structure that we want to abstract away from calling code. Rather than exposing the structure or providing a getter, setter, and transformer for every accessible property, we can instead expose lenses.
Client code can then work with our data structure using
over without being coupled to the exact shape of the structure.
We’ve now learned about a lot of what Ramda provides; certainly enough to do most of what we need to do in our programs. Wrap-up reviews the series and mentions some other topics we might want to explore on our own.