diff -r 9c7eb266594c -r 57ea439feaff progs/comb1.scala --- a/progs/comb1.scala Fri Oct 23 08:35:17 2015 +0100 +++ b/progs/comb1.scala Fri Oct 23 14:45:57 2015 +0100 @@ -1,6 +1,10 @@ import scala.language.implicitConversions import scala.language.reflectiveCalls +/* Note, in the lectures I did not show the type consraint + * I <% Seq[_] , which means that the input type I can be + * treated, or seen, as a sequence. */ + abstract class Parser[I <% Seq[_], T] { def parse(ts: I): Set[(T, I)] @@ -67,20 +71,21 @@ new SeqParser[String, String, String](s, r) } -// palindromes +// a parse 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")) -// well-nested parenthesis +// well-nested parenthesis parser lazy val P : Parser[String, String] = "(" ~ P ~ ")" ~ P ==> { case (((u, x), y), z) => "{" + x + "}" + z } || "" P.parse_all("(((()()))())") P.parse_all("(((()()))()))") P.parse_all(")(") +P.parse_all("()") // arithmetic expressions lazy val E: Parser[String, String] = @@ -93,10 +98,11 @@ println(E.parse_all("1*2+3")) println(E.parse_all("1+2*3")) -println(E.parse_all("1+2+3")) +println(E.parse_all("(1+2)+3")) +println(E.parse_all("1+2+3")) // this is not parsed, because of + // how the grammar is set up - -// non-ambiguous vs ambiguous +// non-ambiguous vs ambiguous grammars lazy val U : Parser[String, String] = ("1" ~ U) ==> { case (x, y) => x + y } || "" @@ -106,3 +112,32 @@ ("1" ~ S ~ S) ==> { case ((x, y), z) => x + y + z } || "" S.parse_all("1" * 15) + + + + + + + + + + + + + + + + + + + + + + + + + + + + +