large gen_fsms

Richard Cameron camster@REDACTED
Mon Mar 20 22:10:48 CET 2006


On 20 Mar 2006, at 19:59, Alex Arnon wrote:

> state1() ->
>         receive
>                 go_to_state_2 -> state2();
>                 _ -> state1()
>         end.
>
> state2() ->
>         receive
>                 go_to_state_1 -> state1();
>                 go_to_state_3 -> state2()
>         end.
>
> ...
>
> Wouldn't this cause the stack to bloat indefinitely? Or does tail- 
> calling eliminate this in Erlang?

  No. Erlang has "last call optimisation" (of which tail recursion is  
a specific case). The code above will execute in constant space.

You'll sometimes also notice last call optimisation when you're  
debugging Erlang code. For instance:

---

-module(x).

-compile(export_all).

f() ->
	g().

g() ->
	math:sqrt(-1).

---

g() will generate a runtime 'badarith' expression. If you call f()  
from the shell and look carefully at the stack trace you'll notice  
something odd - there's no mention of the call to f() anywhere. It  
simply disappeared when it made an LCO call to g():


  1> x:f().

=ERROR REPORT==== 20-Mar-2006::21:09:21 ===
Error in process <0.64.0> with exit value: {badarith,[{math,sqrt, 
[-1]},{x,g,0},{erl_eval,do_apply,5},{shell,exprs,6},{shell,eval_loop, 
3}]}

** exited: {badarith,[{math,sqrt,[-1]},
                       {x,g,0},
                       {erl_eval,do_apply,5},
                       {shell,exprs,6},
                       {shell,eval_loop,3}]} **




More information about the erlang-questions mailing list