--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/progs/parser3.scala Sat Jun 15 09:23:18 2013 -0400
@@ -0,0 +1,41 @@
+package object parser {
+
+// parser combinators
+// with input type I and return type T
+//
+// needs to be compiled with scalac parser3.scala
+
+abstract class Parser[I <% Seq[_], T] {
+ def parse(ts: I): Set[(T, I)]
+
+ def parse_all(ts: I) : Set[T] =
+ for ((head, tail) <- parse(ts); if (tail.isEmpty)) yield head
+
+ def parse_single(ts: I) : T = parse_all(ts).toList match {
+ case t::Nil => t
+ case _ => { println ("Parse Error") ; sys.exit(-1) }
+ }
+
+ def || (right : => Parser[I, T]) : Parser[I, T] = new AltParser(this, right)
+ def ==>[S] (f: => T => S) : Parser [I, S] = new FunParser(this, f)
+ def ~[S] (right : => Parser[I, S]) : Parser[I, (T, S)] = new SeqParser(this, right)
+ def ~>[S] (right : => Parser[I, S]) : Parser[I, S] = this ~ right ==> (_._2)
+ def <~[S] (right : => Parser[I, S]) : Parser[I, T] = this ~ right ==> (_._1)
+}
+
+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] {
+ 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] {
+ def parse(sb: I) =
+ for ((head, tail) <- p.parse(sb)) yield (f(head), tail)
+}
+
+}