Skip to content

Instantly share code, notes, and snippets.

Created May 17, 2014 02:11
Show Gist options
  • Save anonymous/af159ffc74b6a734b808 to your computer and use it in GitHub Desktop.
Save anonymous/af159ffc74b6a734b808 to your computer and use it in GitHub Desktop.
class Action[S](
val when: (S) => Boolean,
val then: (S) => Either[String, S],
val name: String = "") {
def apply(state: S): Either[String, S] = {
if (when(state)) {
then(state)
} else {
Left("The system could not execute the action '" + name + "'.")
}
}
}
package com.gmail.drewctaylor.scalaverse.planner
class Goal[S](val actionSet : List[Action[S]], val name : String = "") {
def action(action: Action[S]) : Goal[S] = {
new Goal(action :: actionSet, name)
}
def apply(state : S) : Either[String, S] = {
scala.util.Random.shuffle(actionSet).foldLeft(Left("The system could not satisfy the goal '" + name + "' .").asInstanceOf[Either[String, S]])((either : Either[String, S], action : Action[S]) => {
either match {
case Left(value) => action(state)
case Right(value) => Right(value)
}
})
}
}
def a1 = new Action[Int]((i : Int) => i % 2 == 0, (i : Int) => Right(i + 1), "Add one to divisible by 2.");
def a2 = new Action[Int]((i : Int) => i % 3 == 0, (i : Int) => Right(i + 1), "Add one to divisible by 3.");
def a3 = new Action[Int]((i : Int) => i % 4 == 0, (i : Int) => Right(i + 2), "Add two to divisible by 4.");
def g1 = new 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