Haskell Monad 状态:获取和修改
Haskell Monad State: gets and modify
我对 monad 状态下 gets 和 modify 的定义感到困惑。
Somewhere 说:
得到:"Gets specific component of the state, using a projection function supplied"。
修改:将旧状态映射到状态 monad 内的新状态。旧状态被丢弃。
这意味着我们可以使用修改直接为状态的组件赋值,如here。
但是 somewhere else 说我们可以使用 modify 和 gets 提供一个函数来声明和结果。
似乎两者都有效,但我不清楚哪个有效!
你从未引用过第二个引文,所以我会在这个答案中忽略它。如果您澄清了问题的那一部分,那么我会尽力回答。
您引用的来源之一说:
gets :: MonadState s m => (s -> a) -> m a Source #
Gets specific component of the state, using a projection function supplied.
和
modify :: MonadState s m => (s -> s) -> m () Source #
Monadic state transformer.
Maps an old state to a new state inside a state monad.
因此,对于 gets
,您可以提供一个函数 s -> a
,它将 return 应用到当前状态后 a
。对于 modify
,您提供一个函数 s -> s
,新状态是您的函数应用于旧状态的结果。
我对 monad 状态下 gets 和 modify 的定义感到困惑。
Somewhere 说:
得到:"Gets specific component of the state, using a projection function supplied"。
修改:将旧状态映射到状态 monad 内的新状态。旧状态被丢弃。
这意味着我们可以使用修改直接为状态的组件赋值,如here。
但是 somewhere else 说我们可以使用 modify 和 gets 提供一个函数来声明和结果。
似乎两者都有效,但我不清楚哪个有效!
你从未引用过第二个引文,所以我会在这个答案中忽略它。如果您澄清了问题的那一部分,那么我会尽力回答。
您引用的来源之一说:
gets :: MonadState s m => (s -> a) -> m a Source #
Gets specific component of the state, using a projection function supplied.
和
modify :: MonadState s m => (s -> s) -> m () Source #
Monadic state transformer.
Maps an old state to a new state inside a state monad.
因此,对于 gets
,您可以提供一个函数 s -> a
,它将 return 应用到当前状态后 a
。对于 modify
,您提供一个函数 s -> s
,新状态是您的函数应用于旧状态的结果。