diff -r 7a777d9cc343 -r 6fe4facb56a6 parser.scala --- a/parser.scala Wed Oct 31 02:05:12 2012 +0000 +++ b/parser.scala Wed Oct 31 08:35:00 2012 +0000 @@ -86,7 +86,7 @@ case class T_OP(s: String) extends Token case object T_LPAREN extends Token case object T_RPAREN extends Token -case class T_NT(s: String) extends Token +case class NT(s: String) extends Token type Rule = (Rexp, List[Char] => Token) @@ -140,10 +140,10 @@ // grammar for arithmetic expressions val grammar = List ("E" -> List(T_NUM), - "E" -> List(T_NT("E"), T_OP("+"), T_NT("E")), - "E" -> List(T_NT("E"), T_OP("-"), T_NT("E")), - "E" -> List(T_NT("E"), T_OP("*"), T_NT("E")), - "E" -> List(T_LPAREN, T_NT("E"), T_RPAREN)) + "E" -> List(NT("E"), T_OP("+"), NT("E")), + "E" -> List(NT("E"), T_OP("-"), NT("E")), + "E" -> List(NT("E"), T_OP("*"), NT("E")), + "E" -> List(T_LPAREN, NT("E"), T_RPAREN)) def chop[A](ts1: List[A], prefix: List[A], ts2: List[A]) : Option[(List[A], List[A])] = @@ -164,19 +164,25 @@ case Some((before, after)) => Some(before ::: in ::: after) } -def parse1(g: Grammar, ts: List[Token]) : Boolean = { +def parse(g: Grammar, ts: List[Token]) : Boolean = { //println(ts) - if (ts == List(T_NT("E"))) true + if (ts == List(NT("E"))) true else { - val tss = for ((lhs, rhs) <- g) yield replace(ts, rhs, List(T_NT(lhs))) - tss.flatten.exists(parse1(g, _)) + val tss = for ((lhs, rhs) <- g) yield replace(ts, rhs, List(NT(lhs))) + tss.flatten.exists(parse(g, _)) } } +def parser(g: Grammar, rs: List[Rule], s: String) = { + println("\n") + parse(g, tokenizer(rs, s)) +} + -println() ; parse1(grammar, tokenizer(lexing_rules, "2 + 3 * 4 + 1")) -println() ; parse1(grammar, tokenizer(lexing_rules, "(2 + 3) * (4 + 1)")) -println() ; parse1(grammar, tokenizer(lexing_rules, "(2 + 3) * 4 (4 + 1)")) + +parser(grammar, lexing_rules, "2 + 3 * 4 + 1") +parser(grammar, lexing_rules, "(2 + 3) * (4 + 1)") +parser(grammar, lexing_rules, "(2 + 3) * 4 (4 + 1)")