【发布时间】:2019-12-16 10:31:06
【问题描述】:
我正在编写一个haskell 程序来执行一堆语句来修改数据记录。我想在没有用户干预的情况下对每个语句的状态进行修改和测试。我想修改Control.Monad.Trans.State.Strict 模块以将我的特定类型合并到一个元组(,) 中。
在出现以下错误之前它运行良好
• Couldn't match type ‘a’ with ‘b’
‘a’ is a rigid type variable bound by
the type signature for:
(>>=) :: forall a b.
StateT s m a -> (a -> StateT s m b) -> StateT s m b
at TestMon.hs:38:7
‘b’ is a rigid type variable bound by
the type signature for:
(>>=) :: forall a b.
StateT s m a -> (a -> StateT s m b) -> StateT s m b
at TestMon.hs:38:7
Expected type: m (b, s, LogS)
Actual type: m (a, s, LogS)
我不明白为什么会出现此错误。 我的代码是这样的:
module TestStateJLJ1 where
import Data.Functor.Identity
import Control.Applicative
import Control.Monad
data LogS = LogOK { stepS:: Int ,logS::[String] }
| LogErr {stepS:: Int , logS::[String] }
deriving (Show)
initLogS = LogOK { stepS=1, logS=[]}
type State s = StateT s Identity
state :: (Monad m) => ((s,LogS) -> (a, s,LogS)) -> StateT s m a
state f = StateT (return . f )
newtype StateT s m a = StateT { runStateT :: (s,LogS) -> m (a,s,LogS) }
instance (Functor m) => Functor (StateT s m) where
fmap f m = StateT $ \ (s,l) ->
fmap (\ (a, s',l') -> (f a, s',l')) $ runStateT m (s,l)
instance (Functor m, Monad m) => Applicative (StateT s m) where
pure a = StateT $ \ (s,l) -> return (a, s,l)
StateT mf <*> StateT mx = StateT $ \ (s,l) -> do
(f, s',l') <- mf (s,l)
(x, s'',l'') <- mx (s',l')
return (f x, s'',l'')
m *> k = m >>= \_ -> k
instance (Monad m) => Monad (StateT s m) where
return a = StateT $ \ (s,l) -> return (a, s,l)
m >>= k = StateT $ \ (s,l) -> do
(a, s',l') <- runStateT m (s,l)
case l' of
LogOK _ _ -> runStateT (k a) (s',l'{stepS=1+stepS l'})
LogErr _ _-> do return ( a, s',l') -- <- This line is causing trouble
fail str = StateT $ \ _ -> fail str
我尝试修改Monad 实例的行为以测试LogS 数据类型的值并根据其值:
执行
stepS的增量(计算语句的数量)和许多其他事情(尚未实现)并继续执行 monad。或者停止monad执行,返回实际状态。
您知道我的代码有什么问题以及如何更正吗?
【问题讨论】:
-
你不能返回
a,因为它应该是StateT s m b,而不是StateT s m a。 -
我已经理解了这个错误,但我真的不知道如何纠正它?有什么想法吗?
标签: haskell monads functor monad-transformers applicative