progs/re2.scala
author Christian Urban <christian dot urban at kcl dot ac dot uk>
Sun, 02 Oct 2016 15:07:21 +0100
changeset 434 8664ff87cd77
parent 424 1129024b26d5
child 440 e14cd32ad497
permissions -rw-r--r--
updated

// version with explicit n-times regular expression

abstract class Rexp 
case object ZERO extends Rexp
case object ONE 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 //explicit constructor

def nullable (r: Rexp) : Boolean = r match {
  case ZERO => false
  case ONE => true
  case CHAR(_) => false
  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)
}

def der (c: Char, r: Rexp) : Rexp = r match {
  case ZERO => ZERO
  case ONE => ZERO
  case CHAR(d) => if (c == d) ONE else ZERO
  case ALT(r1, r2) => ALT(der(c, r1), der(c, r2))
  case SEQ(r1, r2) => 
    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) ZERO else SEQ(der(c, r), NTIMES(r, i - 1))
}

def ders (s: List[Char], r: Rexp) : Rexp = s match {
  case Nil => r
  case c::s => ders(s, der(c, r))
}

def matches(r: Rexp, s: String) : Boolean = nullable(ders(s.toList, r))


//optional: one or zero times
def OPT(r: Rexp) = ALT(r, ONE)

//evil regular expressions
def EVIL1(n: Int) = SEQ(NTIMES(OPT(CHAR('a')), n), NTIMES(CHAR('a'), n))
val EVIL2 = SEQ(STAR(CHAR('a')), CHAR('b'))

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)
}


//test: (a?{n}) (a{n})
for (i <- 1 to 1101 by 100) {
  println(i + " " + "%.5f".format(time_needed(2, matches(EVIL1(i), "a" * i))))
}

for (i <- 1 to 1101 by 100) {
  println(i + " " + "%.5f".format(time_needed(2, matches(EVIL1(i), "a" * i))))
}

//test: (a*)* b
for (i <- 1 to 4501 by 500) {
  println(i + " " + "%.5f".format(time_needed(2, matches(EVIL2, "a" * i))))
}

for (i <- 1 to 4501 by 500) {
  println(i + " " + "%.5f".format(time_needed(2, matches(EVIL2, "a" * i))))
}