What is the general way to implement a finite state machine (or finite state transducer) in Scala?
I often find myself in need for state machine implementation. My typical implementation looks like
object TypicalFSM { // actually — finite state transducer
type State
case object State1 extends State
case object State2 extends State
type Message
case object Message1 extends Message
type ResultMessage
case object ResultMessage1 extends ResultMessage
}
import TypicalFSM._
class TypicalFSM extends ((Message) =>Seq[ResultMessage]){
var state:State = State1
def apply(message:Message):Seq[ResultMessage] = (state, message) match {
case (State1, Message1) =>
state = State2
Seq(ResultMessage1, ResultMessage2)
}
}
What I dislike is the mutable var
which makes the solution thread unsafe. Also the FSM topology is not clear.
How to create FSMs in a functional way?
It also would be very good to draw FSM-graph in .dot format
Akka FSM has a good property of allowing to associate some Data with a State, not only giving an object name. This is also appreciated. (However, Akka FSM is not always convenient to use as it is asynchronous and sometimes a bit heavy-weight.)
This is probably not what you are looking for, but I think it's an interesting concept.
Usage would be like this:
Your use case would strongly determine the structure of the code in this concept. The use case really determines how much type information you want to keep.
I this concept because the state is kept using the type system and that illegal transitions are reported at compile-time.