--- a/progs/comb2.scala Sun Jul 28 21:10:39 2019 +0100
+++ b/progs/comb2.scala Tue Jul 30 20:19:40 2019 +0100
@@ -110,7 +110,7 @@
// boolean expressions with some simple nesting
lazy val BExp: Parser[String, BExp] =
- (AExp ~ "==" ~ AExp) ==> { case ((x, y), z) => Bop("==", x, z) }: Bexp ||
+ (AExp ~ "==" ~ AExp) ==> { case ((x, y), z) => Bop("==", x, z): BExp } ||
(AExp ~ "!=" ~ AExp) ==> { case ((x, y), z) => Bop("!=", x, z): BExp } ||
(AExp ~ "<" ~ AExp) ==> { case ((x, y), z) => Bop("<", x, z): BExp } ||
(AExp ~ ">" ~ AExp) ==> { case ((x, y), z) => Bop(">", x, z): BExp } ||
@@ -120,7 +120,7 @@
("false" ==> ((_) => False: BExp )) ||
("(" ~ BExp ~ ")") ==> { case ((x, y), z) => y}
-// statements
+// statement / statements
lazy val Stmt: Parser[String, Stmt] =
(("skip" ==> ((_) => Skip: Stmt)) ||
(IdParser ~ ":=" ~ AExp) ==> { case ((x, y), z) => Assign(x, z): Stmt } ||
@@ -133,6 +133,7 @@
(Stmt ~ ";" ~ Stmts) ==> { case ((x, y), z) => x :: z : Block } ||
(Stmt ==> ((s) => List(s) : Block))
+// blocks (enclosed in curly braces)
lazy val Block: Parser[String, Block] =
(("{" ~ Stmts ~ "}") ==> { case ((x, y), z) => y} ||
(Stmt ==> ((s) => List(s))))
@@ -142,19 +143,20 @@
Block.parse_all("{x:=5;y:=8}")
Block.parse_all("if(false)then{x:=5}else{x:=10}")
-val fib = """{n := 10;
- minus1 := 0;
- minus2 := 1;
- temp := 0;
- while (n > 0) do {
+val fib = """n := 10;
+ minus1 := 0;
+ minus2 := 1;
+ temp := 0;
+ while (n > 0) do {
temp := minus2;
minus2 := minus1 + minus2;
minus1 := temp;
n := n - 1
- };
- result := minus2}""".replaceAll("\\s+", "")
+ };
+ result := minus2""".replaceAll("\\s+", "")
-Block.parse_all(fib)
+Stmts.parse_all(fib)
+
// an interpreter for the WHILE language
type Env = Map[String, Int]
@@ -198,7 +200,7 @@
// parse + evaluate fib program; then lookup what is
// stored under the variable result
-println(eval(Block.parse_all(fib).head)("result"))
+println(eval(Stmts.parse_all(fib).head)("result"))
// more examles
@@ -208,20 +210,20 @@
println("Factors")
val factors =
- """{n := 12;
+ """n := 12;
f := 2;
while (f < n / 2 + 1) do {
if ((n / f) * f == n) then { write(f) } else { skip };
f := f + 1
- }}""".replaceAll("\\s+", "")
+ }""".replaceAll("\\s+", "")
-eval(Block.parse_all(factors).head)
+eval(Stmts.parse_all(factors).head)
// calculate all prime numbers up to a number
println("Primes")
val primes =
- """{end := 100;
+ """end := 100;
n := 2;
while (n < end) do {
f := 2;
@@ -232,6 +234,6 @@
};
if (tmp == 0) then { write(n) } else { skip };
n := n + 1
- }}""".replaceAll("\\s+", "")
+ }""".replaceAll("\\s+", "")
-eval(Block.parse_all(primes).head)
+eval(Stmts.parse_all(primes).head)