On the signature of >>= Monad operator

后端 未结 6 2321
粉色の甜心
粉色の甜心 2021-02-14 13:54

This is the signature of the well know >>= operator in Haskell

>>= :: Monad m => m a -> (a -> m b) -> m b

The question is why

6条回答
  •  难免孤独
    2021-02-14 14:29

    As others have said, your bind is the fmap function of the Functor class, a.k.a <$>.

    But why is it less powerful than >>=?

    it seems not difficult to write a general "adapter"

    adapt :: (Monad m) => (a -> b) -> (a -> m b)
    

    You can indeed write a function with this type:

    adapt f x = return (f x)
    

    However, this function is not able to do everything that we might want >>='s argument to do. There are useful values that adapt cannot produce.

    In the list monad, return x = [x], so adapt will always return a single-element list.

    In the Maybe monad, return x = Some x, so adapt will never return None.

    In the IO monad, once you retrieved the result of an operation, all you can do is compute a new value from it, you can't run a subsequent operation!

    etc. So in short, fmap is able to do fewer things than >>=. That doesn't mean it's useless -- it wouldn't have a name if it was :) But it is less powerful.

提交回复
热议问题