Wondering how best to combine the Control.Lens package with IORefs. 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 inatomicModifyIORefand the(,) aFunctor, it needs some swapping around to work. I don't think the resulting operator is predefined, but I've given it the preliminary nameswappedIdbelow.Note that the
Lenstype is defined asIt turns out that if you let
fbe the(,) aFunctor, this almost perfectly fits the type you want to use to transform yourinc, except that you'd really have wanted theato be the last element of the tuple instead of the first. After fixing this up, here is what I ended up with: