Skip to content

Instantly share code, notes, and snippets.

@maowug
Created September 10, 2015 00:13
Show Gist options
  • Save maowug/ca08b458a2d3af7ae394 to your computer and use it in GitHub Desktop.
Save maowug/ca08b458a2d3af7ae394 to your computer and use it in GitHub Desktop.
Calculator parser and NameParser2
object NameParser2 extends RegexParsers {
case class Name(first: String, last: String)
def name:Parser[String] = "[a-zA-Z]+".r
def fullName = rep(name) ^^ { names =>
Name(names.head, names(1))
}
def parse(input: String) = parseAll(fullName, input) match {
case Success(result, _) =>
result
case failure : NoSuccess => scala.sys.error(failure.msg)
}
}
val res2 = NameParser2.parse("Martin Martin Odersky")
/////
object Calculator extends RegexParsers {
def number: Parser[Double] = """\d+(\.\d*)?""".r ^^ { _.toDouble }
def factor: Parser[Double] = number | "(" ~> expr <~ ")"
def term : Parser[Double] = factor ~ rep( "*" ~ factor | "/" ~ factor) ^^ {
case number ~ list => (number /: list) {
case (x, "*" ~ y) => x * y
case (x, "/" ~ y) => x / y
}
}
def expr : Parser[Double] = term ~ rep("+" ~ log(term)("Plus term") | "-" ~ log(term)("Minus term")) ^^ {
case number ~ list => list.foldLeft(number) { // same as before, using alternate name for /:
case (x, "+" ~ y) => x + y
case (x, "-" ~ y) => x - y
}
}
def apply(input: String): Double = parseAll(expr, input) match {
case Success(result, _) => result
case failure : NoSuccess => scala.sys.error(failure.msg)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment