--- a/progs/comb1.scala Sun Oct 27 11:46:06 2019 +0000
+++ b/progs/comb1.scala Sun Oct 27 11:57:57 2019 +0000
@@ -50,7 +50,7 @@
val NumParser = RegexParser("[0-9]+".r)
def StringParser(s: String) = RegexParser(Regex.quote(s).r)
-// NumParserInt2 transforms a "string integer" into an Int;
+// NumParserInt2 transforms a "string integer" into an actual Int;
// needs new, because FunParser is not a case class
val NumParserInt2 = new FunParser(NumParser, (s: String) => s.toInt)
@@ -75,10 +75,13 @@
new SeqParser[String, String, String](s, r)
}
-// NumParserInt can now be written as
+// NumParserInt can now be written as _ ===> _
+// the first part is the parser, and the second the
+// semantic action
val NumParserInt = NumParser ==> (s => s.toInt)
+// palindromes
lazy val Pal : Parser[String, String] =
(("a" ~ Pal ~ "a") ==> { case ((x, y), z) => x + y + z } ||
("b" ~ Pal ~ "b") ==> { case ((x, y), z) => x + y + z } || "a" || "b" || "")
@@ -89,7 +92,7 @@
println("Palindrome: " + Pal.parse_all("abaaaba"))
-// well-nested parentheses parser (transforms '(' -> '{' , ')' -> '}' )
+// parser for well-nested parentheses (transforms '(' -> '{' , ')' -> '}' )
lazy val P : Parser[String, String] =
"(" ~ P ~ ")" ~ P ==> { case (((_, x), _), y) => "{" + x + "}" + y } || ""
@@ -98,6 +101,7 @@
P.parse_all(")(")
P.parse_all("()")
+// just counts parentheses
lazy val PC : Parser[String, Int] =
("(" ~ PC ~ ")" ~ PC ==> { case (((_, x), _), y) => x + y + 2 } ||
"" ==> { (s) => 0 })
@@ -106,6 +110,8 @@
P.parse_all("(((()()))()))")
// Arithmetic Expressions (Terms and Factors)
+// (because it is mutually recursive, you need :paste
+// for munching this definition in the REPL)
lazy val E: Parser[String, Int] =
(T ~ "+" ~ E) ==> { case ((x, y), z) => x + z } ||
@@ -193,12 +199,12 @@
-
-// a problem with the parser -> gets slow with nestedness
+// a problem with the arithmetic expression parser -> gets
+// slow with deep nestedness
E.parse("1")
E.parse("(1)")
E.parse("((1))")
E.parse("(((1)))")
E.parse("((((1))))")
E.parse("((((((1))))))")
-E.parse("(((((((1)))))))")
\ No newline at end of file
+E.parse("(((((((1)))))))")