[Haskell-cafe] Pattern guards in comprehensions

Richard Eisenberg eir at cis.upenn.edu
Mon Aug 10 02:53:01 UTC 2015


This can be done today:

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

The syntax is a bit regrettable, but it works quite well. You could use `Just n' <- return (n -? m)` if you wanted, or be even more pedantic and make a synonym `patternMatch :: a -> [a]; patternMatch = return` and say `Just n' <- patternMatch (n -? m)`.

Richard

On Aug 9, 2015, at 8:48 PM, M Farkas-Dyck <strake888 at gmail.com> wrote:

> 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?
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://mail.haskell.org/cgi-bin/mailman/listinfo/haskell-cafe



More information about the Haskell-Cafe mailing list