progs/comb1.scala
changeset 667 412556272333
parent 629 1b718d6065c2
child 672 e0d76f7f0688
equal deleted inserted replaced
666:4fbdc80076cb 667:412556272333
     3 
     3 
     4 /* Note, in the lectures I did not show the implicit type 
     4 /* Note, in the lectures I did not show the implicit type 
     5  * constraint IsSeq, which means that the input type 'I' needs 
     5  * constraint IsSeq, which means that the input type 'I' needs 
     6  * to be a sequence. */
     6  * to be a sequence. */
     7 
     7 
     8  type IsSeq[A] = A => Seq[_]
     8 type IsSeq[A] = A => Seq[_]
     9 
     9 
    10 abstract class Parser[I : IsSeq, T] {
    10 abstract class Parser[I : IsSeq, T] {
    11   def parse(ts: I): Set[(T, I)]
    11   def parse(ts: I): Set[(T, I)]
    12 
    12 
    13   def parse_all(ts: I) : Set[T] =
    13   def parse_all(ts: I) : Set[T] =
    82 lazy val Pal : Parser[String, String] = 
    82 lazy val Pal : Parser[String, String] = 
    83   (("a" ~ Pal ~ "a") ==> { case ((x, y), z) => x + y + z } ||
    83   (("a" ~ Pal ~ "a") ==> { case ((x, y), z) => x + y + z } ||
    84    ("b" ~ Pal ~ "b") ==> { case ((x, y), z) => x + y + z } || "a" || "b" || "")
    84    ("b" ~ Pal ~ "b") ==> { case ((x, y), z) => x + y + z } || "a" || "b" || "")
    85 
    85 
    86 Pal.parse_all("abaaaba")
    86 Pal.parse_all("abaaaba")
       
    87 Pal.parse_all("abacba")
    87 Pal.parse("abaaaba")
    88 Pal.parse("abaaaba")
    88 
    89 
    89 println("Palindrome: " + Pal.parse_all("abaaaba"))
    90 println("Palindrome: " + Pal.parse_all("abaaaba"))
    90 
    91 
    91 // well-nested parentheses parser (transforms '(' -> '{' , ')' -> '}' )
    92 // well-nested parentheses parser (transforms '(' -> '{' , ')' -> '}' )
    94 
    95 
    95 P.parse_all("(((()()))())")
    96 P.parse_all("(((()()))())")
    96 P.parse_all("(((()()))()))")
    97 P.parse_all("(((()()))()))")
    97 P.parse_all(")(")
    98 P.parse_all(")(")
    98 P.parse_all("()")
    99 P.parse_all("()")
       
   100 
       
   101 lazy val PC : Parser[String, Int] = 
       
   102   ("(" ~ PC ~ ")" ~ PC ==> { case (((_, x), _), y) => x + y + 2 } || 
       
   103    "" ==> { (s) => 0 })
       
   104 
       
   105 PC.parse_all("(((()()))())")
       
   106 P.parse_all("(((()()))()))")
    99 
   107 
   100 // Arithmetic Expressions (Terms and Factors)
   108 // Arithmetic Expressions (Terms and Factors)
   101 
   109 
   102 lazy val E: Parser[String, Int] = 
   110 lazy val E: Parser[String, Int] = 
   103   (T ~ "+" ~ E) ==> { case ((x, y), z) => x + z } ||
   111   (T ~ "+" ~ E) ==> { case ((x, y), z) => x + z } ||