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

  • socks5 proxying flash via ssh

    Suppose you're in Germany and want to watch some Flash-based videos that are IP-limited to the US for whatever reason. At first you'd think you could…

  • your vcs sucks

    I've been hacking on some Haskell stuff lately that's all managed in darcs and it's reminded me of an observation I made over two years ago now (see…

  • ghc llvm

    I read this thesis on an LLVM backend for GHC, primarily because I was curious to learn more about GHC internals. The thesis serves well as an…

  • 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