regexp.scala
changeset 29 774007c4b1b3
parent 18 d48cfc286cb1
equal deleted inserted replaced
28:f63ba92a7d78 29:774007c4b1b3
     7 case class ALT(r1: Rexp, r2: Rexp) extends Rexp
     7 case class ALT(r1: Rexp, r2: Rexp) extends Rexp
     8 case class SEQ(r1: Rexp, r2: Rexp) extends Rexp
     8 case class SEQ(r1: Rexp, r2: Rexp) extends Rexp
     9 case class STAR(r: Rexp) extends Rexp
     9 case class STAR(r: Rexp) extends Rexp
    10 
    10 
    11 // some convenience for typing in regular expressions
    11 // some convenience for typing in regular expressions
    12 implicit def string2rexp(s : String) : Rexp = {
    12 def charlist2rexp(s : List[Char]) : Rexp = s match {
    13   s.foldRight (EMPTY: Rexp) ( (c, r) => SEQ(CHAR(c), r) )
    13   case Nil => EMPTY
       
    14   case c::Nil => CHAR(c)
       
    15   case c::s => SEQ(CHAR(c), charlist2rexp(s))
    14 }
    16 }
       
    17 implicit def string2rexp(s : String) : Rexp = charlist2rexp(s.toList)
       
    18 
    15 
    19 
    16 // for example
    20 // for example
    17 println(STAR("abc"))
    21 println(STAR("abc"))
    18 
    22 
    19 // produces STAR(SEQ(CHAR(a),SEQ(CHAR(b),SEQ(CHAR(c),EMPTY))))
    23 // produces STAR(SEQ(CHAR(a),SEQ(CHAR(b),SEQ(CHAR(c),EMPTY))))
    97 println(matcher("cab","cab"))
   101 println(matcher("cab","cab"))
    98 println(matcher(STAR("a"),"aaa"))
   102 println(matcher(STAR("a"),"aaa"))
    99 println(matcher("cab" ,"cab"))
   103 println(matcher("cab" ,"cab"))
   100 println(matcher(STAR("a"),"aaa"))
   104 println(matcher(STAR("a"),"aaa"))
   101 
   105 
       
   106