Evan Martin (evan) wrote in evan_tech,
Evan Martin

haskell trick #2: using list monad fail

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.
Tags: haskell, howto

  • google ime

    Japanophiles might be interested to learn that Google released a Japanese IME. IME is the sort of NLP problem that Google is nearly uniquely…

  • megaupload captcha

    Someone make a Javascript-based captcha cracker for megaupload. It's strange to see those captchas again because I idly myself wrote a…

  • zombie ghosd

    I was tickled to discover another IBM developerworks article on one of my abandoned hacks and that both it and its predecessor have been translated…

  • Post a new comment


    default userpic
    When you submit the form an invisible reCAPTCHA check will be performed.
    You must follow the Privacy Policy and Google Terms of use.
  • 1 comment