Advertisement
Guest User

Untitled

a guest
Oct 27th, 2014
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.88 KB | None | 0 0
  1. import scalaz._
  2. import Scalaz._
  3. import scalaz.Free._
  4. import game._
  5.  
  6. implicit def dGameFunctor = new Functor[DGame] {
  7.   def map[A, B](game: DGame[A])(f: A => B): DGame[B] = game match {
  8.     case DContinue(next) => DContinue(f(next))
  9.     case DInputRequired(next) => DInputRequired(next andThen f)
  10.     case gameOver @ DGameOver(_) => gameOver
  11.   }
  12. }
  13. def interpretGame(inputs: Seq[DInput], game: Free[DGame, DGameState]): DGameState = game.resume.fold({
  14.   case DContinue(next) => interpretGame(inputs, next)
  15.   case DInputRequired(next) => interpretGame(inputs.tail, next(inputs.head))
  16.   case DGameOver(gameState) => gameState
  17. }, identity)
  18.  
  19. def continue[Next](next: Next) = liftF(DContinue(next): DGame[Next])
  20. def getInput = liftF(DInputRequired(identity): DGame[DInput])
  21. def gameOver[Next](gameState: DGameState) = liftF(DGameOver(gameState): DGame[Next])
  22. def gameState(x: Int) = continue(DGameState(x))
  23.  
  24. def applyInput(game: Free[DGame, DGameState]) = for {
  25.   gameState <- game
  26.   num = gameState.num
  27.   input <- getInput
  28.   result <- input match {
  29.     case Inc => continue(DGameState(num+1))
  30.     case Dec => continue(DGameState(num-1))
  31.     case Add(x) => continue(DGameState(num+x))
  32.     case Set(x) => continue(DGameState(x))
  33.     case EndGame => gameOver[DGameState](gameState)
  34.   }
  35. } yield result
  36.  
  37. def gameWithInputs(initial: DGameState, numInputs: Int): Free[DGame, DGameState] =
  38.   if(numInputs == 0) continue(initial)
  39.   else for {
  40.     nextState <- applyInput(continue(initial))
  41.     result <- gameWithInputs(nextState, numInputs - 1)
  42.   } yield result
  43.  
  44. interpretGame(Nil, gameState(5)) // DGameState(5)
  45. interpretGame(Set(5) :: Inc :: Nil, applyInput(applyInput(gameState(0)))) // DGameState(6)
  46. interpretGame(Set(5) :: Inc :: Inc :: Nil, gameWithInputs(DGameState(0), 3)) // DGameState(7)
  47. interpretGame(Set(5) :: EndGame :: Inc :: Nil, gameWithInputs(DGameState(0), 3)) // DGameState(5)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement