Shorthand for lens chaining with _Just

69 Views Asked by At

I have a data object which I access as follows.

foo ^? lens1 . _Just . lens2 . _Just . lens3 . _Just

Is there some builtin lens operator that allows this to be shorthanded like bellow?

foo ^? lens1 © lens2 © lens3
1

There are 1 best solutions below

0
Li-yao Xia On

It's probably not in lens but you can easily define your own operator to insert _Just in between two optics:

infixl 9 .?.
(.?.) :: Traversal' s (Maybe t) -> Traversal' t u -> Traversal' s u
s .?. t = s . _Just . t

where Traversal' is the smallest common supertype of Lens' and Prism' expressible in lens (there is a more precise variant with profunctor lenses). Or here is a more general signature:

(.?.) :: (Choice p, Applicative f) => Optic' p f s (Maybe t) -> Optic' p f t u -> Optic' p f s u

Note that (.?.) only inserts _Just in the middle; you still have to append it at the end:

foo ^? lens1 .?. lens2 .?. lens3 . _Just