solutions/cw5/fun_parser.sc
changeset 920 7af2eea19646
parent 903 2f86ebda3629
--- a/solutions/cw5/fun_parser.sc	Sun Sep 17 19:12:57 2023 +0100
+++ b/solutions/cw5/fun_parser.sc	Tue Sep 19 09:54:41 2023 +0100
@@ -15,46 +15,44 @@
 // case x ~ y ~ z => ...
 case class ~[+A, +B](x: A, y: B)
 
-// constraint for the input
-type IsSeq[A] = A => Seq[_]
-
-abstract class Parser[I : IsSeq, T]{
-  def parse(in: I): Set[(T, I)]
+// parser combinators
+abstract class Parser[I, T](using is: I => Seq[_])  {
+  def parse(in: I): Set[(T, I)]  
 
   def parse_all(in: I) : Set[T] =
-    for ((hd, tl) <- parse(in);
-        if tl.isEmpty) yield hd
+    for ((hd, tl) <- parse(in); 
+        if is(tl).isEmpty) yield hd
 }
 
-// parser combinators
+// alternative parser
+class AltParser[I, T](p: => Parser[I, T], 
+                      q: => Parser[I, T])(using I => Seq[_]) extends Parser[I, T] {
+  def parse(in: I) = p.parse(in) ++ q.parse(in)   
+}
 
 // sequence parser
-class SeqParser[I : IsSeq, T, S](p: => Parser[I, T],
-                                 q: => Parser[I, S]) extends Parser[I, ~[T, S]] {
-  def parse(in: I) =
-    for ((hd1, tl1) <- p.parse(in);
+class SeqParser[I, T, S](p: => Parser[I, T], 
+                         q: => Parser[I, S])(using I => Seq[_]) extends Parser[I, ~[T, S]] {
+  def parse(in: I) = 
+    for ((hd1, tl1) <- p.parse(in); 
          (hd2, tl2) <- q.parse(tl1)) yield (new ~(hd1, hd2), tl2)
 }
 
-// alternative parser
-class AltParser[I : IsSeq, T](p: => Parser[I, T],
-                              q: => Parser[I, T]) extends Parser[I, T] {
-  def parse(in: I) = p.parse(in) ++ q.parse(in)
-}
-
 // map parser
-class MapParser[I : IsSeq, T, S](p: => Parser[I, T],
-                                 f: T => S) extends Parser[I, S] {
+class MapParser[I, T, S](p: => Parser[I, T], 
+                         f: T => S)(using I => Seq[_]) extends Parser[I, S] {
   def parse(in: I) = for ((hd, tl) <- p.parse(in)) yield (f(hd), tl)
 }
 
+
 // more convenient syntax for parser combinators
-implicit def ParserOps[I : IsSeq, T](p: Parser[I, T]) = new {
+extension [I, T](p: Parser[I, T])(using I => Seq[_]) {
   def ||(q : => Parser[I, T]) = new AltParser[I, T](p, q)
   def ~[S] (q : => Parser[I, S]) = new SeqParser[I, T, S](p, q)
   def map[S](f: => T => S) = new MapParser[I, T, S](p, f)
 }
 
+
 // -------------------------------------------------
 // atomic parsers
 
@@ -146,8 +144,8 @@
   }
 }
 
-implicit def parser_interpolation(sc: StringContext) = new {
-  def p(args: Any*) = StrParser(sc.s(args:_*))
+extension (sc: StringContext) {
+   def p(args: Any*) = StrParser(sc.s(args:_*))
 }