diff -r cec95ad3a837 -r f6e937ed0332 progs/comb1.scala --- a/progs/comb1.scala Wed Nov 01 11:44:23 2017 +0000 +++ b/progs/comb1.scala Wed Nov 08 12:54:39 2017 +0000 @@ -77,9 +77,9 @@ // 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 } || "") + ("b" ~ Pal ~ "b") ==> { case ((x, y), z) => x + y + z } || "a" || "b" || "") -println("Palindrome: " + Pal.parse_all("ababbaba")) +println("Palindrome: " + Pal.parse_all("abaaaba")) // well-nested parenthesis parser lazy val P : Parser[String, String] = @@ -103,8 +103,17 @@ println(E.parse_all("4*2+3")) println(E.parse("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 +println(E.parse_all("1+2+3")) + +// no left-recursion allowed, otherwise will loop +lazy val EL: Parser[String, Int] = + ((EL ~ "+" ~ EL) ==> { case ((x, y), z) => x + z} || + (EL ~ "*" ~ EL) ==> { case ((x, y), z) => x * z} || + ("(" ~ EL ~ ")") ==> { case ((x, y), z) => y} || + NumParser) + +//println(E.parse_all("1+2+3")) + // a repetition parser @@ -124,15 +133,18 @@ lazy val S : Parser[String, String] = ("1" ~ S ~ S) ==> { case ((x, y), z) => x + y + z } || "" -S.parse_all("1" * 15) +S.parse("1" * 15) lazy val U : Parser[String, String] = ("1" ~ U) ==> { case (x, y) => x + y } || "" +U.parse("1" * 15) + U.parse("11") U.parse("11111") U.parse("11011") +U.parse_all("1" * 100) U.parse_all("1" * 100 + "0") lazy val UCount : Parser[String, Int] = @@ -168,6 +180,8 @@ yield (x.toString + y) + +// Example section for lazy evaluation def square(n: Int) = { n * n } @@ -179,19 +193,13 @@ 3 } +//would loop +square(bar()) +// lazy def foo(n: => Int) = { print("finished") } foo(bar()) -square(12) + square(10) - - -def time_needed[T](i: Int, code: => T) = { - val start = System.nanoTime() - for (j <- 1 to i) code - val end = System.nanoTime() - (end - start)/(i * 1.0e9) -}