Search code examples
haskellhaskell-lens

Is it possible to set default values if `Nothing` is encountered somewhere in a deep Lens lookup/assignment?


Is it possible to set default values if Nothing is encountered somewhere in a deep Lens lookup/assignment?

E.g. for lookup:

(Just (4, 3), 2) ^. _1 . (maybe (6, 5)) . _1 == 4
(Nothing,     2) ^. _1 . (maybe (6, 5)) . _1 == 6

Or perhaps more importantly, for assignment:

((Just (4, 3), 2) & _1 . (maybe (6, 5)) . _1 .~ 7) == (Just (7, 3), 2)
((Nothing,     2) & _1 . (maybe (6, 5)) . _1 .~ 7) == (Just (7, 5), 2)

Solution

  • You can use non :: Eq a => a -> Iso' (Maybe a) a to create Iso between Eq a => Maybe a and Eq => a (see also).

    (Nothing, 2) ^. _1 . non (6, 5) . _1 == 6
    ((Nothing, 2) & _1 . non (6, 5) . _1 .~ 7) == (Just (7, 5), 2)