--- a/progs/comb1.scala Fri Nov 06 08:52:16 2015 +0000
+++ b/progs/comb1.scala Sat Nov 07 21:37:03 2015 +0000
@@ -44,11 +44,13 @@
}
}
-case object NumParser extends Parser[String, String] {
+case object NumParser extends Parser[String, Int] {
val reg = "[0-9]+".r
def parse(sb: String) = reg.findPrefixOf(sb) match {
case None => Set()
- case Some(s) => Set(sb.splitAt(s.length))
+ case Some(s) => Set(sb.splitAt(s.length) match {
+ case (x, y) => (x.toInt, y)
+ })
}
}
@@ -88,16 +90,16 @@
P.parse_all("()")
// arithmetic expressions
-lazy val E: Parser[String, String] =
- (F ~ "*" ~ T) ==> { case ((x, y), z) => x + y + z } || F
-lazy val F: Parser[String, String] =
- ((T ~ "+" ~ T) ==> { case ((x, y), z) => x + y + z } ||
- (T ~ "-" ~ T) ==> { case ((x, y), z) => x + y + z } || T)
-lazy val T: Parser[String, String] =
- ("(" ~ E ~ ")") ==> { case ((x, y), z) => x + y + z } || NumParser
+lazy val E: Parser[String, Int] =
+ (F ~ "*" ~ F) ==> { case ((x, y), z) => x * z } || F
+lazy val F: Parser[String, Int] =
+ ((T ~ "+" ~ T) ==> { case ((x, y), z) => x + z } ||
+ (T ~ "-" ~ T) ==> { case ((x, y), z) => x - z } || T)
+lazy val T: Parser[String, Int] =
+ ("(" ~ E ~ ")") ==> { case ((x, y), z) => y } || NumParser
-println(E.parse_all("1*2+3"))
-println(E.parse_all("1+2*3"))
+println(E.parse("1*2+3"))
+println(E.parse("1 + 2 * 3"))
println(E.parse_all("(1+2)+3"))
println(E.parse_all("1+2+3")) // this is not parsed, because of
// how the grammar is set up