gpt4 book ai didi

Haskell Control.镜头移动棱镜

转载 作者:行者123 更新时间:2023-12-02 15:10:50 25 4
gpt4 key购买 nike

我有一个深层嵌套的数据结构,并且我正在使用 Control.Lens.* 来简化在状态单子(monad)中访问其值的过程。

因此请考虑以下因素:

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 吗?

最佳答案

您可能需要使用 Prism 进入 Just 分支。

>>> let config' = config & foo . _Just .~ (+1)
in config' ^. foo
Just 2

然后这个棱镜就会像其他镜头一样组合,形成遍历

foo . _Just . bar . _Bar :: Traversal' Config Int

看一下我写的关于镜头的一些教程,其中花了一些时间研究 LensPrism 之间的关系:

https://www.fpcomplete.com/user/tel/a-little-lens-starter-tutorial

https://www.fpcomplete.com/user/tel/lens-aeson-traversals-prisms

关于Haskell Control.镜头移动棱镜,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19555961/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com