tail recursion question

Doug Edmunds (gmail) dougedmunds@REDACTED
Tue Apr 27 22:50:48 CEST 2010


In this example module, loop1 is tail recursive, but
are loop2 and loop3 equally tail recursive?
or do loop2 and loop3 leave something on the stack?

Thanks.
--dae--

-module(loops).
-compile(export_all).

start() ->
     register(loop1, spawn(?MODULE, loop1,[10])),
     register(loop2, spawn(?MODULE, loop2,[10])),
     register(loop3, spawn(?MODULE, loop3,[10])).

loop1(State) ->
     io:format("loop1:~p~n",[State]),
     receive
         a ->
             State2 = State - 1;
         b ->
             State2 = State + 1;
         _ ->
             State2 = State
     end,
     loop1(State2).


loop2(State) ->
     io:format("loop2:~p~n",[State]),
     receive
         a ->
             State2 = State - 1 ,
             loop2(State2);
         b ->
             State2 = State + 1 ,
             loop2(State2);
         _ ->
             State2 = State,
             loop2(State2)
   end.

loop3(State) ->
     io:format("loop3:~p~n",[State]),
     receive
         a ->
             State2 = State - 1 ,
             loop3(State2);
         b ->
             State2 = State + 1 ,
             loop3(State2);
         _ ->
             State2 = State,
             loop3(State2)
     end,
     never_reach_this().

never_reach_this() ->
     io:format("Am I tail recursive or not?").


More information about the erlang-questions mailing list