Skip to content

Instantly share code, notes, and snippets.

@aryairani
Forked from anonymous/gist:af159ffc74b6a734b808
Last active August 29, 2015 14:01
Show Gist options
  • Save aryairani/fdf3a2c3bb5f4867e624 to your computer and use it in GitHub Desktop.
Save aryairani/fdf3a2c3bb5f4867e624 to your computer and use it in GitHub Desktop.
case class Action[S](when: (S) => Boolean,
then: (S) => Either[String, S],
name: String = "")
{
def apply(state: S): Either[String, S] =
if (when(state)) then(state)
else Left(s"The system could not execute the action '$name'.")
}
case class Goal[S](actionSet: List[Action[S]], name: String = "") {
def action(action: Action[S]) = Goal(action :: actionSet, name)
def apply(state: S): Either[String, S] =
scala.util.Random.shuffle(actionSet)
.foldLeft[Either[String,S]](Left(s"The goal '$name' has no actions.")) {
case (Left(_), action) => action(state)
case (success, _) => success
}
}
def a1 = Action[Int]( _ % 2 == 0, i => Right(i + 1), "Add one to divisible by 2.")
def a2 = Action[Int]( _ % 3 == 0, i => Right(i + 1), "Add one to divisible by 3.")
def a3 = Action[Int]( _ % 4 == 0, i => Right(i + 2), "Add two to divisible by 4.")
def g1 = Goal[Int](List(), "Add")
def g2 = g1.action(a1)
def g3 = g2.action(a2)
def g4 = g3.action(a3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment