>> 运算符是做什么的?

What >> operator does?

我正在 Haskell 学习 monad。

我阅读了 here 一篇关于 Monad 的精彩解释,并且我认为已经理解(不是全部,但我刚刚开始)关于 >>= 绑定运算符和 Monad。

我在老师的幻灯片上发现了这个:

class  Monad m  where
    (>>=)            :: m a -> (a -> m b) -> m b   -- "bind"
    (>>)             :: m a -> m b -> m b          -- "then"
    return           :: a -> m a  

什么是 >> 以及它与 >>= 的区别?

>> 是您不关心值时的快捷方式。也就是说,a >> b 等同于 a >>= \_ -> b(假设给定 monad 中 >> 的合理(或默认)定义)。

所以当你,比如说,在 IO monad 中并且想要执行一些 prints 时,你可以使用 >> 因为没有理由对 [=18= 做任何事情] print 产生:print a >> print b.

在do-notation方面exp >>= \var -> rest对应于

do
  var <- exp
  rest

exp >> rest对应的只是

do
  exp
  rest

>> 在左侧执行单子操作但丢弃其结果然后在右侧执行。

当你使用 do-notation 时,当你写类似

的东西时会发生这种情况
... = do _ <- action1
         action2

或更短(但编译器会发出未绑定的警告action1

... = do action1
         action2

现在它在哪里有用 - 考虑你

的单子解析器的情况
... = do string "IP:"
         d1 <- decimal
         char '.'
         d2 <- decimal
         char '.'
         d3 <- decimal
         char '.'
         d4 <- decimal
         char '.'
         return $ IP d1 d2 d3 d4

此处您对实际数字感兴趣,但对中间的点或开头的字符串 "IP:" 不感兴趣。

>> 运算符与 >>= 运算符相同,在函数不需要第一个单子运算符生成的值时使用。

为了更好地理解它,与 do 符号进行比较很有用:

The (>>) (then) operator works almost identically in do notation and in unsugared code. [here]

你可以看看这个例子:

putStr "Hello" >> 
putStr " " >> 
putStr "world!" >> 
putStr "\n"

相当于:

do putStr "Hello"
   putStr " "
   putStr "world!"
   putStr "\n"