gpt4 book ai didi

haskell - 理解 Writer Monad 的示例

转载 作者:行者123 更新时间:2023-12-02 17:14:54 25 4
gpt4 key购买 nike

我正在通过《Learn You A Haskell》一书了解 Writer Monad。

这是一段代码:

import Control.Monad.Writer

logNumber :: Int -> Writer [String] Int
logNumber num = writer (num, ["Got number: " ++ show num])

multWithLog :: Writer [String] Int
multWithLog = do
a <- logNumber 3
b <- logNumber 5
return (a * b)

运行multWithLog时,结果如下:

*Main> runWriter multWithLog
(15,["Got number: 3","Got number: 5"])

在这一行:

a <- logNumber 3
b <- logNumber 5

很容易看出a = 3b = 5,因为它们都在return函数上相乘。

我不明白的是为什么这些值为 35ab 不应该是 Writer Monad 中包含的值吗?在这种情况下元组?

例如,对于Maybe Monad,ab将是35:

do
a <- Just 3
b <- Just 5
return (a * b)

在这种情况下,这对我来说是有意义的,因为 ab 接收 Just 内的内容。但在最初的示例中,ab 仅接收部分值。

最佳答案

It is easy to see that a = 3 and b = 5, since both of them are being multiplied on the return function. What I don't understand is why those values are 3 and 5. Shouldn't a and b be the values that contain inside the Writer Monad? In this case tuples?

没有。我认为回答这个问题的最简单方法就是实现 Writer输入并研究其 Monad类实例:

newtype Writer w a = Writer { runWriter :: (a, w) }

instance Functor (Writer w) where
fmap f (Writer (a, w)) = Writer (f a, w)

instance Monoid w => Applicative (Writer w) where
pure a = Writer (a, mempty)
Writer (f, w) <*> Writer (a, w') = Writer (f a, w <> w')

instance Monoid w => Monad (Writer w) where
return = pure
Writer (a, w) >>= f = let (b, w') = runWriter (f a)
in Writer (b, w <> w')

tell :: w -> Writer w ()
tell w = Writer ((), w)

正如您在 >>= 的实例方法中看到的那样,函数f应用于a值,而不是整个元组。语法a <- logNumber 3使用 >>= 脱糖,因此绑定(bind)到 a 的值将是 Writer 的元组的第一个元素环绕。

关于haskell - 理解 Writer Monad 的示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33881822/

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