简体   繁体   English

Haskell如何运行`tell`工作

[英]How does Haskell function `tell` work

I'm learning do expression and Monad using LEARN YOU A HASKELL FOR GREAT GOOD . 我正在学习do expressionMonad使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM