如果在 deep Lens lookup/assignment 中某处遇到 `Nothing` 是否可以设置默认值?

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

如果在deep Lens某处遇到Nothing是否可以设置默认值lookup/assignment?

例如查找:

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

或者更重要的是,对于作业:

((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)

是的,好像可以:

let
  df :: Functor f => a -> (a -> f b) -> Maybe a -> f (Maybe b)
  df d = lens (maybe d id) (const Just)

(Just (4, 3), 2) ^. _1 . df (6, 5) . _1 `shouldBe` 4
(Nothing,     2) ^. _1 . df (6, 5) . _1 `shouldBe` 6

((Nothing,     2) & _1 . df (6, 5) . _1 .~ 7) `shouldBe` (Just (7, 5), 2)
((Just (4, 3), 2) & _1 . df (6, 5) . _1 .~ 7) `shouldBe` (Just (7, 3), 2)

注意:我正在熟悉 Lenses,所以如果有人知道更好的方法,请告诉我——例如如果存在等效于 df.

的内置函数

您可以使用 non :: Eq a => a -> Iso' (Maybe a) aEq a => Maybe aEq => a 之间创建 Iso (see also)

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