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

  • blog moved

    As described elsewhere, I've quit LiveJournal. If you're interested in my continuing posts, you should look at one of these (each contains feed…

  • dremel

    They published a paper on Dremel, my favorite previously-unpublished tool from the Google toolchest. Greg Linden discusses it: "[...] it is capable…

  • treemaps

    I finally wrote up my recent adventures in treemapping, complete with nifty clickable visualizations.

  • 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