我正在学习Miran Lipovaca所著的书籍“Learn You a Haskell for Great Good!”中关于State monad的内容。针对以下的monad实例:
instance Monad (State s) where
return x = State $ \s -> (x,s)
(State h) >>= f = State $ \s -> let (a, newState) = h s
(State g) = f a
in g newState
我对
>>=
函数的定义存在困惑,我不确定h
是有状态计算(即接收状态并返回带有更新状态的结果的函数)还是一个状态。我猜测它必须是一个有状态的计算,因为它应用于状态(类型为s
)的lambda函数中,以产生结果(a, newState)
。但是从
State s a
的类型声明来看:newtype State s a = State { runState :: s -> (a,s) }
状态的类型为
s
,结果的类型为a
。所以对于monad实例,instance Monad (State s)
中的s
是状态的类型,还是实际的有状态计算?任何见解都将不胜感激。
newtype {- StatePassingComputations -} State s a = MkState { runState :: s -> (a,s) }
可能会在面向新手的书籍中更加清晰易懂。 - Will Ness