如果在深镜头查找/分配中某处遇到Nothing
,是否可以设置默认值?
E.g。查找:
(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)
答案 0 :(得分:5)
您可以使用non :: Eq a => a -> Iso' (Maybe a) a
在Iso
和Eq a => Maybe a
(see also)之间创建Eq => a
。
(Nothing, 2) ^. _1 . non (6, 5) . _1 == 6
((Nothing, 2) & _1 . non (6, 5) . _1 .~ 7) == (Just (7, 5), 2)
答案 1 :(得分:0)
是的,似乎有可能:
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)
注意:我正在熟悉镜片,所以如果有人知道更好的方法,请告诉 - 例如如果有一个等同于df
的内置函数。