Haskell Lens: Prism over maybes

Viewed 146

I have those lenses:

getB :: Lens' A (Maybe B) 

getC :: Prism' B C

How can I extract a Maybe C from an A? The best I could find:

case A ^. getB of
    Just b -> b ^? getC
    Nothing -> Nothing

Anything more elegant?

2 Answers
_Just :: Prism' (Maybe a) a

The _Just prism will get you the value out of a Maybe.

a ^? getB . _Just . getC

Or you can use Maybe's Traversable instance, which gets the value inside the Just if there is one.

-- traverse :: Traversal' (Maybe a) a
a ^? getB . traverse . getC
Related