Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non-exhaustive pattern in Haskell list comprehension [duplicate]

Possible Duplicate:
Why don't Haskell list comprehensions cause an error when pattern match fails?

Today I saw the following code:

Prelude> [a | Just a <- [Just 10, Nothing, Just 20]]
[10, 20]

It works. But I thought that the above list comprehension is just syntactic sugar for...

[Just 10, Nothing, Just 20] >>= (\(Just x) -> return x)

...for which Haskell, when encountering the Nothing, would emit an error *** Exception: Non-exhaustive patterns in lambda.

So my question is: what does [a | Just a <- [Just 10, Nothing, Just 20]] translate into (in terms of monadic code) that makes it ignore the Nothing?

like image 809
Niccolo M. Avatar asked Nov 03 '22 19:11

Niccolo M.


1 Answers

I think the best answer in that other question is actually the one referencing 'compiler magic'. You're matching the pattern Just x, and according to the Haskell 2010 Report the behaviour is specified as

.. if a match fails then that element of the list is simply skipped over.

So I think implementations are free to do this as they please (i.e., the desugaring is not necessarily unique).

like image 191
jtobin Avatar answered Nov 15 '22 08:11

jtobin