如何构成 return 也许 (Haskell) 的镜头
How to compose lenses that return Maybe (Haskell)
假设我有一个像 at _
这样的镜头需要一些 Maybe a
:
import Data.Map as M
m = M.fromList [(1,(2,3))]
--set 2nd element
m ^. at 1 .~ Just (4,5)
--gives fromList [(1,(4,5))]
m ^. at 1 .~ Nothing
--gives fromList ()
现在假设我想用另一个镜头合成它。这个镜头returns有些Maybe a
让我无法直接做到
m ^. at 1 . _2 .~ Just 4
--error
-- I want to get M.fromList [(1,(2,4))]
正确的做法是什么?
使用 _Just
棱镜根据键是否存在在 Map 中设置值。这就是棱镜的用途!
λ> let m = fromList [(1, (2, 3))]
λ> m & at 1 . _Just . _2 .~ 4
fromList [(1,(2,4))]
λ> m & at 100 . _Just . _2 .~ 4
fromList [(1,(2,3))]
要设置一个值,您可以这样写:
> m & ix 1 . _2 .~ 4
fromList [(1,(2,4))]
要获取值,您可以执行类似的操作:
> m ^? ix 1 . _2
Just 3
假设我有一个像 at _
这样的镜头需要一些 Maybe a
:
import Data.Map as M
m = M.fromList [(1,(2,3))]
--set 2nd element
m ^. at 1 .~ Just (4,5)
--gives fromList [(1,(4,5))]
m ^. at 1 .~ Nothing
--gives fromList ()
现在假设我想用另一个镜头合成它。这个镜头returns有些Maybe a
让我无法直接做到
m ^. at 1 . _2 .~ Just 4
--error
-- I want to get M.fromList [(1,(2,4))]
正确的做法是什么?
使用 _Just
棱镜根据键是否存在在 Map 中设置值。这就是棱镜的用途!
λ> let m = fromList [(1, (2, 3))]
λ> m & at 1 . _Just . _2 .~ 4
fromList [(1,(2,4))]
λ> m & at 100 . _Just . _2 .~ 4
fromList [(1,(2,3))]
要设置一个值,您可以这样写:
> m & ix 1 . _2 .~ 4
fromList [(1,(2,4))]
要获取值,您可以执行类似的操作:
> m ^? ix 1 . _2
Just 3