Let me have a go! I’d explain optics/lenses as giving field access as a data structure. That is, a lens is an object which describes how to access an element from a ‘larger’ value. For example, you can define _1 and _2 as lenses for accessing the first and second element respectively of a tuple:
_1 :: Lens' (a,b) a
_2 :: Lens' (a,b) b
(Using Haskell syntax here as that’s what I know best, though I’ve simplified the types slightly.)The great advantage of having these as first-class values is that you can now manipulate them. Of course, the main things you’ll want to do with these are get and set things:
> (1,2) ^. _1
1
> (1,2) & _1 .~ 3
(3,2)
More interestingly, you can also use a function to modify the value to which a lens is pointing: > (1,2) & _1 %~ negate
(-1,2)
Most usefully, you can also compose lenses. For instance, to get the second element of the first element of a nested tuple, you can compose _2 and _1 using dot notation: _1._2 :: Lens' ((a,b),c) b
Or, for a more realistic example, here’s a lens which accesses the ‘numSeen’ field of the value corresponding to key "keyToIncrement": (ix "keyToIncrement")._numSeen :: Lens' (Map String MyStructure) Int
(Well, strictly speaking, this is actually a traversal or a prism or something, because "keyToIncrement" might not exist, but let’s ignore that for this really simple example…)And now that you have it, you can use this new lens to do anything you want with this value: you can get it, set it, increment it, decrement it, print it, etc.
Additionally, you don’t have to restrict yourself to just lenses. For example, ‘traversals’ are a generalisation of lenses which allow you to access 0, 1 or more elements, rather than restricting access to just one element at a time. For instance, you can use ‘both’ to transform, well, both elements of a tuple:
> (1,2) & both 5~ negate
(-1,-2)
Or you can use ‘traversed’ to access each element of, say, a list: > [1,2,3,4,5] & traversed .~ 0
[0,0,0,0,0]
Of course, there are other ways of doing each of these. If you happen to be working with mutable values, you can sometimes use dot notation to access deeply nested fields. Some usecases of ‘traversed’ can be replaced by a map. However, there really is no comparable substitute for lenses when working with deeply nested immutable structures, especially ones of unknown shape.