Re:Facts about State Machines
by rowanG077 on Friday September 30, 2022 @06:38PM
(#33041661)
It really depends on your programming language. In C it's not much more then a switch case over an enum where every enum value is a concrete state. It languages with pattern matching and ADTs it's much more ergonomic since a state machine then is just a function from a state and an input to a new state and an output.
[ Parent
| on HN ]
typedef struct State State, *StateMachine;
typedef void (*Event)(StateMachine *sm);
struct State {
Event TurnOn;
Event TurnOff;
Event MakeStuck;
};
void IdleTransition(StateMachine *sm);
void BecomeOn(StateMachine *sm);
void BecomeOff(StateMachine *sm);
void BecomeStuck(StateMachine *sm);
const State StateOn = {
.TurnOn = IdleTransition,
.TurnOff = BecomeOff,
.MakeStuck = BecomeStuck
};
const State StateOff = {
.TurnOn = BecomeOn,
.TurnOff = IdleTransition,
.MakeStuck = BecomeStuck
};
const State StateStuck = {
.TurnOn = IdleTransition,
.TurnOff = IdleTransition,
.MakeStuck = IdleTransition
};
void IdleTransition(StateMachine *sm) { }
void BecomeOn(StateMachine *sm) { *sm = &StateOn; }
void BecomeOff(StateMachine *sm) { *sm = &StateOff; }
void BecomeStuck(StateMachine *sm) { *sm = &StateStuck; }
StateMachine sm = &StateOff;
It's still C but arguably much more concise than a switch, wouldn't you agree?For large state machines sure. For smaller ones no. My point wasn't that enum is the only way to do it in C. Just a simple representation that is used in practice that I could explain in a single sentence.
>"In C it's not much more then a switch case over an enum where every enum value is a concrete state."
This is but stupidly primitive representation / implementation of SM (yes it is useful in very simple cases). You can do way better in C. Somebody else already presented more advanced design.