--- a/progs/re2.scala Tue Oct 01 23:59:36 2013 +0100
+++ b/progs/re2.scala Wed Oct 02 00:10:52 2013 +0100
@@ -1,36 +1,13 @@
-abstract class Rexp {
- def simp : Rexp = this
-}
+abstract class Rexp
case object NULL extends Rexp
case object EMPTY extends Rexp
case class CHAR(c: Char) extends Rexp
-case class ALT(r1: Rexp, r2: Rexp) extends Rexp {
- override def simp = (r1.simp, r2.simp) match {
- case (NULL, r) => r
- case (r, NULL) => r
- case (r, EMPTY) => if (nullable(r)) r else ALT(r, EMPTY)
- case (EMPTY, r) => if (nullable(r)) r else ALT(r, EMPTY)
- case (r1, r2) => if (r1 == r2) r1 else ALT(r1, r2)
- }
-}
-case class SEQ(r1: Rexp, r2: Rexp) extends Rexp {
- override def simp = (r1.simp, r2.simp) match {
- case (NULL, _) => NULL
- case (_, NULL) => NULL
- case (EMPTY, r) => r
- case (r, EMPTY) => r
- case (r1, r2) => SEQ(r1, r2)
- }
-}
-case class STAR(r: Rexp) extends Rexp {
- override def simp = r.simp match {
- case NULL => EMPTY
- case EMPTY => EMPTY
- case r => STAR(r)
- }
-}
+case class ALT(r1: Rexp, r2: Rexp) extends Rexp
+case class SEQ(r1: Rexp, r2: Rexp) extends Rexp
+case class STAR(r: Rexp) extends Rexp
+case class NTIMES(r: Rexp, n: Int) extends Rexp
// some convenience for typing in regular expressions
def charlist2rexp(s : List[Char]) : Rexp = s match {
@@ -50,6 +27,7 @@
case ALT(r1, r2) => nullable(r1) || nullable(r2)
case SEQ(r1, r2) => nullable(r1) && nullable(r2)
case STAR(_) => true
+ case NTIMES(r, i) => if (i == 0) true else nullable(r)
}
// derivative of a regular expression w.r.t. a character
@@ -62,12 +40,14 @@
if (nullable(r1)) ALT(SEQ(der(c, r1), r2), der(c, r2))
else SEQ(der(c, r1), r2)
case STAR(r) => SEQ(der(c, r), STAR(r))
+ case NTIMES(r, i) =>
+ if (i == 0) NULL else SEQ(der(c, r), NTIMES(r, i - 1))
}
// derivative w.r.t. a string (iterates der)
def ders (s: List[Char], r: Rexp) : Rexp = s match {
case Nil => r
- case c::s => ders(s, der(c, r).simp)
+ case c::s => ders(s, der(c, r))
}
// main matcher function
@@ -77,14 +57,7 @@
//one or zero
def OPT(r: Rexp) = ALT(r, EMPTY)
-//n-times
-def NTIMES(r: Rexp, n: Int) : Rexp = n match {
- case 0 => EMPTY
- case 1 => r
- case n => SEQ(r, NTIMES(r, n - 1))
-}
-
-def RTEST(n: Int) = SEQ(NTIMES(OPT("a"), n), NTIMES("a", n))
+def EVIL(n: Int) = SEQ(NTIMES(OPT("a"), n), NTIMES("a", n))
def time_needed[T](i: Int, code: => T) = {
val start = System.nanoTime()
@@ -94,7 +67,12 @@
}
for (i <- 1 to 100) {
- println(i + ": " + "%.5f".format(time_needed(1, matcher(RTEST(i), "a" * i))))
+ println(i + ": " + "%.5f".format(time_needed(1, matcher(EVIL(i), "a" * i))))
}
+for (i <- 1 to 1000 by 50) {
+ println(i + " " + "%.5f".format(time_needed(1, matcher(EVIL(i), "a" * i))))
+}
+
+