3 ms·
Practically speaking, optics are useful for avoiding long chains of nested field access, like myBody.LeftArm.Hand.RingFinger. This is particularly useful for p
by munchler 1y ago
Practically speaking, optics are useful for avoiding long chains of nested field access, like myBody.LeftArm.Hand.RingFinger.
This is particularly useful for providing copy-on-write semantics for immutable data structures. E.g. Putting a ring on a finger creates a new finger, which creates a new hand, which creates a new arm, which creates a new body. Using an appropriate lens, such updates become much simpler to write.
- kqr 1y agoBut also things like myBody.BothArms.Hand.RingFinger which targets the ring fingers on both hands at the same time, or myBody.LeftArm.Hand.RingFinger.WeddingBand which targets a ring that might not exist, or myBody.LeftArm.Hand.RingFinger.Straight which targets the ring finger when it is stretched out straight. People often think of optics as only "OOP accessors but for FP" but they are strictly more powerful than OOP accessors.
- titanomachy 1y agoI agree that "concisely updating immutable data structures" is the easiest way to show how this is useful. let x = (set `bar.quux` new_quux) y instead of let x = { foo: y.foo, bar: {baz: y.bar.baz, quux: new_quux} } If the language allows, both expressions could be fully type-checked at compile time.