Re: finite state machine
- From: Logan Shaw <lshaw-usenet@xxxxxxxxxxxxx>
- Date: Sun, 16 Dec 2007 01:42:44 -0600
bob@xxxxxxxxxxxxxx wrote:
What is the best way to translate a finite state machine into code?
There are sort of two ways to take this question. One is that you want
to make some kind of complex transformation, so that you go from a
state machine to code that no longer looks like a finite state machine
when you're done with it. I don't really have any comments on this
first interpretation.
The other interpretation is that you really want to think in terms of a
finite state machine (because that sort of model is useful for working
with whatever type of problem you are solving) and you want to write code
that will look and work like a state machine, but you're just looking for
a pattern on how to do that. That is, you want to basically transliterate
a state machine into code and you're looking for a good, clean way to do
it in a commonly-used programming language.
For this second interpretation, I can suggest three obvious ways.
The first method is to simply define an enumerated type (enum in C) where
each value of the enum is a state. Then have a while loop that contains
a switch statement. The switch statement will switch on the state and
each case of the switch statement will run code for a state, setting the
new state.
The second method is to assign an integer value for each state, then define
a table of function pointers. Then you have loop just like in the first
method, but instead of using a switch statement in the body, you simply
use the current state as an index into the table (probably an array) of
function pointers, and you call the function you get out of the table.
The function returns the next state as its return value.
And the third method is like the second, but you eliminate the array.
You simply have functions return pointers to other functions. Then the
loop simply calls a function, stores its return value (which is a function
pointer), and then when it repeats calls the function specified by the
return value. This is actually very similar to your method where one
function calls another, but since you return first and it is a loop body
that repeatedly calls functions, you don't need to worry about the stack
overflowing.
- Logan
.
- References:
- finite state machine
- From: bob
- finite state machine
- Prev by Date: Re: finite state machine
- Next by Date: Re: finite state machine
- Previous by thread: Re: finite state machine
- Next by thread: Re: finite state machine
- Index(es):
Relevant Pages
|