▲ | kqr 2 days ago | |
Aside from making it convenient to build getters and setters for nested data, optics also have conditional accessors and collection accessors as building blocks. Conditional accessors have since become a popular language feature with e.g. the elvis operator ?. in C#. Optics make it possible to innovate on features like that in library code rather than as language features. Something I've yet to see made into a language feature that is common in optics libraries are iterating accessors. E.g. to reset all counters we can, with optics, say something like (in Haskell syntax, since that is what I know)
and that sets the count to zero for all objects in the stats array. If not all stats objects have a count (some might be of a gauge type, for example) we can compose in a conditional accessor that resolves the count field only if it is not null:
In the above statement, nothing is language syntax --it's all library functions and operators. But it still combines really well on the page. Once one knows optics, one rarely has to think very hard about how to do any get or update operation, even when the data types become complicated. |