progs/re1.scala
author Christian Urban <urbanc@in.tum.de>
Sat, 07 Jan 2017 14:52:26 +0000
changeset 471 9476086849ad
parent 469 1f4e81950ab4
child 477 b78664a24f5d
permissions -rw-r--r--
updated


abstract class Rexp
case object ZERO extends Rexp                    // matches nothing
case object ONE extends Rexp                     // matches the empty string
case class CHAR(c: Char) extends Rexp            // matches a character c
case class ALT(r1: Rexp, r2: Rexp) extends Rexp  // alternative
case class SEQ(r1: Rexp, r2: Rexp) extends Rexp  // sequence
case class STAR(r: Rexp) extends Rexp            // star

// nullable function: tests whether a regular 
// expression can recognise the empty string
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

}

// derivative of a regular expression w.r.t. a character
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(r1) => SEQ(der(c, r1), STAR(r1))
}

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

//examples 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, ONE)

//n-times (explicitly expanded)
def NTIMES(r: Rexp, n: Int) : Rexp = n match {
  case 0 => ONE
  case 1 => r
  case n => SEQ(r, NTIMES(r, n - 1))
}

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

// the evil regular expression (a*)*b
val EVIL2 = SEQ(STAR(STAR(CHAR('a'))), CHAR('b'))

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

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

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

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

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