我有一个深度嵌套的数据结构,我正在使用 Control.Lens.* 来简化在状态单子中访问它的值。
所以考虑以下几点:
data Config = Config { _foo :: Maybe Int
, _bar :: Int
}
$(makeLenses ''Config)
我如何在 Maybe 上“功能性地”操作?我想写一个惯用的getter:
config = Config (Just 1) 0
config^.foo.to fmap (+1) == Just 2
更好的是,当 Config 嵌套更深时,我们将如何处理这种情况?
data Config = { _foo :: Maybe Foo }
data Foo = Foo { _bar :: Bar }
data Bar = Bar Int
$(makeLenses ''Bar)
$(makeLenses ''Foo)
我们可以使用访问器 foo 和 bar 来返回修改后的 Bar 吗?