class Monad m => MonadState s m | m -> s where
-- | Return the state from the internals of the monad.
get :: m s
get = state (\s -> (s, s))
-- | Replace the state inside the monad.
put :: s -> m ()
put s = state (\_ -> ((), s))
-- | Embed a simple state action into the monad.
state :: (s -> (a, s)) -> m a
state f = do
s <- get
let ~(a, s') = f s
put s'
return a
instance MonadState s m => MonadState s (MaybeT m) where...
Run Code Online (Sandbox Code Playgroud)
为什么MonadState的实例需要状态和monad,为什么不创建单个参数State类?
让我试着在评论中回答格特的问题,因为这是一个非常不同的问题.
问题是,为什么我们不能只写
class State s where
get :: s
put :: s -> ()
Run Code Online (Sandbox Code Playgroud)
好吧,我们可以写这个.但现在的问题是,我们可以用它做什么?而困难的部分是,如果我们有一些代码put x然后get,我们如何链接get到,put以便返回相同的值作为放入?
问题是,只有类型()和s,没有办法将一个链接到另一个.您可以尝试以各种方式实现它,但它不起作用.没有办法将数据传输put到get(也许有人可以更好地解释这一点,但最好的理解方法是尝试编写它).
Monad不一定是使操作可链接的唯一方法,但它是一种方式,因为它有>>操作符将两个语句链接在一起:
(>>) :: m a -> m b -> m b
Run Code Online (Sandbox Code Playgroud)
所以我们可以写
(put x) >> get
Run Code Online (Sandbox Code Playgroud)
foo :: StateT Int IO ()
foo = do
put 3
x <- get
lift $ print x
main = evalStateT foo 0
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
486 次 |
| 最近记录: |