progs/re1.scala
author Christian Urban <christian dot urban at kcl dot ac dot uk>
Sun, 28 Sep 2014 18:07:58 +0100
changeset 261 24531cfaa36a
parent 258 1e4da6d2490c
child 343 539b2e88f5b9
permissions -rw-r--r--
updated handouts

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 

// 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
  case CHAR(_) => false
  case ALT(r1, r2) => nullable(r1) || nullable(r2)
  case SEQ(r1, r2) => nullable(r1) && nullable(r2)
  case STAR(_) => true
}

// 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
  case CHAR(d) => if (c == d) EMPTY else NULL
  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))
}

// 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 matches(r: Rexp, s: String) : Boolean = nullable(ders(s.toList, r))

//example from the homework
//val r = STAR(ALT(SEQ(CHAR('a'), CHAR('b')), CHAR('b')))
//der('a', r)
//der('b', r)
//der('c', r)

//optional: one or zero times
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))
}

// the evil regular expression  a?{n} a{n}
def EVIL(n: Int) = SEQ(NTIMES(OPT(CHAR('a')), n), NTIMES(CHAR('a'), n))

//for measuring time
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)
}

for (i <- 1 to 29) {
  println(i + ": " + "%.5f".format(time_needed(1, matches(EVIL(i), "a" * i))))
}