Erlang processes can be used to implement finite state machines. A finite state machine, or FSM for short, is a model that consists of a finite number of states and events. You can think of an FSM as a model of the world which will contain abstractions from the details of the real system. At any one time, the FSM is in a specific state. Depending on the incoming event and the current state of the FSM, a set of actions and a transition to a new state will occur (see Figure 5-5).
Figure 5-5. A finite state machine
In Erlang, each state is represented as a tail-recursive function,
and each event is represented as an incoming message. When a message is
received and matched in a
clause, a set of actions are executed. These actions are followed by a
state transition achieved by calling the function corresponding to the new
As an example, think of modeling a fixed-line phone as a finite
state machine (see Figure 5-6). The phone can be in
idle state when it is plugged in
and waiting either for an incoming phone call or for a user to take it
off the hook. If you receive an incoming call from your aunt, the phone will start ringing. Once it has started ringing,
the state will change from
ringing and will wait for one of two events. You can pretend to be asleep, hopefully resulting in your aunt giving up on you and putting the phone ...