Skip to content

Instantly share code, notes, and snippets.

@paulogaspar7
Last active April 24, 2016 20:02
Show Gist options
  • Save paulogaspar7/ae66e8c21440eb7e689992b73dcbd5c5 to your computer and use it in GitHub Desktop.
Save paulogaspar7/ae66e8c21440eb7e689992b73dcbd5c5 to your computer and use it in GitHub Desktop.
Romans number parser with (some) validation. Not beautiful, not efficient, just small...
def table(i: Char, v: Char, x: Char) = Seq("", s"$i", s"$i$i", s"$i$i$i", s"$i$v", s"$v", s"$v$i", s"$v$i$i", s"$v$i$i$i", s"$i$x" )
val x1000 = Seq("", "M", "MM", "MMM", "MMMM")
val x100 = table('C', 'D', 'M')
val x10 = table('X', 'L', 'C')
val x1 = table('I', 'V', 'X')
val lookup: Map[String, Int] = (1 to 4999).foldLeft(Map.empty[String, Int]) {
case (m, d) => m.updated(x1000(d / 1000) + x100((d % 1000) / 100) + x10((d % 100) / 10) + x1(d % 10), d)
}
override def parsed(roman: String) = lookup.get(roman.trim().toUpperCase()).map(Right(_)).getOrElse(Left("Invalid roman number"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment