Let's say I have this code here:
do_recv_loop(State) ->
receive
{do,Stuff} ->
case Stuff of
one_thing ->
do_one_thing(),
do_recv_loop(State);
another_thing ->
do_another_thing(),
do_recv_loop(State);
_ ->
im_dead_now
end
{die} -> im_dead_now;
_ -> do_recv_loop(State)
end.
Now, in theory this is tail-recursive, as none of the three calls to do_recv_loop require anything to be returned. But will erlang recognize that this is tail recursive and optimize appropriately? I'm worried that the nested structure might make it not able to recognize it.
The function len(Rest) itself then needed the result of another function call to be found. The additions would get stacked until the last one is found, and only then would the final result be calculated. Tail recursion aims to eliminate this stacking of operation by reducing them as they happen.
Advantages: Tail recursion optimizes the space complexity of the function by reducing the number of stack frames in the memory stack.
Tail recursion and tail-call optimization To keep the memory footprint to a minimum, some languages—like Erlang and thus Elixir—implement tail-call optimization.
Question: Which of the following algorithms would be best suited for a tail recursive implementation? Select the correct answer: file system traversal binary search of a sorted array depth first search of a tree randomized quicksort.
Yes, it will. Erlang is required to optimize tail calls, and this is clearly a tail call since nothing happens after the function is called.
I used to wish there were a tailcall
keyword in Erlang so the compiler could warn me about invalid uses, but then I got used to it.
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