Wondering how best to combine the Control.Lens package with IORef
s. Specifically I'd like to be able to use atomicModifyIORef
with lenses so that i can supply a function of type a -> (a, b)
and return a value from the operation. Code snippet:
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
In principle, the lens operator needed is actually
%%~
, which is just a convenience synonym forid
. However, due to an annoying incompatibility in the tuple orderings used inatomicModifyIORef
and the(,) a
Functor
, it needs some swapping around to work. I don't think the resulting operator is predefined, but I've given it the preliminary nameswappedId
below.Note that the
Lens
type is defined asIt turns out that if you let
f
be the(,) a
Functor
, this almost perfectly fits the type you want to use to transform yourinc
, except that you'd really have wanted thea
to be the last element of the tuple instead of the first. After fixing this up, here is what I ended up with: