progs/comb1.scala
changeset 360 c6c574d2ca0c
parent 185 ea8b94d4755e
child 362 57ea439feaff
--- a/progs/comb1.scala	Tue Oct 20 00:01:56 2015 +0100
+++ b/progs/comb1.scala	Fri Oct 23 00:16:00 2015 +0100
@@ -5,20 +5,24 @@
   def parse(ts: I): Set[(T, I)]
 
   def parse_all(ts: I) : Set[T] =
-    for ((head, tail) <- parse(ts); if (tail.isEmpty)) yield head
+    for ((head, tail) <- parse(ts); 
+        if (tail.isEmpty)) yield head
 }
 
-class SeqParser[I <% Seq[_], T, S](p: => Parser[I, T], q: => Parser[I, S]) extends Parser[I, (T, S)] {
+class SeqParser[I <% Seq[_], T, S](p: => Parser[I, T], 
+                                   q: => Parser[I, S]) extends Parser[I, (T, S)] {
   def parse(sb: I) = 
     for ((head1, tail1) <- p.parse(sb); 
          (head2, tail2) <- q.parse(tail1)) yield ((head1, head2), tail2)
 }
 
-class AltParser[I <% Seq[_], T](p: => Parser[I, T], q: => Parser[I, T]) extends Parser[I, T] {
+class AltParser[I <% Seq[_], T](p: => Parser[I, T], 
+                                q: => Parser[I, T]) extends Parser[I, T] {
   def parse(sb: I) = p.parse(sb) ++ q.parse(sb)   
 }
 
-class FunParser[I <% Seq[_], T, S](p: => Parser[I, T], f: T => S) extends Parser[I, S] {
+class FunParser[I <% Seq[_], T, S](p: => Parser[I, T], 
+                                   f: T => S) extends Parser[I, S] {
   def parse(sb: I) = 
     for ((head, tail) <- p.parse(sb)) yield (f(head), tail)
 }
@@ -44,7 +48,7 @@
   }
 }
 
-
+// convenience
 implicit def string2parser(s : String) = StringParser(s)
 
 implicit def ParserOps[I<% Seq[_], T](p: Parser[I, T]) = new {
@@ -63,16 +67,14 @@
     new SeqParser[String, String, String](s, r)
 }
 
-
-
-
+// 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 } || "")
 
-println("Palindrom" + Pal.parse_all("ababbaba"))
+println("Palindrom: " + Pal.parse_all("ababbaba"))
 
-
+// well-nested parenthesis
 lazy val P : Parser[String, String] = 
   "(" ~ P ~ ")" ~ P ==> { case (((u, x), y), z) => "{" + x + "}" + z } || ""
 
@@ -80,6 +82,7 @@
 P.parse_all("(((()()))()))")
 P.parse_all(")(")
 
+// arithmetic expressions
 lazy val E: Parser[String, String] = 
   (F ~ "*" ~ F) ==> { case ((x, y), z) => x + y + z } || F  
 lazy val F: Parser[String, String] =