Created
May 13, 2016 06:00
-
-
Save acdenhartog/945d1c62da21ce9dc9a0c1041407c707 to your computer and use it in GitHub Desktop.
StringContext regex extractors idea
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object Main extends App { | |
implicit class Reggy(val sc: StringContext) extends AnyVal { | |
def regexNonTypeSafe(args: CanParse[_]*) = new RegexMatcher(Tuple1(args),sc) | |
def regex[T<:Product](args: T):RegexMatcher[T] = new RegexMatcher(args,sc) | |
//this could work with some type level hackery to map the args though a Poly into CanParsers | |
} | |
class RegexMatcher[T<:Product] | |
(val captures:T, //type of T here is (Int.type,String,Long.type) or (WrappedArray(CanParse[Int],CanParse[String],CanParse[Long])) | |
val context:StringContext){ | |
def getCaptures(from:String):T = ??? //just do the regex, then Poly map your CanParse[T] into Try[T]? | |
} | |
trait CanParse[T] { | |
def regexMatcher:String //capture pattern for this type | |
def parse(str:String):T //accepts a capture | |
} | |
//cannot use a type class in regexNonTypeSafe case because we need to abstract over arity | |
implicit val canParseInt : Int.type => CanParse[Int] = | |
objectInt =>new CanParse[Int] { | |
override def regexMatcher = """(\d+)""" //what about other integer representations? | |
override def parse(str: String) = str.toInt | |
} | |
implicit val canParseLong : Long.type => CanParse[Long] = | |
objectInt =>new CanParse[Long] { | |
override def regexMatcher = """(\d+L?)""" | |
override def parse(str: String) = str.toLong | |
} | |
implicit val canParseRegex : String => CanParse[String] = | |
regexSnippet =>new CanParse[String] { | |
override def regexMatcher = regexSnippet | |
override def parse(str: String) = str | |
} | |
regexNonTypeSafe"""$Int${"capture\t"}..$Long hello*o!""".getCaptures("blablabla") | |
regex"""$Int${"capture\t"}..$Long hello*o!""" //<<<---- this looks more fancy if you drop it into an IDE with real syntax highlighting... | |
// both on the parsing end "18E-23".toDouble | |
// now also on the capture end """-?\d+(.\d+)?(E-?\d+)?""" could be easily supplied by the library, | |
// and then you can pretty much guarantee that parsing always succeeds. | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment