[erlang-questions] Why doesn't Erlang has return statement?

Richard A. O'Keefe <>
Thu Dec 18 03:40:03 CET 2014


Let me offer one example of how ‘return’ can affect things.

Suppose I have a function

   foo(<|args|>) ->
      <|stuff|>.

Now suppose I discover that this is sometimes returning integers
and sometimes returning floats, but my life would be easier if
it always returned floats.  Easy:

    foo(<|args|>) ->
        float((
        <|stuff|>)).

I don’t have to look inside <|stuff|> at all.  Any value returned
will be caught this way.  But in the presence of ‘return’, I have
to locate each and every ‘return’ and patch that separately.

Yes, I have had to do this kind of thing in C.  I am actually
quite tired of writing
   #define safely(e) (void)(<|clean up|>), e
macros and changing
    return e;
to
    return safely(e);
and then finding I’ve missed one.   This is of course why
Lisp provides unwind-protect, which Java copied as
try-finally.

What is the price of NOT having return?

Code duplication in a few rare cases.

case E1 of P1 -> .., ^E2 ; P2 -> .., ^E3 ; P3 -> .. ; P4 -> .. end, E5

has to become

case E1 of P1 -> .., E2 ; P2 -> .., E3 ; P3 -> .., E5 ; P4 -> .., E5 end

A compiler that does cross-jumping optimisation can eliminate the
duplication in the BEAM code.

If you keep your function bodies small, a little bit of duplication
won’t be a problem.  (Is Garrett Smith reading this thread?)


More information about the erlang-questions mailing list