在教程Learn You a Haskell - chapter 'for-a-few-monads-more', section 'The State monad',它列出了以下定义国家单子:Haskell State Monad - 对lamba s - > ...的输入是什么?
newtype State s a = State { runState :: s -> (a,s) }
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
只需要回答一个简单的问题:你会在输入\ S是(因为状态H =一个函数,一个状态并输出一个元组(result,newState);暗示\ s的输入只是该函数)?欢迎举例
's'是当前状态,'State' newtype包装的函数返回结果和新状态。 – Lee
但是'现状'来自哪里呢?它来自定义的第一行:'Monad(State s)'实例吗?暗示输入是's'?需要使用定义本身的冷酷答案。 – SoyTeins
不,还有一个'runState'函数,它使初始状态和计算运行,例如'runState(return 1)“state”=>(1,“state”)' – Lee