An Introduction to Erlang
Subject:   Recursion? Goto?
Date:   2007-12-20 19:37:17
From:   rickhg12hs
A complete newbie question ...


loop(MyName) ->
{ accept, SenderName, Message } ->
io:format("~n~s receives from ~s: ~s ~n", [MyName, SenderName, Message]),

{ say, Message } ->
io:format("~n~s says ~s ~n",[MyName, Message]),
room ! { self(), broadcast, MyName, Message },


Is "loop(MyName)" a recursive call? ... a goto? What happens under the hood? E.g., is a completely new call stack generated for each "loop(MyName)"?

Thanks for the intro article. It's got me interested in Erlang.

Full Threads Newest First

Showing messages 1 through 3 of 3.

  • Gregory Brown photo Recursion? Goto?
    2007-12-21 03:46:33  Gregory Brown | O'Reilly AuthorO'Reilly Blogger [View]

    Hi. The call to loop() is a simply a recursive call. Functional languages are optimized to handle recursion efficiently, and Erlang is no exception.

    I'm mostly an Erlang newbie, so I won't venture into guessing what the optimizations are, but I will say that virtually all Erlang code you write will include recursion in some form or another.

    I'm glad you enjoyed the article. I need to dig up and dust off some code that I wrote that does simplified neural networking in Erlang. If I ever do that, you'll find it under an Erlang tag at

    • Recursion? Goto?
      2007-12-21 18:20:52  rickhg12hs [View]

      Thanks for the response.

      I'll have to learn more about Erlang and how it does recursion. Seems like after some enormous number of messages, the chat system would run out of memory by the ever increasing stack ... so I guess that's not how Erlang handles it. Very interesting.
      • Recursion? Goto?
        2008-01-09 21:19:11  MattKangas [View]

        Erlang supports efficient tail recursion. Since the chat server's functions recurse as the last statement in the function, they are tail-recursive, so they can recurse infinitely without penalty.

        To quote the book ("Programming In Erlang", pp.149)

        "A tail-recursive function can be compiled so that the last function call in a sequence of statements can be replaced by a single jump to the start of the function being called. This means that a tail-recursive function can loop forever without consuming stack space."

        This is standard behavior for functional languages like Erlang, Scheme, Lisp, et al.