Created
February 6, 2017 19:31
-
-
Save pfcoperez/aaa5eef551b28ce95bfdc96ed48430a9 to your computer and use it in GitHub Desktop.
Parsers combinators example: Robot commands
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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