--- a/progs/parser-combinators/comb1.sc Fri Oct 25 18:54:08 2024 +0100
+++ b/progs/parser-combinators/comb1.sc Sat Nov 09 06:23:35 2024 +0000
@@ -60,10 +60,19 @@
if (in != "" && in.head == c) Set((c, in.tail)) else Set()
}
+
+
val ap = CharParser('a')
val bp = CharParser('b')
+print(ap.parse("aade"))
+
val abp = SeqParser(ap, bp)
+print(abp.parse("abade"))
+
+val abp = AltParser(ap, bp)
+print(abp.parse("abc"))
+
MapParser(abp, ab => s"$ab").parse("abc")
// an atomic parser for parsing strings according to a regex
@@ -78,6 +87,8 @@
// atomic parsers for numbers and "verbatim" strings
val NumParser = RegexParser("[0-9]+".r)
+NumParser.parse("123abc345")
+
def StrParser(s: String) = RegexParser(Regex.quote(s).r)
NumParser.parse("123a123bc")
@@ -95,6 +106,8 @@
//
// p"<_some_string_>"
+
+
extension (sc: StringContext)
def p(args: Any*) = StrParser(sc.s(args*))
@@ -124,7 +137,7 @@
val NumParserInt2 = NumParser.map(_.toInt)
-val x = 1 + 3
+
// A parser for palindromes (just returns them as string)
// since the parser is recursive it needs to be lazy
@@ -135,7 +148,7 @@
}
// examples
-Pal.parse_all("abacaba")
+Pal.parse("abaaba")
Pal.parse("abacaaba")
println("Palindrome: " + Pal.parse_all("abaaaba"))
@@ -157,6 +170,7 @@
// A parser for arithmetic expressions (Terms and Factors)
+
lazy val E: Parser[String, Int] = {
(T ~ p"+" ~ E).map{ case ((x, _), z) => x + z } ||
(T ~ p"-" ~ E).map{ case ((x, _), z) => x - z } || T }
@@ -178,8 +192,8 @@
// with parser combinators (and many other parsing algorithms)
-// no left-recursion is allowed, otherwise the will loop;
-// newer versions of Scala (3.5) will actually give a warning
+// no left-recursion is allowed, otherwise they will loop;
+// newer versions of Scala (3.5+) will actually give a warning
// about this
/*