作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
想知道如何最好地结合 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/
我是一名优秀的程序员,十分优秀!