Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Haskell know to retain Nothing as nothing when passed to a lambda that returns Just x?

Tags:

haskell

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
like image 933
paperduck Avatar asked Nov 30 '22 21:11

paperduck


1 Answers

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.

like image 127
Fyodor Soikin Avatar answered Dec 05 '22 05:12

Fyodor Soikin