StateT newtype:从mtl切换到变换器

Gre*_*ber 0 haskell monad-transformers

使用mtl,派生MonadState似乎可以使状态操作正常解除:


:set -XGeneralizedNewtypeDeriving
import Control.Applicative (Applicative)
import Control.Monad.Trans ( MonadIO, liftIO )
import Control.Monad.State (MonadState, evalStateT, modify, StateT, gets)

data State = State { int:: Int }
newtype St a = St { unSt :: StateT State IO a } deriving (Functor, Applicative, Monad, MonadIO, MonadState State)

let testLift = gets int >> return () :: St ()
Run Code Online (Sandbox Code Playgroud)

对于变形金刚,没有MonadState


:set -XGeneralizedNewtypeDeriving
import Control.Monad.Trans.State.Strict (runStateT, evalStateT, modify, StateT, gets)
import Control.Monad.IO.Class ( MonadIO, liftIO )
import Control.Applicative (Applicative)


data State = State { int:: Int }
newtype St a = St { unSt :: StateT State IO a } deriving (Functor, Applicative, Monad, MonadIO)


let testLift = gets int >> return () :: St ()
Run Code Online (Sandbox Code Playgroud)
Couldn't match type `StateT State m0' with `St'
Expected type: St Int
  Actual type: StateT State m0 Int
In the return type of a call of `gets'
In the first argument of `(>>)', namely `gets int'
In the expression: gets int >> return () :: St ()
Run Code Online (Sandbox Code Playgroud)

我应该做些什么才能让变形金刚工作?

sha*_*haf 6

你应该用来mtl做这项工作.mtltransformers不是真正的竞争对手- mtl 取决于变压器!它的存在是为了添加类似于MonadState使用函数依赖的类,因此它们不必是核心(Haskell-98)类型定义的一部分.还有一个monads-tf使用类型系列的package(),它也兼容transformers(但实际上,你不应该使用它).

也许我应该问:你为什么"从mtl转换为变形金刚"?