haskellstate-monadlenseshaskell-lens

Searching for missing State Combinator for Lens


I currently have code that looks like this:

do
  x <- use foo
  foo <~ runFoo x

where foo is a Lens to a Foo field and runFoo :: MonadState m => Foo -> m Foo

I think there should be a way to do this operation in one line, but I cannot find it. I think it ought to have a comment like:

(????) :: MonadState s m => Lens' s a -> (a -> m a) -> m a

Questions:


Solution

  • lens doesn't offer such a combinator in a ready-made form. If instead of runFoo you had some g :: a -> a function, you would be able to use (%=), which is to over what use is to view, and write simply foo %= g. Your desired functionality, though, involves interleaving the m effects introduced by runFoo in between the getting and setting, which precludes a solution this straightforward.