How to combine case case templates

I am trying to match many different constructors in a case case. For simplicity, suppose that in half the cases we do the same, and in the other half we do something else. Even if I explain the logic of another function, I still have to write:

case x of C1 -> foo x C2 -> foo x ... C10 -> bar x C11 -> bar x ... 

Is there a way to make case statements look more like switch in C (i.e., fail) or so that I can combine one of many patterns at the same time, for example:

 case x of C1, C2, C3 -> foo x C10, C11, C12 -> bar x 

Or perhaps another way to clear this?

+5
source share
1 answer

They are called disjunctive patterns, but Haskell doesn't have them. (OCaml and F # do.) However, there are several typical workarounds. If your type is an enum, you can use equality, for example elem :

 case cond of c | c `elem` [C1, C2, C3] -> foo | c `elem` [C10, C11, C12] -> bar | otherwise -> baz 

And, of course, if foo or bar are long expressions, thanks to laziness, you can simply decompose them into local definitions, so you only need to repeat the name and any template variables that you need as arguments:

 case cond of C1 x -> foo x C2 y -> foo y ... C10 -> bar C11 -> bar ... where foo x = something long (involving x, presumably) bar = if you please then something else quite long 
+8
source

Source: https://habr.com/ru/post/1216044/


All Articles