Skip to content

Commit

Permalink
Merge pull request fpinscala#419 from x7c1/refactor-candy-answer
Browse files Browse the repository at this point in the history
Simplify answer to exercise 6.11
  • Loading branch information
runarorama committed Jun 26, 2015
2 parents b118cfd + 70cf952 commit 5166981
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 6 deletions.
9 changes: 6 additions & 3 deletions answerkey/state/11.answer.scala
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,19 @@ case object Turn extends Input
case class Machine(locked: Boolean, candies: Int, coins: Int)

object Candy {
def simulateMachine(inputs: List[Input]): State[Machine, (Int, Int)] = for {
_ <- sequence(inputs.map(i => modify((s: Machine) => (i, s) match {
def update = (i: Input) => (s: Machine) =>
(i, s) match {
case (_, Machine(_, 0, _)) => s
case (Coin, Machine(false, _, _)) => s
case (Turn, Machine(true, _, _)) => s
case (Coin, Machine(true, candy, coin)) =>
Machine(false, candy, coin + 1)
case (Turn, Machine(false, candy, coin)) =>
Machine(true, candy - 1, coin)
})))
}

def simulateMachine(inputs: List[Input]): State[Machine, (Int, Int)] = for {
_ <- sequence(inputs map (modify[Machine] _ compose update))
s <- get
} yield (s.coins, s.candies)
}
9 changes: 6 additions & 3 deletions answers/src/main/scala/fpinscala/state/State.scala
Original file line number Diff line number Diff line change
Expand Up @@ -222,16 +222,19 @@ case object Turn extends Input
case class Machine(locked: Boolean, candies: Int, coins: Int)

object Candy {
def simulateMachine(inputs: List[Input]): State[Machine, (Int, Int)] = for {
_ <- sequence(inputs.map(i => modify((s: Machine) => (i, s) match {
def update = (i: Input) => (s: Machine) =>
(i, s) match {
case (_, Machine(_, 0, _)) => s
case (Coin, Machine(false, _, _)) => s
case (Turn, Machine(true, _, _)) => s
case (Coin, Machine(true, candy, coin)) =>
Machine(false, candy, coin + 1)
case (Turn, Machine(false, candy, coin)) =>
Machine(true, candy - 1, coin)
})))
}

def simulateMachine(inputs: List[Input]): State[Machine, (Int, Int)] = for {
_ <- sequence(inputs map (modify[Machine] _ compose update))
s <- get
} yield (s.coins, s.candies)
}
Expand Down

0 comments on commit 5166981

Please sign in to comment.