On the signature of >>= Monad operator

后端 未结 6 2320
粉色の甜心
粉色の甜心 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:31

    The whole 'point' of the monad really (that puts it above functor or applicative) is that you can determine the monad you 'return' based on the values/results of the left hand side.

    For example, >>= on a Maybe type allows us to decide to return Just x or Nothing. You'll note that using functors or applicative, it is impossible to "choose" to return Just x or Nothing based on the "sequenced" Maybe.

    Try implementing something like:

    halve :: Int -> Maybe Int
    halve n | even n    = Just (n `div` 2)
            | otherwise = Nothing
    
    return 24 >>= halve >>= halve >>= halve
    

    with only <$> (fmap1) or <*> (ap).

    Actually the "straightforward integration of pure code" that you mention is a significant aspect of the functor design pattern, and is very useful. However, it is in many ways unrelated to the motivation behind >>= --- they are meant for different applications and things.

提交回复
热议问题