如何组成返回Maybe(Haskell)的镜头

时间:2016-01-13 05:04:40

标签: haskell lens lenses

假设我有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))]

正确的方法是什么?

2 个答案:

答案 0 :(得分:13)

使用_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))]

答案 1 :(得分:2)

要设置一个值,您可以写:

> m & ix 1 . _2 .~ 4
fromList [(1,(2,4))]

要获得值,您可以执行类似的操作:

> m ^? ix 1 . _2
Just 3