2014-03-28 51 views
0

我得到「MonadState BTState BT沒有實例」,我不知道我在做什麼錯誤。我試過在不同的地方添加約束,把MonadState推導()子句中,等沒有用於MonadState的實例

{-# 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 

回答

2

您需要派生MonadState

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

而且MonadError,而我們在這。


如果你曾試圖只是把deriving (Monad, MonadState, MonadError),你會得到一個編譯器錯誤,因爲你必須與你的變壓器堆棧相關的狀態或錯誤類型,否則你能夠改變的類型錯誤或計算中途的狀態類型,這不會在其他地方進行類型檢查。

相關問題