Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

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.



But 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.


I 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.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: