Fahad/Eclipse/ScalaProjects/bin/POSIX/PosixAlgo.sc
author Chengsong
Wed, 23 Aug 2023 03:02:31 +0100
changeset 668 3831621d7b14
parent 40 e5afb97b54f6
permissions -rw-r--r--
added technical Overview section, almost done introduction

package POSIX

object PosixAlgo {

  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
  case class RECD(x: String, r: Rexp) extends Rexp

	abstract class Val
  case object Void extends Val
  case class Chr(c: Char) extends Val
  case class Sequ(v1: Val, v2: Val) extends Val
  case class Left(v: Val) extends Val
  case class Right(v: Val) extends Val
  case class Stars(vs: List[Val]) extends Val
  case class Rec(x: String, v: Val) extends Val

	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
    case RECD(_, r1) => nullable(r1)
  }                                               //> nullable: (r: POSIX.PosixAlgo.Rexp)Boolean
  
  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))
    case RECD(_, r1) => der(c, r1)
  }                                               //> der: (c: Char, r: POSIX.PosixAlgo.Rexp)POSIX.PosixAlgo.Rexp
}