▲ | dkarl 3 days ago | ||||||||||||||||||||||||||||||||||||||||||||||
The problem most programmers would be familiar with is making an update inside a deeply nested immutable data structure. For example, suppose you want to update a user's billing address, and you have an immutable data structure that looks like this:
The structure is immutable, so you can't make the update in place. On the other hand, you're only changing one field, so it would be wasteful to make a complete deep copy. The efficient way to create an updated instance is to create a new user instance and a new billingInfo instance while reusing the name, subscription, and status instances.You can think of this as the equivalent of a setter for immutable data structures. This is an artificial example, because the cost of making a deep copy of this user structure is probably not that bad, and the boilerplate to make an efficient update is not all that bad, either. You would use an optics library when 1) you need efficient updates and 2) it's worth investing a little effort to hide the boilerplate. Optics also let you concisely express access into a deeply nested structure, the getter paired with the setter. In my experience, updates are the motivation for setting up optics, and concise access is a nice thing you get as a bonus. | |||||||||||||||||||||||||||||||||||||||||||||||
▲ | afandian 2 days ago | parent | next [-] | ||||||||||||||||||||||||||||||||||||||||||||||
Is this much different from Clojure’s `update-in` ? You just express a path as a sequence of keys / indexes, and a function to apply, and let the persistent data structure get updated. It's very neat. But depends on a type system built for this kind of use. | |||||||||||||||||||||||||||||||||||||||||||||||
▲ | usrusr 3 days ago | parent | prev [-] | ||||||||||||||||||||||||||||||||||||||||||||||
Does it offer creating a mutable view on top of the immutable structure that can be used to accumulate a whole set of changes to later be materialized into a copy with the changes? (or to be used directly, at whatever cost would be required) That's something I've been wondering why it's not more of an established thing. It would basically be docker, but for in-memory reference graphs instead of filesystems. | |||||||||||||||||||||||||||||||||||||||||||||||
|