progs/comb1.scala
changeset 588 a4646557016d
parent 586 451a95e1bc25
child 590 c6a1e19e9801
--- a/progs/comb1.scala	Wed Oct 24 20:37:37 2018 +0100
+++ b/progs/comb1.scala	Thu Oct 25 00:50:58 2018 +0100
@@ -37,22 +37,17 @@
     if (sb != "" && sb.head == c) Set((c, sb.tail)) else Set()
 }
 
-case class StringParser(s: String) extends Parser[String, String] {
-  def parse(sb: String) = {
-    val (prefix, suffix) = sb.splitAt(s.length)
-    if (prefix == s) Set((prefix, suffix)) else Set()
+import scala.util.matching.Regex
+case class RegexParser(reg: Regex) extends Parser[String, String] {
+  def parse(sb: String) = reg.findPrefixMatchOf(sb) match {
+    case None => Set()
+    case Some(m) => Set((m.matched, m.after.toString))  
   }
 }
 
-case object NumParser extends Parser[String, Int] {
-  val reg = "[0-9]+".r
-  def parse(sb: String) = reg.findPrefixOf(sb) match {
-    case None => Set()
-    case Some(s) => Set(sb.splitAt(s.length) match {
-      case (x, y) => (x.toInt, y)
-    }) 
-  }
-}
+val NumParser = RegexParser("[0-9]+".r)
+def StringParser(s: String) = RegexParser(s.r)
+
 
 // convenience
 implicit def string2parser(s: String) = StringParser(s)
@@ -74,6 +69,13 @@
     new SeqParser[String, String, String](s, r)
 }
 
+val c = new CharParser('c')
+lazy val cn = c ==> (c => c.toInt)
+val f = (c: Char) => c.toInt
+
+c.parse("cb")
+(c ==> f).parse("cb")
+
 // a parse palindromes
 lazy val Pal : Parser[String, String] = 
   (("a" ~ Pal ~ "a") ==> { case ((x, y), z) => x + y + z } ||