3 ms·
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
by rowanG077 4y ago
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.
- Joker_vD 4y agotypedef 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?
- rowanG077 4y agoFor 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.
- FpUser 4y ago>"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.