--- a/progs/comb2.scala Sun Jul 28 01:00:41 2019 +0100
+++ b/progs/comb2.scala Sun Jul 28 14:24:46 2019 +0100
@@ -1,28 +1,28 @@
-// A parser and evaluator for the while language
+// A parser and interpreter for the While language
//
import scala.language.implicitConversions
import scala.language.reflectiveCalls
-abstract class Parser[I <% Seq[_], T] {
+abstract class Parser[I, T](implicit ev: I => Seq[_]) {
def parse(ts: I): Set[(T, I)]
def parse_all(ts: I) : Set[T] =
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, T, S](p: => Parser[I, T], q: => Parser[I, S])(implicit ev: I => Seq[_]) 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, T](p: => Parser[I, T], q: => Parser[I, T])(implicit ev: I => Seq[_]) 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, T, S](p: => Parser[I, T], f: T => S)(implicit ev: I => Seq[_]) extends Parser[I, S] {
def parse(sb: I) =
for ((head, tail) <- p.parse(sb)) yield (f(head), tail)
}
@@ -48,7 +48,7 @@
implicit def string2parser(s : String) = StringParser(s)
-implicit def ParserOps[I<% Seq[_], T](p: Parser[I, T]) = new {
+implicit def ParserOps[I, T](p: Parser[I, T])(implicit ev: I => Seq[_]) = new {
def || (q : => Parser[I, T]) = new AltParser[I, T](p, q)
def ==>[S] (f: => T => S) = new FunParser[I, T, S](p, f)
def ~[S] (q : => Parser[I, S]) = new SeqParser[I, T, S](p, q)
@@ -141,7 +141,7 @@
// an interpreter for the WHILE language
type Env = Map[String, Int]
-def eval_aexp(a: AExp, env : Env) : Int = a match {
+def eval_aexp(a: AExp, env: Env) : Int = a match {
case Num(i) => i
case Var(s) => env(s)
case Aop("+", a1, a2) => eval_aexp(a1, env) + eval_aexp(a2, env)
@@ -174,4 +174,6 @@
def eval(bl: Block) : Env = eval_bl(bl, Map())
+// parse + evaluate fib program; then lookup what is
+// stored under the variable result
println(eval(Block.parse_all(fib).head)("result"))