[erlang-questions] tail recursion

ok ok@REDACTED
Fri Jun 1 05:33:26 CEST 2007


On 31 May 2007, at 12:26 pm, Jason Dusek wrote:

> I have a server like this:
>
> server({X, Y}) ->
>   receive
>     {update, NewState} -> server(NewState);
>     {x, Client} -> Client ! X, server({X, Y});
>     {y, Client} -> Client ! Y, server({X, Y});
>   end
>   .
>
> It's tail recursive but, unfortunately, a little redundant -- I'd like
> to rewrite it like this:
>
> server({X, Y}) ->
>   receive
>     {update, NewState} -> server(NewState);
>     {x, Client} -> Client ! X;
>     {y, Client} -> Client ! Y;
>   end,
>   server({X, Y})
>   .
>
> But I worry that the compiler and interpreter will fail to recognize
> my server as tail recursive. Will my rewrite blow the stack?

The update case really ISN'T tail recursive.  Worse, if for some
reason the first server/1 call returns, the code will resume the
old one.

Let's restructure this cleanly:

	server(State = {X,Y}) ->
	    Next_State =
		receive
	            {update,New_State} -> New_State
		;   {x,Client} -> Client ! X, State
		;   {y,Client} -> Client ! Y, State
		end,
	    server(Next_State).





More information about the erlang-questions mailing list