42 val (prefix, suffix) = sb.splitAt(s.length) |
42 val (prefix, suffix) = sb.splitAt(s.length) |
43 if (prefix == s) Set((prefix, suffix)) else Set() |
43 if (prefix == s) Set((prefix, suffix)) else Set() |
44 } |
44 } |
45 } |
45 } |
46 |
46 |
47 case object NumParser extends Parser[String, String] { |
47 case object NumParser extends Parser[String, Int] { |
48 val reg = "[0-9]+".r |
48 val reg = "[0-9]+".r |
49 def parse(sb: String) = reg.findPrefixOf(sb) match { |
49 def parse(sb: String) = reg.findPrefixOf(sb) match { |
50 case None => Set() |
50 case None => Set() |
51 case Some(s) => Set(sb.splitAt(s.length)) |
51 case Some(s) => Set(sb.splitAt(s.length) match { |
|
52 case (x, y) => (x.toInt, y) |
|
53 }) |
52 } |
54 } |
53 } |
55 } |
54 |
56 |
55 // convenience |
57 // convenience |
56 implicit def string2parser(s : String) = StringParser(s) |
58 implicit def string2parser(s : String) = StringParser(s) |
86 P.parse_all("(((()()))()))") |
88 P.parse_all("(((()()))()))") |
87 P.parse_all(")(") |
89 P.parse_all(")(") |
88 P.parse_all("()") |
90 P.parse_all("()") |
89 |
91 |
90 // arithmetic expressions |
92 // arithmetic expressions |
91 lazy val E: Parser[String, String] = |
93 lazy val E: Parser[String, Int] = |
92 (F ~ "*" ~ T) ==> { case ((x, y), z) => x + y + z } || F |
94 (F ~ "*" ~ F) ==> { case ((x, y), z) => x * z } || F |
93 lazy val F: Parser[String, String] = |
95 lazy val F: Parser[String, Int] = |
94 ((T ~ "+" ~ T) ==> { case ((x, y), z) => x + y + z } || |
96 ((T ~ "+" ~ T) ==> { case ((x, y), z) => x + z } || |
95 (T ~ "-" ~ T) ==> { case ((x, y), z) => x + y + z } || T) |
97 (T ~ "-" ~ T) ==> { case ((x, y), z) => x - z } || T) |
96 lazy val T: Parser[String, String] = |
98 lazy val T: Parser[String, Int] = |
97 ("(" ~ E ~ ")") ==> { case ((x, y), z) => x + y + z } || NumParser |
99 ("(" ~ E ~ ")") ==> { case ((x, y), z) => y } || NumParser |
98 |
100 |
99 println(E.parse_all("1*2+3")) |
101 println(E.parse("1*2+3")) |
100 println(E.parse_all("1+2*3")) |
102 println(E.parse("1 + 2 * 3")) |
101 println(E.parse_all("(1+2)+3")) |
103 println(E.parse_all("(1+2)+3")) |
102 println(E.parse_all("1+2+3")) // this is not parsed, because of |
104 println(E.parse_all("1+2+3")) // this is not parsed, because of |
103 // how the grammar is set up |
105 // how the grammar is set up |
104 |
106 |
105 // non-ambiguous vs ambiguous grammars |
107 // non-ambiguous vs ambiguous grammars |