[Haskell-cafe] Pattern guards in comprehensions

M Farkas-Dyck strake888 at gmail.com
Mon Aug 10 00:48:33 UTC 2015


I propose we add pattern guards in comprehensions, but I'm not sure what syntax would work. Consider this function:

allMinus :: [Natural] -> [Natural]
allMinus m = mapMaybe (-? m)
  where n -? m | m > n = Nothing
                     | True  = Just (n-m)

One may wish to write such as a list comprehension, but it is cumbersome:

allMinus m ns = [n' | n@((-? m) -> Just n') <- ns]

This would be clearer with pattern guards, fictitious syntax here:

allMinus m ns = [n' | n <- ns, Just n' <- n -? m]

Alas, this conflicts with the other part of list comprehension syntax. Try we this, actual syntax now:

allMinus m ns = [n' | n <- ns, let Just n' = n -? m]

Nope, that's an error if (any (< m) ns).

I recognize in this case the one in terms of mapMaybe is quite clear, but in the case of some other code I'm writing it's much more complicated.

Ideas:
1. Modify semantics of let in comprehension to skip that element on pattern mismatch
2. Use another keyword, e.g. [n' | n <- ns where Just n' <- n -? m]

Thoughts?


More information about the Haskell-Cafe mailing list