Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to modify using a monadic function with lenses?

I needed a lens function that works like over, but with monadic operations:

overM :: (Monad m) => Lens s t a b -> (a -> m b) -> (s -> m t)

While this function is easy to define (it's actually just an identity modulo WrappedMonad), I wonder are such functions defined somewhere in lens?

{-# LANGUAGE RankNTypes #-}
import Control.Applicative
import Control.Lens

overF :: (Functor f) => Lens s t a b -> (a -> f b) -> (s -> f t)
overF l = l

overM :: (Monad m) => Lens s t a b -> (a -> m b) -> (s -> m t)
overM l = (unwrapMonad .) . l . (WrapMonad .)
like image 591
Petr Avatar asked Mar 05 '14 21:03

Petr


1 Answers

in Control.Lens.Traversal:

traverseOf :: Over p f s t a b -> p a (f b) -> s -> f t
traverseOf = id

mapMOf :: Profunctor p =>
     Over p (WrappedMonad m) s t a b -> p a (m b) -> s -> m t
mapMOf l cmd = unwrapMonad #. l (WrapMonad #. cmd)

Example:

Prelude Control.Lens> traverseOf _1 (Just . (+2)) (2,2)
Just (4,2)

Prelude Control.Lens> mapMOf _1 (Just . (+2)) (2,2)
Just (4,2)
like image 172
Charles Durham Avatar answered Oct 24 '22 09:10

Charles Durham