[erlang-questions] tail recursion question
Valentin Micic
v@REDACTED
Wed Apr 28 00:22:14 CEST 2010
loop2 - yes, it is tail-recursive.
loop3 - following an approach that compiler should not second-guess a
programmer, I'd say *no*, this is not a tail-recursive function. This should
be relatively simple to test -- run the code by calling loop3/1, and see if
the memory increases over time. If it does (eventually dumping the core),
the loop3/1 is definitely *not* tail recursive :-)
V/
On 2010/04/27 10:50 PM, "Doug Edmunds (gmail)" <dougedmunds@REDACTED>
wrote:
> 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?").
>
> ________________________________________________________________
> erlang-questions (at) erlang.org mailing list.
> See http://www.erlang.org/faq.html
> To unsubscribe; mailto:erlang-questions-unsubscribe@REDACTED
>
More information about the erlang-questions
mailing list