progs/scala/re-basic.scala
changeset 238 2dc1647eab9e
parent 178 2835d13be702
child 293 1a4e5b94293b
equal deleted inserted replaced
237:3cbd19ecdc9d 238:2dc1647eab9e
     2 
     2 
     3 import scala.language.implicitConversions    
     3 import scala.language.implicitConversions    
     4 import scala.language.reflectiveCalls
     4 import scala.language.reflectiveCalls
     5 import scala.annotation.tailrec   
     5 import scala.annotation.tailrec   
     6 import scala.io.Source
     6 import scala.io.Source
       
     7 import scala.util._
     7 
     8 
     8 abstract class Rexp 
     9 abstract class Rexp 
     9 case object ZERO extends Rexp
    10 case object ZERO extends Rexp
    10 case object ONE extends Rexp
    11 case object ONE extends Rexp
    11 case class CHAR(c: Char) extends Rexp
    12 case class CHAR(c: Char) extends Rexp
   139 def lex(r: Rexp, s: List[Char]) : Val = s match {
   140 def lex(r: Rexp, s: List[Char]) : Val = s match {
   140   case Nil => if (nullable(r)) mkeps(r) else throw new Exception("Not matched")
   141   case Nil => if (nullable(r)) mkeps(r) else throw new Exception("Not matched")
   141   case c::cs => inj(r, c, lex(der(c, r), cs))
   142   case c::cs => inj(r, c, lex(der(c, r), cs))
   142 }
   143 }
   143 
   144 
   144 def lexing(r: Rexp, s: String) : Val = lex(r, s.toList)
   145 def lexing(r: Rexp, s: String) : Try[Val] = Try(lex(r, s.toList))
   145 
   146 
   146 // Examples
   147 // Examples
   147 
   148 
   148 val K: Rexp = "a" | "b"
   149 val K: Rexp = "a" | "b"
   149 val I: Rexp = "ab" | "ba"  
   150 val I: Rexp = "ab" | "ba"