main_templates3/re.scala
changeset 418 fa7f7144f2bb
parent 400 e48ea8300b2d
child 424 daf561a83ba6
equal deleted inserted replaced
417:29fc780ca130 418:fa7f7144f2bb
    10 case class CHAR(c: Char) extends Rexp
    10 case class CHAR(c: Char) extends Rexp
    11 case class ALTs(rs: List[Rexp]) extends Rexp      // alternatives 
    11 case class ALTs(rs: List[Rexp]) extends Rexp      // alternatives 
    12 case class SEQ(r1: Rexp, r2: Rexp) extends Rexp   // sequence
    12 case class SEQ(r1: Rexp, r2: Rexp) extends Rexp   // sequence
    13 case class STAR(r: Rexp) extends Rexp             // star
    13 case class STAR(r: Rexp) extends Rexp             // star
    14 
    14 
       
    15 import scala.language.implicitConversions    
       
    16 import scala.language.reflectiveCalls 
       
    17 
       
    18 def charlist2rexp(s: List[Char]): Rexp = s match {
       
    19   case Nil => ONE
       
    20   case c::Nil => CHAR(c)
       
    21   case c::s => SEQ(CHAR(c), charlist2rexp(s))
       
    22 }
       
    23 implicit def string2rexp(s: String): Rexp = charlist2rexp(s.toList)
       
    24 
       
    25 
       
    26 // "a|b"
       
    27 ALT(CHAR('a'), CHAR('b'))
       
    28 
       
    29 val reg : Rexp = "a" | "b" // CHAR('a')
    15 
    30 
    16 // some convenience for typing regular expressions
    31 // some convenience for typing regular expressions
    17 
    32 
    18 //the usual binary choice can be defined in terms of ALTs
    33 //the usual binary choice can be defined in terms of ALTs
    19 def ALT(r1: Rexp, r2: Rexp) = ALTs(List(r1, r2))
    34 def ALT(r1: Rexp, r2: Rexp) = ALTs(List(r1, r2))
    26   case Nil => ONE
    41   case Nil => ONE
    27   case c::Nil => CHAR(c)
    42   case c::Nil => CHAR(c)
    28   case c::s => SEQ(CHAR(c), charlist2rexp(s))
    43   case c::s => SEQ(CHAR(c), charlist2rexp(s))
    29 }
    44 }
    30 implicit def string2rexp(s: String): Rexp = charlist2rexp(s.toList)
    45 implicit def string2rexp(s: String): Rexp = charlist2rexp(s.toList)
       
    46 
       
    47 
       
    48 
    31 
    49 
    32 implicit def RexpOps (r: Rexp) = new {
    50 implicit def RexpOps (r: Rexp) = new {
    33   def | (s: Rexp) = ALT(r, s)
    51   def | (s: Rexp) = ALT(r, s)
    34   def % = STAR(r)
    52   def % = STAR(r)
    35   def ~ (s: Rexp) = SEQ(r, s)
    53   def ~ (s: Rexp) = SEQ(r, s)