Why use such a peculiar function type in monads?

后端 未结 5 1175
温柔的废话
温柔的废话 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:59

    The problem with the alternative type signature for (>>=) is that it only accidently works for the Maybe monad, if you try it out with another monad (i.e. List monad) you'll see it breaks down at the type of b for the general case. The signature you provided doesn't describe a monadic bind and the monad laws can't don't hold with that definition.

    import Prelude hiding (Monad, return)
    
    -- assume monad was defined like this
    class Monad m where
      (>>=)  :: m a -> (a -> b) -> m b
      return :: a -> m a
    
    instance Monad Maybe where
      Nothing  >>= f = Nothing
      (Just x) >>= f = return $ f x
    
    instance Monad [] where
      m >>= f   =  concat (map f m)
      return x  =  [x]
    

    Fails with the type error:

        Couldn't match type `b' with `[b]'
          `b' is a rigid type variable bound by
              the type signature for >>= :: [a] -> (a -> b) -> [b]
              at monadfail.hs:12:3
        Expected type: a -> [b]
          Actual type: a -> b
        In the first argument of `map', namely `f'
        In the first argument of `concat', namely `(map f m)'
        In the expression: concat (map f m)
    

提交回复
热议问题