【发布时间】:2016-04-15 16:28:14
【问题描述】:
在教程Learn You a Haskell - chapter 'for-a-few-monads-more', section 'The State monad' 中,它列出了以下定义State Monad:
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为当前状态,Statenewtype 包裹的函数返回结果和新状态。 -
但是“当前状态”从何而来?它是否来自定义的第一行:
instance Monad (State s)?暗示输入是's'?需要使用定义本身的冷酷答案。 -
不,还有一个
runState函数,它采用初始状态和计算来运行,例如runState (return 1) "state" => (1, "state") -
当前状态必须从外部提供。
State s a类型的值可以被视为一台机器需要当前状态s,并在返回a类型的值的同时对其进行修改。
标签: haskell functional-programming monads