35 case class CharParser(c: Char) extends Parser[String, Char] { |
35 case class CharParser(c: Char) extends Parser[String, Char] { |
36 def parse(sb: String) = |
36 def parse(sb: String) = |
37 if (sb != "" && sb.head == c) Set((c, sb.tail)) else Set() |
37 if (sb != "" && sb.head == c) Set((c, sb.tail)) else Set() |
38 } |
38 } |
39 |
39 |
40 case class StringParser(s: String) extends Parser[String, String] { |
40 import scala.util.matching.Regex |
41 def parse(sb: String) = { |
41 case class RegexParser(reg: Regex) extends Parser[String, String] { |
42 val (prefix, suffix) = sb.splitAt(s.length) |
42 def parse(sb: String) = reg.findPrefixMatchOf(sb) match { |
43 if (prefix == s) Set((prefix, suffix)) else Set() |
43 case None => Set() |
|
44 case Some(m) => Set((m.matched, m.after.toString)) |
44 } |
45 } |
45 } |
46 } |
46 |
47 |
47 case object NumParser extends Parser[String, Int] { |
48 val NumParser = RegexParser("[0-9]+".r) |
48 val reg = "[0-9]+".r |
49 def StringParser(s: String) = RegexParser(s.r) |
49 def parse(sb: String) = reg.findPrefixOf(sb) match { |
50 |
50 case None => Set() |
|
51 case Some(s) => Set(sb.splitAt(s.length) match { |
|
52 case (x, y) => (x.toInt, y) |
|
53 }) |
|
54 } |
|
55 } |
|
56 |
51 |
57 // convenience |
52 // convenience |
58 implicit def string2parser(s: String) = StringParser(s) |
53 implicit def string2parser(s: String) = StringParser(s) |
59 implicit def char2parser(c: Char) = CharParser(c) |
54 implicit def char2parser(c: Char) = CharParser(c) |
60 |
55 |
72 new SeqParser[String, String, S](s, q) |
67 new SeqParser[String, String, S](s, q) |
73 def ~ (r: String) = |
68 def ~ (r: String) = |
74 new SeqParser[String, String, String](s, r) |
69 new SeqParser[String, String, String](s, r) |
75 } |
70 } |
76 |
71 |
|
72 val c = new CharParser('c') |
|
73 lazy val cn = c ==> (c => c.toInt) |
|
74 val f = (c: Char) => c.toInt |
|
75 |
|
76 c.parse("cb") |
|
77 (c ==> f).parse("cb") |
|
78 |
77 // a parse palindromes |
79 // a parse palindromes |
78 lazy val Pal : Parser[String, String] = |
80 lazy val Pal : Parser[String, String] = |
79 (("a" ~ Pal ~ "a") ==> { case ((x, y), z) => x + y + z } || |
81 (("a" ~ Pal ~ "a") ==> { case ((x, y), z) => x + y + z } || |
80 ("b" ~ Pal ~ "b") ==> { case ((x, y), z) => x + y + z } || "a" || "b" || "") |
82 ("b" ~ Pal ~ "b") ==> { case ((x, y), z) => x + y + z } || "a" || "b" || "") |
81 |
83 |