More than one match in a statement of a case in Erlang?

I have a piece of code like this:

case sth of {a, 1} -> doA(); {a, 2} -> doA(); {a, 3} -> doB() end. 

Is there a way to not repeat the "doA ()" part? I thought this should be easy, but I could not find the answer on google.

+8
erlang case
source share
2 answers

Apart from using the guards in the manner suggested by @Bunnit, there is no way to avoid repeating the provisions of the reservation. There are no alternative templates in one sentence. In your case there are not many repetitions, but if the repetitive body was more complex, the best way would be to put it in a separate function and call it.

Adding this function, if possible, will lead to some โ€œinterestingโ€ processing of variables.

+13
source share

You can use when guards in a case statement, such as:

 case sth of {a, Var} when Var < 3-> doA(); {a, 3} -> doB() end. 

Also, your expression ( sth ) is an atom, meaning it can never be compared to any of these cases.

+19
source share

All Articles