没有MonadState的实例

时间:2014-03-28 20:01:51

标签: haskell

我得到“MonadState BTState BT没有实例”,我不知道我做错了什么。我尝试在各个地方添加约束,将MonadState放在deriving()子句中等等。

{-# LANGUAGE GeneralizedNewtypeDeriving #-}

import System.Random
import Control.Monad.Error
import Control.Monad.State

-- I want to make a class of monads which contain random generator state.
class Monad m => RandMonad m where
  putGen :: StdGen -> m ()
  getGen :: m StdGen

-- the following creates a monadic type BT
data BTState = BTState
 { bGoalN :: Int
 , bRandState :: StdGen }

newtype BT a = BT { insideBT :: ErrorT String (State BTState) a }
    deriving(Monad)

runBT a s = runState (runErrorT $ insideBT a) s

instance RandMonad BT where
  getGen = BT $ gets bRandState
  putGen g = BT $ do { s <- get; put s {bRandState=g} }

-- trying to use BT
backtrackBT :: BT Int
backtrackBT = do
  s <- get
  put s {bGoalN=2}
  return 3

1 个答案:

答案 0 :(得分:2)

您需要派生MonadState

newtype BT a = ...
    deriving (Monad, MonadState BTState, MonadError String)

MonadError我们正在进行此活动。


如果您曾尝试过放置deriving (Monad, MonadState, MonadError),那么您将遇到编译器错误,因为您必须与变换器堆栈具有关联的状态或错误类型,否则您将能够更改类型错误或计算中途的状态类型,这在其他地方都不会发生变形。