Erlang: Return from Function

I have a function in which I have a number of separate cases.

case ... of ... end, case ... of ... end, ... 

and etc.

I want to return from the function immediately when a particular condition is encountered in one of the case statements, so the next case statement is not checked, and the function simply exits / returns. How to do it?

+6
erlang functional-programming
source share
6 answers

I would suggest refactoring to take full advantage of Erlang's power and its pattern matching capabilities.

There is no return . Also, a little-known fact: you can do something like:

Return=case ... of

Operator

a case may have a value of "return".

+13
source share

Template compatibility is a good way to refactor case case - 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 just completes:

 X = testcase(Number, Param1, Param2). 

(in this far-fetched example, X will either be passed, or passed2, or passed too large or by default)

+12
source share

Erlang does not have a return . You will need to reorganize your code into smaller functions.

There are two case expressions in the source code encoded using the comma operator. I assume that you have some side effects in the first case that you want to keep. Below I use an imaginary return :

 case ... of P1 -> return E1; P2 -> E2; end, case ... of ... end 

Such an expression can be converted to real Erlang code using small functions and matching with something similar to this:

 case1(P1, ...) -> E1; case1(P2, ...) -> E2, case2(...). case2(...) -> ... 

Disclaimer: 10 years have passed since I wrote the Erlang code, so my syntax may be disabled.

+4
source share

In Erlang, you simply use pattern matching to call the corresponding function. If you have too many suggestions to cover and process, I would also suggest a bit of code rework.

+2
source share

One way is to cascade the statements of your case:

 my_fun(X) -> case cond1(X) of true -> ret1; _ -> case cond2(X) of true -> ret2; _ -> ... end end. 

Another is to split your case statements into sentences:

 my_fun(X) -> my_fun(cond1, X). my_fun(cond1, X) -> case cond1(X) of true -> ret1; _ -> my_fun(cond2, X) end; my_fun(cond2, X) -> case cond2(X) of true -> ret2; _ -> my_fun(cond3, X) end; ... 
+2
source share

use catch / throw

The caller says:

  X = (catch foo (A, B)).

then write

  foo (A, B) ->
     case ... of
      ... throw (X) ..
     end

     case ... of
      ... throw (Y)
     end
     ...

This is usually considered bad programming practice - since the program has multiple outputs and is difficult to give in to

0
source share

All Articles