I am looking at ways to implement FSM that led to my first encounter with coroutines.
I have seen several examples ( here , here, and here ) that hint that a state machine can be implemented by a single coroutine. However, what I noticed that all these machines have in common is that, with the exception of loops, they are trees - that is, there is one path (excluding loops) from the very beginning of the node for all the other nodes - and that displays well to the hierarchical control flow provided by nested ifs. I am trying to simulate a state machine with at least one state with several paths from the very beginning of the node (if the cycles are eliminated, this is a directed acyclic graph). and I cannot imagine what control flow (except gotos) can achieve this, or if at all possible.
As an alternative, I can use a separate coroutine to process each state and move on to some dispatch coroutine. However, I do not see any particular advantages of using coroutines over regular functions in this setting.
Here is a simple machine that is difficult for me to model:
A
A
B
B
C
C
And that's what I still have. The final implementation will be in C ++ using Boost, but I use Python for prototyping.
def StateMachine():
while True:
print(" Entered state A")
input = (yield)
if input == "a":
print(" Entered state B")
input = (yield)
if input == "a":
pass
elif input == "b":
continue
elif input == "b":
print(" Entered state C")
input = (yield)
if input == "b":
continue
elif input == "a":
pass
if __name__ == "__main__":
sm = StateMachine()
sm.__next__()
while True:
for line in input():
sm.send(line)
Is it possible to fix this coroutine in order to correctly model the state machine? Or do I need to go differently?
source
share