本文介绍了如何修改使用带镜头的monadic功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个镜头功能,其功能类似于而不是,但使用一次性操作:

  overM ::(Monad m)=>镜头s a b  - > (a  - > m b) - > (s  - > mt)

虽然这个函数很容易定义(它实际上只是一个标识模 WrappedMonad ),我想知道在镜头的某个地方定义了这样的函数吗?

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

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

overM ::(Monad m)=>镜头s a b - > (a - > m b) - > (s - > m t)
overM l =(unwrapMonad。)。 l。 (WrapMonad。)


解决方案

在Control.Lens.Traversal中:

  traverseOf :: Over pfstab  - > 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例子:

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

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


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 .)
解决方案

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)

这篇关于如何修改使用带镜头的monadic功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 11:44