main_templates3/re.scala
changeset 474 8a61bcd51ec3
parent 425 6e990ae2c6a3
equal deleted inserted replaced
473:be818c5a67d4 474:8a61bcd51ec3
    15 //the usual binary choice and binary sequence can be defined 
    15 //the usual binary choice and binary sequence can be defined 
    16 //in terms of ALTs and SEQs
    16 //in terms of ALTs and SEQs
    17 def ALT(r1: Rexp, r2: Rexp) = ALTs(List(r1, r2))
    17 def ALT(r1: Rexp, r2: Rexp) = ALTs(List(r1, r2))
    18 def SEQ(r1: Rexp, r2: Rexp) = SEQs(List(r1, r2))
    18 def SEQ(r1: Rexp, r2: Rexp) = SEQs(List(r1, r2))
    19 
    19 
    20 
       
    21 // some convenience for typing regular expressions
    20 // some convenience for typing regular expressions
    22 import scala.language.implicitConversions    
       
    23 import scala.language.reflectiveCalls 
       
    24 
    21 
    25 def charlist2rexp(s: List[Char]): Rexp = s match {
    22 def charlist2rexp(s: List[Char]): Rexp = s match {
    26   case Nil => ONE
    23   case Nil => ONE
    27   case c::Nil => CHAR(c)
    24   case c::Nil => CHAR(c)
    28   case c::s => SEQ(CHAR(c), charlist2rexp(s))
    25   case c::s => SEQ(CHAR(c), charlist2rexp(s))
    29 }
    26 }
    30 implicit def string2rexp(s: String): Rexp = charlist2rexp(s.toList)
       
    31 
    27 
    32 implicit def RexpOps (r: Rexp) = new {
    28 import scala.language.implicitConversions
       
    29 
       
    30 given Conversion[String, Rexp] = (s => charlist2rexp(s.toList))
       
    31 
       
    32 extension (r: Rexp) {
    33   def | (s: Rexp) = ALT(r, s)
    33   def | (s: Rexp) = ALT(r, s)
    34   def % = STAR(r)
    34   def % = STAR(r)
    35   def ~ (s: Rexp) = SEQ(r, s)
    35   def ~ (s: Rexp) = SEQ(r, s)
    36 }
    36 }
    37 
    37 
    38 implicit def stringOps (s: String) = new {
    38 // some examples for the conversion and extension:
    39   def | (r: Rexp) = ALT(s, r)
       
    40   def | (r: String) = ALT(s, r)
       
    41   def % = STAR(s)
       
    42   def ~ (r: Rexp) = SEQ(s, r)
       
    43   def ~ (r: String) = SEQ(s, r)
       
    44 }
       
    45 
    39 
    46 // examples for the implicits:
       
    47 // ALT(CHAR('a'), CHAR('b'))
       
    48 // val areg : Rexp = "a" | "b"
    40 // val areg : Rexp = "a" | "b"
    49 
    41 //  => ALTs(List(CHAR('a'), CHAR('b')))
    50 // SEQ(CHAR('a'), CHAR('b')) 
    42 //
    51 // val sreg : Rexp = "a" ~ "b"
    43 // val sreg : Rexp = "a" ~ "b"
    52 
    44 //  => SEQs(List(CHAR('a'), CHAR('b'))) 
       
    45 //
       
    46 // val star_reg : Rexp = ("a" ~ "b").%
       
    47 //  => STAR(SEQs(List(CHAR('a'), CHAR('b')))) 
    53 
    48 
    54 // ADD YOUR CODE BELOW
    49 // ADD YOUR CODE BELOW
    55 //======================
    50 //======================
    56 
    51 
    57 // (1)
    52 // (1)