Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does erlang handle case statements mixed with tail recursion

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.

like image 558
Mediocre Gopher Avatar asked Mar 24 '11 21:03

Mediocre Gopher


People also ask

What is tail recursion in Erlang?

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.

What is an advantage of tail recursion assuming a good compiler?

Advantages: Tail recursion optimizes the space complexity of the function by reducing the number of stack frames in the memory stack.

Does elixir have tail call optimization?

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.

Which algorithm is best for tail recursive implementation?

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.


1 Answers

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.

like image 59
nmichaels Avatar answered Oct 13 '22 15:10

nmichaels