Haskell pattern matching symmetrical cases

Suppose I have a haskell expression, for example:

foo (Nothing, Just a) = bar a foo (Just a, Nothing) = bar a 

Is there any haskell syntax to collapse these cases, so I can match any pattern and specify bar a as the answer for both? Or is it as brief as I can understand it?

+8
syntax pattern-matching haskell
source share
3 answers

It is as red as in Haskell. There is syntax in ML for what you want (by writing several patterns that bind the same variables, next to each other, separated by | body after the last pattern), but this is not the case in Haskell.

+5
source share

If your code is more complex than your example, you can do something like this using the Alternative instance for Maybe and the PatternGuards extension (part of Haskell2010).

 {-# LANGUAGE PatternGuards #-} import Control.Applicative foo (x, y) | Just a <- y <|> x = bar a 

If you are not familiar with it, <|> selects the leftmost Just , if any, and returns Nothing otherwise, which will cause the template to fail to protect.

+8
source share

You can use -XViewPatterns to add arbitrary functions to collapse your two cases into one template. Now your template is a p function that gives what you want to combine:

 foo (p -> (Just a, Nothing)) = bar a 

much easier!

We must define p , though:

 p (Nothing, a@(Just _)) = (a, Nothing) pa@(Just _, Nothing) = a pa = a 

or you want to normalize the data before viewing.


Links: GHC Viewer Templates chapter

+4
source share

All Articles