Calculator parser and NameParser2

u.go
2015-09-10T00:13:04Z

NameParser2.scala

| 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)
| }
|
| }