Reputation: 1195
I'm just trying to understand why this doesn't error:
Prelude> Nothing >>= (\x -> Just $ x + 3)
Nothing
If I break the lambda down into individual steps:
Prelude> Nothing + 3
<interactive>:8:1: error:
• Non type-variable argument in the constraint: Num (Maybe a)
(Use FlexibleContexts to permit this)
• When checking the inferred type
it :: forall a. Num (Maybe a) => Maybe a
and
Prelude> Just Nothing
Just Nothing
Upvotes: 3
Views: 371
Reputation: 80765
When you write Nothing >>= (\x -> Just $ x + 3)
, this is not at all the same as Just $ Nothing + 3
. You're not actually passing Nothing
as the value of x
.
Instead, you're calling operator >>=
, and you're passing into it two arguments: Nothing
on the left and the lambda expression on the right.
Therefore, the result of this expression would be determined by the definition of operator >>=
. Let's take a look at how it is defined for Maybe
:
(Just x) >>= f = f x
Nothing >>= f = Nothing
As you can see, when passed Nothing
as left argument, operator >>=
simply returns Nothing
right away, and doesn't even bother with the function that is passed as right argument.
Upvotes: 19