gpt4 book ai didi

haskell - 为什么在 MonadState 中使用 MultiParamTypeClasses

转载 作者:行者123 更新时间:2023-12-03 14:27:35 26 4
gpt4 key购买 nike

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...

为什么 MonadState 的实例需要一个 state 和一个 monad,为什么不创建一个单参数的 State 类呢?

最佳答案

让我尝试在评论中回答 Gert 的问题,因为这是一个完全不同的问题。

问题是,为什么我们不能只写

class State s where
get :: s
put :: s -> ()

嗯,我们可以写这个。但现在的问题是,我们能用它做什么?困难的部分是,如果我们有一些带有 put x 的代码再后来 get ,我们如何链接 getput以便返回与放入的值相同的值?

问题是,只有类型 ()s ,没有办法将一个链接到另一个。您可以尝试以各种方式实现它,但它不起作用。只是没有办法携带来自 put 的数据。到 get (也许有人可以更好地解释这一点,但最好的理解方法是尝试编写它)。

Monad 不一定是使操作可链接的唯一方法,但它是一种方法,因为它具有 >>将两个语句链接在一起的运算符:
(>>) :: m a -> m b -> m b

所以我们可以写
(put x) >> get

编辑:这是一个使用 the StateT instance defined in the package 的示例
foo :: StateT Int IO ()
foo = do
put 3
x <- get
lift $ print x

main = evalStateT foo 0

关于haskell - 为什么在 MonadState 中使用 MultiParamTypeClasses,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12237831/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com