zie1ony
zie1ony

Reputation: 1270

More than one match in case statement in Erlang?

I have that kind piece of code:

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

Is there a way not to repeat "doA()" part? I thought that it should be easy, but I couldn't found answer in google.

Upvotes: 13

Views: 9351

Answers (2)

rvirding
rvirding

Reputation: 20926

Apart from using guards in a manner suggested by @Bunnit there is no way of avoiding repeating the clause bodies. There is no way of having alternate patterns in one clause. In your case there is not much repetition but if the repeated body was more complex then the best way is to put it in a separate function and call that.

Adding this feature, while possible, would lead to some "interesting" handling of variables.

Upvotes: 15

Scott Logan
Scott Logan

Reputation: 1516

You can use when guards in the case statement such as:

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

Also your expression(sth) is an atom here meaning it can never match any of those cases.

Upvotes: 23

Related Questions