本文介绍了有没有用于获取monad的变压器版本的库或类型类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 在我目前的项目中,我遇到了需要将各种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 这种方法不适用于没有定义为应用于 Identity ,就像 Maybe 和任一 monad。您被 hoistMaybe 和 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 astateT stf = StateT $ return . runState stfIt'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 likeclass (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 bMeaning 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 IdentityTherefore, we can define the following function (taken form the Generalizing base monads section of the mmorph documentation):import Data.Functor.Identitygeneralize :: (Monad m) => Identity a -> m ageneralize m = return (runIdentity m)and combine it with hoist:hoist generalize :: (Monad m, MFunctor t) => t Identity b -> t m bThis 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的变压器版本的库或类型类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 10-30 07:37