Skip to content

Instantly share code, notes, and snippets.

@joseraya
Created April 14, 2012 15:47
Show Gist options
  • Save joseraya/2385328 to your computer and use it in GitHub Desktop.
Save joseraya/2385328 to your computer and use it in GitHub Desktop.
Roman Numerals Scala (2)
A more functional version would be:
package kata
import org.scalatest.matchers.ShouldMatchers
import org.scalatest.{BeforeAndAfterEach, FlatSpec}
class Roman extends FlatSpec with ShouldMatchers {
case class Symbol(latin:Int, roman:String)
var symbols = List(Symbol(5,"V"), Symbol(4, "IV"), Symbol(1,"I"))
def toRoman(number:Int): String = symbols.foldLeft((number, "")){case((remaining, result),symbol)=> {
val occurrences = remaining / symbol.latin
(remaining - (occurrences * symbol.latin), result + symbol.roman * occurrences)
}}._2
it should "convert a 1 to I" in {
assert(toRoman(1) === "I")
}
it should "convert a 2 to II" in {
assert(toRoman(2) === "II")
}
it should "convert a 5 to V" in {
assert(toRoman(5) === "V")
}
it should "convert a 4 to IV" in {
assert(toRoman(4) === "IV")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment