[erlang-questions] tail recursion

Ulf Wiger ulf@REDACTED
Thu May 31 08:32:10 CEST 2007


2007/5/31, Jason Dusek <jsnx@REDACTED>:
>
>
> Its 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?
>

Yup, since the call to server/1 from within the receive clause is not in
fact a tail call.

A common way to solve this dilemma is to do this:

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

I added the "= State" in the function head so I wouldn't have to rebuild the
tuple when nothing has changed.

BR,
Ulf W
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20070531/0ee20407/attachment.htm>


More information about the erlang-questions mailing list