[erlang-questions] Please help me relate a past project to Erlang, I'm trying to understand...

Paul Fisher pfisher@REDACTED
Fri Mar 13 00:42:18 CET 2009


bill robertson wrote:
> So I've been thinking more about Erlang lately, and I still haven't
> gotten over a conceptual hurdle.  Where do you keep state?

The actual key is to remember that function calls in erlang are 
call-recursive, so a simple function that calls itself consumes only one 
  level in stack no matter how many times it loops.  This extends to 
sequences of calls too, as long as each call to recursive function is 
the return value of the calling function.

A simple example:

-record(state, { foo, boo, bar }).
loop(#state{} = State) ->
     receive
         {some, Foo} ->
             %% do something here with Foo and anything else in State
             loop( State#state{ foo = Foo } );
         {interesting, Boo} ->
             %% do something here with Boo and anything else in State
             loop( State#state{ boo = Boo } );
         {messages, Foo} ->
             %% do something here with Bar and anything else in State
             loop( State#state{ bar = Bar } )
     end.

If you spawn loop/1 as a process, then it will simply keep going 
processing messages that it receives.

Now OTP captures this in a pair of abstractions called gen_server and 
gen_fsm, which are a generalized server and generalized finite state 
machine, respectively.  I encourage you to look into these as they make 
thing easier as you get further along in structuring larger solutions. 
These are documented in the stdlib application:

http://www.erlang.org/doc/apps/stdlib/index.html


--
paul



More information about the erlang-questions mailing list