假设我有一个像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 ()
现在假设我想用另一个镜头合成它。该镜头返回一些
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))]