Group matches in case of expression

I have a type variable

a = 3 

For some values ​​of a, I have the same function that I want to call:

 case a of 3 -> print "hello" 4 -> print "hello" 5 -> print "hello" 6 -> print "hello something else" 

So, for a = 3, a = 4 and a = 5, I am making the same function call. Can I group them better? I'm kind of looking for a solution that would be:

 case a of 3 || 4 || 5 -> print "hello" 6 -> print "hello something else" 

This does not work, of course, but I hope you get what I want to end up with.

Thanks.

+6
source share
2 answers

What about

 case a of _ | a == 3 || a == 4 || a == 5 -> print "hello" 6 -> print "hello something else" 

It will be less tiring to write

 case a of _ | a `elem` [3, 4, 5] -> print "hello" 6 -> print "hello something else" 

or

 case a of _ | 3 <= a && a <= 5 -> print "hello" 6 -> print "hello something else" 

or even if your real program had many possible values ​​for you, for example:

 import qualified Data.Set as S valuesToMatchAgainst :: S.Set Int valuesToMatchAgainst = S.fromList [3, 4, 5] -- ... case a of _ | a `S.elem` valuesToMatchAgainst -> print "hello" 6 -> print "hello something else" 

(I assume you already realized that _ is a wildcard that matches any value, and that | introduces protection .)

+13
source

You can do different things to improve your code. Firstly, if all branches name the same function, then why not:

 print (case a of 3 -> "hello" 4 -> "hello" 5 -> "hello" 6 -> "hello something else") 

This leads to a more general behavior of your code. Secondly, you seem to be asking the question of combining 3.4 and 5 cases together, a factorization function factor might be the best way:

  let cat 3 = True cat 4 = True cat 5 = True cat 6 = False in print (case cat a of True -> "hello" False -> "hello something else") 

You can combine this with one of the alternatives suggested by the previous poster ( cat x = x elem [3,4,5] , etc.).

+2
source

All Articles