|
1 |
|
2 abstract class Rexp { |
|
3 def simp : Rexp = this |
|
4 } |
|
5 |
|
6 case object NULL extends Rexp |
|
7 case object EMPTY extends Rexp |
|
8 case class CHAR(c: Char) extends Rexp |
|
9 case class ALT(r1: Rexp, r2: Rexp) extends Rexp |
|
10 case class SEQ(r1: Rexp, r2: Rexp) extends Rexp |
|
11 case class STAR(r: Rexp) extends Rexp |
|
12 |
|
13 // some convenience for typing in regular expressions |
|
14 def charlist2rexp(s : List[Char]) : Rexp = s match { |
|
15 case Nil => EMPTY |
|
16 case c::Nil => CHAR(c) |
|
17 case c::s => SEQ(CHAR(c), charlist2rexp(s)) |
|
18 } |
|
19 implicit def string2rexp(s : String) : Rexp = charlist2rexp(s.toList) |
|
20 |
|
21 |
|
22 // nullable function: tests whether the regular |
|
23 // expression can recognise the empty string |
|
24 def nullable (r: Rexp) : Boolean = r match { |
|
25 case NULL => false |
|
26 case EMPTY => true |
|
27 case CHAR(_) => false |
|
28 case ALT(r1, r2) => nullable(r1) || nullable(r2) |
|
29 case SEQ(r1, r2) => nullable(r1) && nullable(r2) |
|
30 case STAR(_) => true |
|
31 } |
|
32 |
|
33 // derivative of a regular expression w.r.t. a character |
|
34 def der (c: Char, r: Rexp) : Rexp = r match { |
|
35 case NULL => NULL |
|
36 case EMPTY => NULL |
|
37 case CHAR(d) => if (c == d) EMPTY else NULL |
|
38 case ALT(r1, r2) => ALT(der(c, r1), der(c, r2)) |
|
39 case SEQ(r1, r2) => |
|
40 if (nullable(r1)) ALT(SEQ(der(c, r1), r2), der(c, r2)) |
|
41 else SEQ(der(c, r1), r2) |
|
42 case STAR(r) => SEQ(der(c, r), STAR(r)) |
|
43 } |
|
44 |
|
45 // derivative w.r.t. a string (iterates der) |
|
46 def ders (s: List[Char], r: Rexp) : Rexp = s match { |
|
47 case Nil => r |
|
48 case c::s => ders(s, der(c, r).simp) |
|
49 } |
|
50 |
|
51 // main matcher function |
|
52 def matcher(r: Rexp, s: String) : Boolean = nullable(ders(s.toList, r)) |
|
53 |
|
54 |
|
55 //one or zero |
|
56 def OPT(r: Rexp) = ALT(r, EMPTY) |
|
57 |
|
58 //n-times |
|
59 def NTIMES(r: Rexp, n: Int) : Rexp = n match { |
|
60 case 0 => NULL |
|
61 case 1 => r |
|
62 case n => SEQ(r, NTIMES(r, n - 1)) |
|
63 } |
|
64 |
|
65 def RTEST(n: Int) = SEQ(NTIMES(OPT("a"), n), NTIMES("a", n)) |
|
66 |
|
67 def time_needed[T](i: Int, code: => T) = { |
|
68 val start = System.nanoTime() |
|
69 for (j <- 1 to i) code |
|
70 val end = System.nanoTime() |
|
71 (end - start)/(i * 1.0e9) |
|
72 } |
|
73 |
|
74 for (i <- 1 to 22) { |
|
75 println(i + ": " + "%.5f".format(time_needed(1, matcher(RTEST(i), "a" * i)))) |
|
76 } |
|
77 |
|
78 |