evan_tech

Previous Entry Add to Memories Share Next Entry
Here's a Haskell trick that I use infrequently but is still nice.

Sometimes you want to filter a list on something that can be pattern-matched on. For example, say you want to grab all the Justs out of a list of Maybes. (That's Data.Maybe.catMaybes, by the way. Or, if you want to be fancy, Control.Monad.msum, since Maybe's an instance of MonadPlus.) One way is something like:
filter (\x -> case x of Just _ -> True; _ -> False) xs
But that's ugly. It turns out that pattern match failure (only within a do block or comprehension) calls fail, which can be defined by the monad, and within the list monad it just skips over that item. So you could write the above as:
[x | Just x ← xs]
or even:
do Just x ← xs; return x

The latter sort of pattern comes in handy sometimes when your filtering expression is more complicated than a simple pattern-match, or something that can be tucked into a one-line comprehension.