Skip to content

Instantly share code, notes, and snippets.

@a2mz
Forked from pfcoperez/RobotCommands.scala
Last active June 28, 2017 13:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save a2mz/f7552d9365aa980508c35ee98c7aa7c9 to your computer and use it in GitHub Desktop.
Save a2mz/f7552d9365aa980508c35ee98c7aa7c9 to your computer and use it in GitHub Desktop.
[Parsers] Parsers combinators example #scala #parsers
import scala.util.parsing.combinator._
object RobotCommands extends App {
object Entities {
trait MovementDirection
case object Up extends MovementDirection
case object Down extends MovementDirection
case object Left extends MovementDirection
case object Right extends MovementDirection
case class Robot(id: String)
trait Command {
val robot: Robot
}
case class Move(robot: Robot, direction: MovementDirection) extends Command
}
import Entities._
object Parser extends RegexParsers {
//One letter followed by a number
def robotId: Parser[String] = """[A-Z][1-9]+""".r ^^ { _.toString }
//New robots declarations
def declare: Parser[Robot] = "NEW ROBOT(" ~ robotId ~ ")" ^^ {
case _ ~ id ~ _ => Robot(id)
}
def direction: Parser[MovementDirection] = """(Up|Down|Left|Right)""".r ^^ {
case "Up" => Up
case "Down" => Down
case "Left" => Left
case "Right" => Right
}
def robotUse: Parser[Robot] = "R." ~ robotId ^^ {
case _ ~ rid => Robot(rid)
}
def command: Parser[Command] = robotUse ~ "GO" ~ direction ^^ {
case robot ~ "GO" ~ dir => Move(robot, dir)
}
trait Sentence
case class Declaration(newRobot: Robot) extends Sentence
case class Order(cmd: Command) extends Sentence
def sentence: Parser[Sentence] = (declare | command) ^^ {
case r: Robot => Declaration(r)
case cmd: Command => Order(cmd)
}
}
import Parser._
val parsedExample01 = parse(sentence, "NEW ROBOT(C17)")
val parsedExample02 = parse(sentence, "R.C17 GO Up")
println(parsedExample01)
println(parsedExample02)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment