Why use such a peculiar function type in monads?

后端 未结 5 1163
温柔的废话
温柔的废话 2020-12-06 16:32

New to Haskell, and am trying to figure out this Monad thing. The monadic bind operator -- >>= -- has a very peculiar type signature:

(>         


        
5条回答
  •  一生所求
    2020-12-06 16:53

    It's much more symmetric if you think in terms the following derived function (from Control.Monad):

    (>=>) :: Monad m => (a -> m b) -> (b -> m c) -> (a -> m c)
    (f >=> g) x = f x >>= g
    

    The reason this function is significant is that it obeys three useful equations:

    -- Associativity
    (f >=> g) >=> h = f >=> (g >=> h)
    
    -- Left identity
    return >=> f = f
    
    -- Right identity
    f >=> return = f
    

    These are category laws and if you translate them to use (>>=) instead of (>=>), you get the three monad laws:

    (m >>= g) >>= h = m >>= \x -> (g x >>= h)
    
    return x >>= f = f x
    
    m >>= return = m
    

    So it's really not (>>=) that is the elegant operator but rather (>=>) is the symmetric operator you are looking for. However, the reason we usually think in terms of (>>=) is because that is what do notation desugars to.

提交回复
热议问题