[erlang-questions] tail recursion
Joe Armstrong
erlang@REDACTED
Thu May 31 12:23:31 CEST 2007
On 5/31/07, Ulf Wiger <ulf@REDACTED> wrote:
>
>
> 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.
>
Why not just
server({X, Y} = State) ->
receive
{update, NewState} ->
NewState;
{x, Client} ->
Client ! X,
server(State);
{y, Client} ->
Client ! Y,
sever(State)
end.
/Joe
> BR,
> Ulf W
>
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://www.erlang.org/mailman/listinfo/erlang-questions
>
>
More information about the erlang-questions
mailing list