In principle, the lens operator needed is actually %%~
, which is just a convenience synonym for id
. However, due to an annoying incompatibility in the tuple orderings used in atomicModifyIORef
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 name swappedId
below.
Note that the Lens
type is defined as
type Lens s t a b = forall f. Functor f => (a -> f b) -> s -> f t
It turns out that if you let f
be the (,) a
Functor
, this almost perfectly fits the type you want to use to transform your inc
, except that you'd really have wanted the a
to be the last element of the tuple instead of the first. After fixing this up, here is what I ended up with:
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