I have a function in which I have a series of individual case statements.
case ... of
...
end,
case ... of
...
end,
...
etc.
I want to return from the function immediately when a particular case condition occurs in one of the case statements - so that the next case statement is not checked, and the function just exits/returns. How do I do that?
I would suggest you refactor to harness the full power of Erlang and its pattern matching abilities.
There isn't a return
operator. Also, a little known fact is you can do something like:
Return=case ... of
a case
statement can have a "return" value.
Pattern matching is a good way to refactor a case statement - you can do something like this
testcase(1, X, Y) -> .... passed1;
testcase(2, X, Y) -> .... passed2;
testcase(N, X, Y) when N > 2 -> .... passedlarge;
testcase(_, X, Y) -> defaultcase.
and then your case statement simply wraps up to:
X = testcase(Number, Param1, Param2).
(X will be either passed1, passed2, passedlarge or defaultcase in this contrived example)
Erlang does not have a return
operator. You will need to refactor your code into smaller functions.
Your original code has two case expressions chained with the comma operator. I presume you have some side effects in the first case expression that you want to preserve. Below, I'm using an imaginary return
operator:
case ... of
P1 -> return E1;
P2 -> E2;
end,
case ... of
...
end
An expression like this can be converted to real Erlang code using small functions and pattern matching with something resembling this:
case1(P1, ...) -> E1;
case1(P2, ...) -> E2, case2(...).
case2(...) -> ...
Disclaimer: It's been 10 years since I've written Erlang code, so my syntax may be off.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With