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
?
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With