Search code examples
haskellhaskell-lenslenses

Traversal/lens with a monad side effect


I have a traversal mytraversal and a function f: a -> a that I can use as follows: mydata & mytraversal %~ f.

However, what do I use if I instead have f: a -> m a for a monad m? In my case, it's a state monad, and I want to modify items of a structure, modifying the current state.


Solution

  • type Traversal s t a b = forall f. Applicative f => (a -> f b) -> s -> f t
    

    So, really, just

    mydata & mytraversal f
    

    should do. If you want an operator, it's called (%%~).

    mydata & mytraversal %%~ f