Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Erlang : Returning from a function

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?

like image 561
jeffreyveon Avatar asked Dec 08 '09 12:12

jeffreyveon


3 Answers

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.

like image 150
jldupont Avatar answered Nov 04 '22 17:11

jldupont


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)

like image 12
Alan Moore Avatar answered Nov 04 '22 16:11

Alan Moore


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.

like image 6
Ville Laurikari Avatar answered Nov 04 '22 17:11

Ville Laurikari