Created
January 23, 2012 16:55
-
-
Save pr1001/1664232 to your computer and use it in GitHub Desktop.
How to get Enumeration values back when using Scala parser combinators.
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
// ISO 3166-1 alpha-2 two letter country codes from http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 | |
object Country extends Enumeration { | |
val Andorra = Value("ad") // Andorra | |
val UAE = Value("ae") // United Arab Emirates | |
val Afghanistan = Value("af") // Afghanistan | |
// ... | |
} | |
trait CountryParser extends JavaTokenParsers { | |
// would love to get rid of the silly regex | |
lazy val country: Parser[Country.Value] = """\w+""".r ^? ({ | |
// if lower-cased | |
case str if Country.values.exists((ctry) => ctry.toString == str) => Country.withName(str) | |
// if upper-cased | |
case str if Country.values.exists((ctry) => ctry.toString.toUpperCase == str) => Country.withName(str.toLowerCase) | |
}, "Unknown country code: " + _) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It'd be awesome if someone could figure out a generic version. This is along the lines:
But it doesn't work: