A state machine contains another state machine

6 Jan 2015

Today, I've just implemented a state machine that contains another state machine. It confused the heck out of me.

Normally, a state machine can be implemented with a 2-dimensional array pretty easily. But when a state machine can have another state machine inside, it becomes very difficult to stick with 2-dimensional arrays.

Apart from that, I also prefer linking states (or nodes) instead of maintaining a 2-dimensional arrays. Here's how a state looks like:

class State { def name: String def edges: Seq[(CharMatcher, State)] def next(c: Char): Option[State] }

This implementation is nicer than the 2-dimensional arrays approach because …. (why is it better?)

A state machine can look like this:

class StateMachine { var currentState: State def next(c: Char): Unit { currentState.next(c) match { case Some(nextState) => currentState = nextState case None => // reach rejection } }

That looks pretty simple. Nevertheless, when we want to implement a sub state machine, that will get more complicated.


Give it a kudos