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
}