Created
December 9, 2021 15:42
-
-
Save mrbald/521f3a5ecd93be6317a11c1041ce84d0 to your computer and use it in GitHub Desktop.
Ridiculously Simple FSM DSL in Scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* A Ridiculously Simple FSM DSL in Scala, similar to AKKA Actor-based FSM syntax | |
* | |
* def MY_STATE(...args...) = state("MY_STATE") { | |
* ... do something on entry ... | |
* events { | |
* case MyEvent => | |
* ... do something on event ... | |
* MY_OTHER_STATE(...) | |
* } | |
* } | |
* | |
* ... then somewhere else ... | |
* var state = MY_STATE | |
* while (...) { state = state + event_queue.poll() } | |
*/ | |
FsmDsl { | |
type BehaviorPf = PartialFunction[Event, Behavior] | |
sealed trait Behavior extends BehaviorPf { | |
val name: String | |
def +(event: Event): Behavior = applyOrElse(event, (_: Event) => this) | |
} | |
def state(name: String)(supplier: => BehaviorPf): Behavior = supplier match { | |
case b: Behavior => b | |
case pf => behavior(name, pf) | |
} | |
def events(pf: BehaviorPf): BehaviorPf = pf | |
val ignore_events: BehaviorPf = events(PartialFunction.empty) | |
private def behavior(n: String, pf: BehaviorPf): Behavior = new Behavior { | |
override val name: String = n | |
override def isDefinedAt(event: Event): Boolean = pf.isDefinedAt(event) | |
override def apply(event: Event): Behavior = pf.apply(event) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment