"<-" and associated values

haskell, monads

Solution

Let's try and desugar the do-notation of that last example.

func'' = Nothing >>= (\a -> Just 5 >>= (\b -> return $ a+b))

Now, let's see how >>= is defined for Maybe. It's in the Prelude:

instance  Monad Maybe  where
    (Just x) >>= k   =  k x
    Nothing  >>= k   =  Nothing
    return           =  Just
    fail s           =  Nothing

So `Nothing >>= foo` is simply `Nothing`

Problem

Say I've written the following amazin piece of code: ``` func = do a <- Just 5 return a ``` It's pretty pointless, I know. Here, `a` is `5`, and `func` returns `Just 5`. Now I rewrite my awesome (yet pointless) function: ``` func' = do a <- Nothing return a ``` This function returns `Nothing`, but what the heck is `a`? There's nothing to extract from a `Nothing` value, yet the program doesn't whine when I do something like this: ``` func'' = do a <- Nothing b <- Just 5 return $ a+b ``` I just have a hard time seeing what actually happens. What is `a`? In other words: What does `<-` actually do? Saying it "extracts the value from right-side and binds it to the left-side" is obviously over-simplifying it. What is it I'm not getting? Thanks :)

Original source