diff -r 6512884e03b4 -r 155426396b5f progs/parser-combinators/comb2.sc --- a/progs/parser-combinators/comb2.sc Mon Jul 27 11:02:48 2020 +0100 +++ b/progs/parser-combinators/comb2.sc Thu Jul 30 13:50:54 2020 +0100 @@ -1,18 +1,28 @@ -// Parser Combinators: Simple Version +// Parser Combinators: +// Simple Version for WHILE-language //==================================== +// +// with some added convenience for +// map-parsers and grammar rules +// +// call with +// +// amm comb2.sc -// more convenience for the map parsers later on + + +// more convenience for the map parsers later on; +// it allows writing nested patterns as +// case x ~ y ~ z => ... + case class ~[+A, +B](_1: A, _2: B) -/* - Note, in the lectures I did not show the implicit type constraint - I : IsSeq, which means that the input type 'I' needs to be - a sequence. -*/ +// constraint for the input type IsSeq[A] = A => Seq[_] + abstract class Parser[I : IsSeq, T]{ def parse(in: I): Set[(T, I)] @@ -141,7 +151,7 @@ (p"false".map[BExp]{ _ => False }) || (p"(" ~ BExp ~ p")").map[BExp]{ case _ ~ x ~ _ => x } -// statement +// a single statement lazy val Stmt: Parser[String, Stmt] = ((p"skip".map[Stmt]{_ => Skip }) || (IdParser ~ p":=" ~ AExp).map[Stmt]{ case x ~ _ ~ z => Assign(x, z) } || @@ -223,7 +233,7 @@ def eval(bl: Block) : Env = eval_bl(bl, Map()) // parse + evaluate fib program; then lookup what is -// stored under the variable result +// stored under the variable "result" println(eval(Stmts.parse_all(fib).head)("result")) @@ -243,6 +253,7 @@ println(eval(Stmts.parse_all(factors).head)) + // calculate all prime numbers up to a number println("Primes")