[英]How does Haskell function `tell` work
I'm learning do expression
and Monad
using LEARN YOU A HASKELL FOR GREAT GOOD . 我正在学习
do expression
和Monad
使用LEARN你是一个很好的HASKELL 。 There's a gcd
implementation using tell
function makes me confused. 使用
tell
函数的gcd
实现让我很困惑。
gcd :: Int -> Int -> Writer [String] Int
gcd a b
| b == 0 = tell ["Finished with " ++ show a ] >>= (\_ -> return a)
| otherwise = tell [show a ++ " mod " ++ show b ++ " = " ++ show (a `mod` b)] >>= (\_ -> gcd b (a `mod` b))
gcdResult = gcd 8 3
-- result: WriterT (Identity (1,["8 mod 3 = 2","3 mod 2 = 1","2 mod 1 = 0","Finished with 1"]))
But I am confused by the tell
function. 但我对
tell
函数感到困惑。 When using >>= (\\_ -> ...)
or >>
, the result before will be ignored, so why does the result of tell
can be passed to the final result? 当使用
>>= (\\_ -> ...)
或>>
,之前的结果将被忽略,那么为什么tell
的结果可以传递给最终结果? As my thought, the tell
result may be ignored, and the final result will be WriterT (Identity (1,[]))
. 根据我的想法,可以忽略
tell
结果,最终结果将是WriterT (Identity (1,[]))
。
You're confusing the result with the context. 你将结果与上下文混淆了。 You are correct that, when applying
>>
or >>= \\_ ->
, the result of the left-hand-side is ignored. 你是正确的,当应用
>>
或>>= \\_ ->
,左侧的结果被忽略。 However, if the entire value was ignored, it would be completely pointless; 但是,如果忽略整个价值,那将是完全没有意义的; the monadic context can be passed forward.
monadic环境可以向前传递。
a >> b
This means "take the context from a
and combine it with the context of b
, keeping the result value of b
". 这意味着“从拿上下文
a
与上下文结合起来b
,保持的结果值b
”。 In the case of Writer
, the monadic context is that there is some write-only data being passed about. 在
Writer
的情况下,monadic上下文是传递一些只写数据。
tell :: Monoid w => w -> Writer w ()
This is the (somewhat simplified) type of tell
. 这是(略微简化)的
tell
类型。 It takes a value to write and returns a Writer
instance whose result value is insignificant ( ()
) but whose context is that there is a write-only value containing the w
argument. 它需要一个值来编写并返回一个结果值无关紧要的
Writer
实例( ()
),但其上下文是包含w
参数的只写值。 When you apply >>
, the result value is ignored (which is irrelevant because tell
returns nothing of value through its result) but the context is kept. 当你应用
>>
,结果值被忽略(这是无关紧要的,因为tell
通过其结果不返回任何值),但保留了上下文 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.