How does The Haskell Bind Operator extract the value from monad?

Viewed 110

Forgive me if the question sounds silly, I'm still a beginner learning Haskell.

Given the bind operator function signature:

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

My question is, how does the "a" value get extracted from "m a" so that the function (a -> m b) can fire? Does haskell abstract this internally?

1 Answers

This is implemented by the person who writes the Monad instance of a specific type.

For example if we look at the instance of Monad for Maybe, we see [src]:

-- | @since 2.01
instance  Monad Maybe  where
    (Just x) >>= k      = k x
    Nothing  >>= _      = Nothing

    (>>) = (*>)

whereas for an instance of the list [src], we see:

-- See Note: [List comprehensions and inlining]
-- | @since 2.01
instance Monad []  where
    {-# INLINE (>>=) #-}
    xs >>= f             = [y | x <- xs, y <- f x]
    {-# INLINE (>>) #-}
    (>>) = (*>)

If you thus make something an instance of the Monad typeclass, you will need to provide an implementation for the (>>=) function.

Related