Skip to content

Instantly share code, notes, and snippets.

@pleax
Created January 17, 2010 21:02
Show Gist options
  • Save pleax/279579 to your computer and use it in GitHub Desktop.
Save pleax/279579 to your computer and use it in GitHub Desktop.
Funny pattern matching
object ToRome {
sealed class RomeDigit(val value: Int)
case object I extends RomeDigit(1)
case object V extends RomeDigit(5)
case object X extends RomeDigit(10)
case object L extends RomeDigit(50)
case object C extends RomeDigit(100)
case object D extends RomeDigit(500)
case object M extends RomeDigit(1000)
def toRome(x: Int): List[RomeDigit] = x match {
case x if x >= M.value => M :: toRome(x - M.value)
case x if x >= M.value - C.value => C :: M :: toRome(x - (M.value - C.value))
case x if x >= D.value => D :: toRome(x - D.value)
case x if x >= D.value - C.value => C :: D :: toRome(x - (D.value - C.value))
case x if x >= C.value => C :: toRome(x - C.value)
case x if x >= C.value - X.value => X :: C :: toRome(x - (C.value - X.value))
case x if x >= L.value => L :: toRome(x - L.value)
case x if x >= L.value - X.value => X :: L :: toRome(x - (L.value - X.value))
case x if x >= X.value => X :: toRome(x - X.value)
case x if x >= X.value - I.value => I :: X :: toRome(x - (X.value - I.value))
case x if x >= V.value => V :: toRome(x - V.value)
case x if x >= V.value - I.value => I :: V :: toRome(x - (V.value - I.value))
case x if x >= I.value => I :: toRome(x - I.value)
case 0 => Nil
case _ => throw new IllegalArgumentException
}
def main(args: Array[String]) {
1 to 10 foreach { x =>
println(toRome(x))
}
println(toRome(15))
println(toRome(19))
println(toRome(8))
println(toRome(64))
println(toRome(63))
80 to 100 foreach { x =>
println(toRome(x))
}
39 to 55 foreach { x =>
println(toRome(x))
}
println(toRome(1993))
println(toRome(2010))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment