【发布时间】:2019-12-13 21:28:57
【问题描述】:
我在“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 是否是有状态计算(即接受状态并返回具有更新状态的结果的函数)或者它是否是状态。我猜它一定是有状态的计算,因为它被应用于 lambda 函数中的状态(s 类型)以产生结果(a, newState)。
但是从State s a的类型声明来看:
newtype State s a = State { runState :: s -> (a,s) }
状态为s 类型,结果为a 类型。那么对于 monad 实例,instance Monad (State s) 中的 s 是状态的 type 还是实际上是有状态的计算?任何见解都值得赞赏。
【问题讨论】:
-
在一本面向新手的书中,使用
newtype {- StatePassingComputations -} State s a = MkState { runState :: s -> (a,s) }可能不会那么混乱。
标签: haskell functional-programming monads state-monad newtype