progs/nfa.scala
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--
updated

// NFAs in Scala based on sets of partial functions

// type abbreviation for partial functions
type :=>[A, B] = PartialFunction[A, B]

case class NFA[A, C](starts: Set[A],            // starting states
                     delta: Set[(A, C) :=> A],  // transitions
                     fins:  A => Boolean) {     // final states 

  // given a state and a character, what is the set of next states?
  // if there is none => empty set
  def next(q: A, c: C) : Set[A] = 
    delta.flatMap(d => Try(d(q, c)).toOption)

  def nexts(qs: Set[A], c: C) : Set[A] =
    qs.flatMap(next(_, c))

  def deltas(qs: Set[A], s: List[C]) : Set[A] = s match {
    case Nil => qs
    case c::cs => deltas(nexts(qs, c), cs)
  }

  def accepts(s: List[C]) : Boolean = 
    deltas(starts, s).exists(fins)
}