4

I'm learning about monad in Haskell.

I read here an excelent explaination about Monads, and I think to have understand (not all, but ehy I just started) about >>= bind operator and Monad.

On my teacher's slides I found this:

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

What is >> and in what it differs from >>=?

Community
  • 1
  • 1
granmirupa
  • 2,780
  • 16
  • 27

3 Answers3

14

>> is a shortcut for when you don't care about the value. That is, a >> b is equivalent to a >>= \_ -> b (assuming a sane (or default) definition of >> in the given monad).

So when you're, say, in the IO monad and want to execute some prints, you can use >> because there's no reason to do anything with the () that print produces: print a >> print b.

In terms of do-notation exp >>= \var -> rest corresponds to

do
  var <- exp
  rest

and exp >> rest corresponds to just

do
  exp
  rest
RAbraham
  • 5,956
  • 8
  • 45
  • 80
sepp2k
  • 363,768
  • 54
  • 674
  • 675
6

>> performs the monadic action on the left hand side but discards its result and then performs the right hand side.

when you are using do - notation this is what happens when you write something like

... = do _ <- action1
         action2

or shorter (but the compiler will issue a warning of unbound action1)

... = do action1
         action2

now where is that useful - consider the situation of a monadic parser where you

... = do string "IP:"
         d1 <- decimal
         char '.'
         d2 <- decimal
         char '.'
         d3 <- decimal
         char '.'
         d4 <- decimal
         char '.'
         return $ IP d1 d2 d3 d4

here you are interested in the actual numbers but not in the dots in between or the string "IP:" at the beginning.

epsilonhalbe
  • 15,637
  • 5
  • 46
  • 74
1

The >> operator works as the >>= operator and is used when the function does not need the value produced by the first monadic operator.

To better understand it a comparation with do notation is useful:

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

You can look better at this example:

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

that is equivalent to:

do putStr "Hello"
   putStr " "
   putStr "world!"
   putStr "\n"
f.saint
  • 33
  • 2
  • 6