Created
September 26, 2017 22:10
-
-
Save jimleroyer/1ce238b3934882ddc02a09485f52f407 to your computer and use it in GitHub Desktop.
Scala Workflow using forSome existentials
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
import scala.language.existentials | |
// Simple laboratory exercise that uses existentials everywhere for the Transition. | |
// But these existentials are not bound to much restriction and are not recognized | |
// to be compatible with the built list of transitions. | |
object Lab { | |
/** ************** Types */ | |
trait StateDef { | |
def id: String | |
} | |
case class State[CV](override val id: String, context: CV) extends StateDef | |
trait Action[P, R] | |
abstract class Condition[-T] extends Function1[T, Boolean] { | |
override def apply(contextState: T): Boolean | |
} | |
case class Transition[P, R](tailState: StateDef, headState: StateDef, action: Action[P, R], condition: Option[Condition[P]] = None) | |
case class Workflow private(transitions: List[Transition[P forSome {type P}, R forSome {type R}]]) { | |
def getTransitions(tail: StateDef, head: StateDef): List[Transition[P forSome {type P}, R forSome {type R}]] = { | |
transitions.filter(t => true) | |
} | |
def matchTransition[P <: Nothing](tail: State[P], head: StateDef): Option[Transition[P forSome {type P}, R forSome {type R}]] = { | |
val value = tail.context | |
val transitions: List[Transition[P forSome {type P}, R forSome {type R}]] = getTransitions(tail, head) | |
transitions.find(t => t.condition.forall(cond => cond(value))) | |
} | |
} | |
/** ************** Fixtures */ | |
// Model | |
case class CreateImage() | |
case class Image() | |
// States | |
class Init extends State[CreateImage]("INIT", CreateImage()) | |
val init = new Init() | |
case object Published extends StateDef { | |
override def id: String = "PUBLISHED" | |
} | |
// Action | |
class CreateTipAction extends Action[CreateImage, Image] | |
/** ************** Demo */ | |
val transitions = List( | |
Transition(init, Published, new CreateTipAction()) | |
) | |
val w = Workflow(transitions) | |
val t = w.matchTransition(init, Published) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment