--- a/progs/re2.scala Mon Sep 22 13:42:14 2014 +0100
+++ b/progs/re2.scala Fri Sep 26 14:06:55 2014 +0100
@@ -1,26 +1,12 @@
-import scala.language.implicitConversions
-
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
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
+case class NTIMES(r: Rexp, n: Int) extends Rexp //explicit constructor
-// some convenience for typing in regular expressions
-def charlist2rexp(s : List[Char]) : Rexp = s match {
- case Nil => EMPTY
- case c::Nil => CHAR(c)
- case c::s => SEQ(CHAR(c), charlist2rexp(s))
-}
-implicit def string2rexp(s : String) : Rexp = charlist2rexp(s.toList)
-
-
-// nullable function: tests whether the regular
-// expression can recognise the empty string
def nullable (r: Rexp) : Boolean = r match {
case NULL => false
case EMPTY => true
@@ -31,7 +17,6 @@
case NTIMES(r, i) => if (i == 0) true else nullable(r)
}
-// derivative of a regular expression w.r.t. a character
def der (c: Char, r: Rexp) : Rexp = r match {
case NULL => NULL
case EMPTY => NULL
@@ -45,20 +30,18 @@
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))
}
-// main matcher function
def matcher(r: Rexp, s: String) : Boolean = nullable(ders(s.toList, r))
-//one or zero
+//optional: one or zero times
def OPT(r: Rexp) = ALT(r, EMPTY)
-def EVIL(n: Int) = SEQ(NTIMES(OPT("a"), n), NTIMES("a", n))
+def EVIL(n: Int) = SEQ(NTIMES(OPT(CHAR('a')), n), NTIMES(CHAR('a'), n))
def time_needed[T](i: Int, code: => T) = {
val start = System.nanoTime()
@@ -71,7 +54,7 @@
println(i + ": " + "%.5f".format(time_needed(1, matcher(EVIL(i), "a" * i))))
}
-
+//a bit bolder test
for (i <- 1 to 1000 by 50) {
println(i + " " + "%.5f".format(time_needed(1, matcher(EVIL(i), "a" * i))))
}