gpt4 book ai didi

haskell - 如何将 IORef 与镜头配合使用?

转载 作者:行者123 更新时间:2023-12-02 21:08:26 25 4
gpt4 key购买 nike

想知道如何最好地结合 Control.Lens与 IORef 一起封装。具体来说,我希望能够将 atomicModifyIORef 与镜头一起使用,以便我可以提供 a -> (a, b) 类型的函数并从手术。代码片段:

let inc x = (x+1, x)
ior <- newIORef ((1, 1) :: (Int, Int))
thisShouldBe1 <- ior & atomicModifyIORef ?? _1 inc -- this is the bit I'm stuck on

最佳答案

原则上,所需的镜头算子实际上是%%~,它只是id的方便同义词。但是,由于 atomicModifyIORef(,) a Functor 中使用的元组顺序存在令人烦恼的不兼容性,因此需要进行一些交换才能工作。我认为生成的运算符不是预定义的,但我在下面为其指定了初步名称 swappedId

请注意,Lens 类型定义为

type Lens s t a b = forall f. Functor f => (a -> f b) -> s -> f t

事实证明,如果您让 f(,) a Functor,这几乎完全适合您要使用的类型来转换您的 inc ,只不过您确实希望 a 成为元组的最后一个元素而不是第一个元素。解决这个问题后,我得到了以下结果:

import Data.IORef
import Control.Lens

l `swappedId` f = f & mapping swapped %~ l

main = do
let inc x = (x+1, x)
ior <- newIORef ((1, 1) :: (Int, Int))
thisShouldBe1 <- atomicModifyIORef ior $ _1 `swappedId` inc
print thisShouldBe1
print =<< readIORef ior

关于haskell - 如何将 IORef 与镜头配合使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25423793/

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