[erlang-questions] Tail call optimization

Salikhov Dinislam Dinislam.Salikhov@REDACTED
Mon Oct 17 14:28:55 CEST 2016


The confusing thing is that the doc says about tail *recursive* call.
For example, if I have a call chain:
     a() ->
         % some code
         b().
     b() ->
         % some code
         c().
     % ...
     y() ->
         %some code
         z().
Recursion is *not* involved here. And I'd like to know if erlang 
requires (and guarantees) that all tail callees in the chain above use 
the stack of the caller.
AFAIU, compiler is free to not apply the optimization if it is not 
stated in the specification (and it is pure luck that the compiler does).

Salikhov Dinislam

On 10/17/2016 03:00 PM, Dmytro Lytovchenko wrote:
> In the doc page you linked:
> > If the last expression of a function body is a function call, a 
> *tail recursive* call is done.
>
> Compiler will replace call opcode with a tail call (call_last, 
> call_ext_last, apply_last). You can check it with "erl -S test.erl" to 
> see assembly, and in erl console: "l(modulename)." to load the module 
> then "erts_debug:df(modulename)." to create disassembly from BEAM VM 
> memory (it will be a bit different from the erl -S output).
>
> See that your calls are replaced with one of: call_last, 
> call_ext_last, apply_last.
>
> 2016-10-17 10:58 GMT+02:00 Salikhov Dinislam 
> <Dinislam.Salikhov@REDACTED 
> <mailto:Dinislam.Salikhov@REDACTED>>:
>
>     Hello.
>
>     Erlang guarantees tail recursion optimization and states it in the
>     documentation:
>     http://erlang.org/doc/reference_manual/functions.html#id78464
>     <http://erlang.org/doc/reference_manual/functions.html#id78464>
>
>     Does erlang guarantee that tail call optimization is done in a
>     generic case, without recursion?
>     Say, we have a function calling a function from another module as
>     its final statement:
>         alpha() ->
>             xxx:beta().
>     Is it guaranteed that xxx:beta() will use the stack of alpha()
>     regardless whether recursion is involved.
>     I mean whether the language guarantees it rather than virtual
>     machine may provide such optimization.
>
>     Thanks in advance,
>     Salikhov Dinislam
>
>     _______________________________________________
>     erlang-questions mailing list
>     erlang-questions@REDACTED <mailto:erlang-questions@REDACTED>
>     http://erlang.org/mailman/listinfo/erlang-questions
>     <http://erlang.org/mailman/listinfo/erlang-questions>
>
>

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20161017/2589dd7f/attachment.htm>


More information about the erlang-questions mailing list