author | Christian Urban <urbanc@in.tum.de> |
Tue, 11 Apr 2017 06:22:46 +0800 | |
changeset 483 | 6f508bcdaa30 |
parent 482 | 0f6e3c5a1751 |
child 485 | bd6d999ab7b6 |
permissions | -rw-r--r-- |
482 | 1 |
// NFAs in Scala based on sets of partial functions |
144
0cb61bed557d
added
Christian Urban <christian dot urban at kcl dot ac dot uk>
parents:
diff
changeset
|
2 |
|
482 | 3 |
// type abbreviation for partial functions |
4 |
type :=>[A, B] = PartialFunction[A, B] |
|
144
0cb61bed557d
added
Christian Urban <christian dot urban at kcl dot ac dot uk>
parents:
diff
changeset
|
5 |
|
482 | 6 |
case class NFA[A, C](starts: Set[A], // starting states |
7 |
delta: Set[(A, C) :=> A], // transitions |
|
8 |
fins: A => Boolean) { // final states |
|
144
0cb61bed557d
added
Christian Urban <christian dot urban at kcl dot ac dot uk>
parents:
diff
changeset
|
9 |
|
482 | 10 |
// given a state and a character, what is the set of next states? |
11 |
// if there is none => empty set |
|
12 |
def next(q: A, c: C) : Set[A] = |
|
483 | 13 |
delta.flatMap(d => Try(d(q, c)).toOption) |
144
0cb61bed557d
added
Christian Urban <christian dot urban at kcl dot ac dot uk>
parents:
diff
changeset
|
14 |
|
482 | 15 |
def nexts(qs: Set[A], c: C) : Set[A] = |
16 |
qs.flatMap(next(_, c)) |
|
144
0cb61bed557d
added
Christian Urban <christian dot urban at kcl dot ac dot uk>
parents:
diff
changeset
|
17 |
|
482 | 18 |
def deltas(qs: Set[A], s: List[C]) : Set[A] = s match { |
19 |
case Nil => qs |
|
20 |
case c::cs => deltas(nexts(qs, c), cs) |
|
144
0cb61bed557d
added
Christian Urban <christian dot urban at kcl dot ac dot uk>
parents:
diff
changeset
|
21 |
} |
0cb61bed557d
added
Christian Urban <christian dot urban at kcl dot ac dot uk>
parents:
diff
changeset
|
22 |
|
482 | 23 |
def accepts(s: List[C]) : Boolean = |
24 |
deltas(starts, s).exists(fins) |
|
144
0cb61bed557d
added
Christian Urban <christian dot urban at kcl dot ac dot uk>
parents:
diff
changeset
|
25 |
} |
0cb61bed557d
added
Christian Urban <christian dot urban at kcl dot ac dot uk>
parents:
diff
changeset
|
26 |