src/main/scala/Robot.scala

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
object Bearing extends Enumeration{
  val North, East, South, West = Value
  val Direction = Map(
    North -> (0, 1),
    East  -> (1, 0),
    South -> (0, -1),
    West  -> (-1, 0)
  );
  val CompassPoint = Direction.map(_ swap)
}

case class Robot(val bearing: Bearing.Value, val coordinates: (Int, Int)) {
  type Commands = String
  private val (x, y) = coordinates
  private val (dx, dy) = Bearing.Direction(bearing)

  def turnRight() = Robot(Bearing.CompassPoint(dy, -dx), coordinates)
  def turnLeft() = Robot(Bearing.CompassPoint(-dy, dx), coordinates)
  def advance() = Robot(bearing, (x + dx, y + dy))

  def simulate(sequence: Commands): Robot =
    sequence.foldLeft(this) {
      (robot, command) => command match {
        case 'L' => robot.turnLeft
        case 'R' => robot.turnRight
        case 'A' => robot.advance
      }
    }
}

@abo64 thinks this looks great

Comments

tidied up simulate with help of old friend foldLeft :-)

helenst commented 4 June 2016 at 18:01 UTC

yes, I often wonder how I could live w/o foldLeft! ;-)

abo64 commented 6 June 2016 at 06:07 UTC

You're not logged in right now. Please login via GitHub to comment