有没有用于获取monad的变压器版本的库或类型类? [英] Is there a library or typeclass for getting the transformer version of a monad?
问题描述
在我目前的项目中,我遇到了需要将各种monad转换为它们的变形对象,例如
stateT :: Monad m =>国家a - > StateT s $ a
stateT stf = StateT $ return。 runState stf
为我需要的monads编写这些实用函数是很简单的,但是我想知道是否有已经存在一个库,它包含标准monad的这个功能,或者是一个抽象这种转换的类型类。类似于
class(Monad f,MonadTrans t)=> LiftTrans f t | f - > t其中
liftT :: Monad m => f a - > tma
(lift可能是这里使用的错误术语,但我不确定是什么)
检出函数 hoist
mmorph 包。
其签名是
hoist :: Monad m => (全部a - > a a) - > t m b - > t b
这意味着它可以改变变压器底层的monad。
现在,在 trasformers
包中,许多基本monad实现为应用于 Identity
monad,像这样:
type State s = StateT s Identity
因此,我们可以定义以下函数(采用将 mmorph <
$ b
import Data.Functor.Identity
generalize ::((code> documentation): Monad m)=>身份a - > ma
generalize m = return(runIdentity m)
并结合提升: p>
hoist generalize ::(Monad m,MFunctor t)=> t身份b - > tmb
这种方法不适用于没有定义为应用于<$ c的转换器的简单monad $ c> Identity ,就像 Maybe
和任一
monad。您被 hoistMaybe < a>和 hoistEither 为这些。
In my current project I've run into the need to turn various monads into their transformer counterparts e.g.
stateT :: Monad m => State s a -> StateT s m a
stateT stf = StateT $ return . runState stf
It's trivial to write these utility functions for the monads I need, but I was wondering if there already exists a library that contains this functionality for the standard monads and maybe a typeclass that abstracts this sort of transformation. Something like
class (Monad f, MonadTrans t) => LiftTrans f t | f -> t where
liftT :: Monad m => f a -> t m a
("lift" is probably the wrong term to use here, but I wasn't sure what else to call it.)
Check out function hoist
from the mmorph package.
Its signature is
hoist :: Monad m => (forall a. m a -> n a) -> t m b -> t n b
Meaning that it can change the base monad underlying a transformer.
Now, in the trasformers
package, many "basic" monads are implemented as transformers applied to the Identity
monad, like this:
type State s = StateT s Identity
Therefore, we can define the following function (taken form the Generalizing base monads section of the mmorph
documentation):
import Data.Functor.Identity
generalize :: (Monad m) => Identity a -> m a
generalize m = return (runIdentity m)
and combine it with hoist:
hoist generalize :: (Monad m, MFunctor t) => t Identity b -> t m b
This method won't work for simple monads which are not defined as transformers applied to Identity
, like the Maybe
and Either
monads. You are stuck with hoistMaybe and hoistEither for these.
这篇关于有没有用于获取monad的变压器版本的库或类型类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!