Created
April 14, 2012 15:47
-
-
Save joseraya/2385328 to your computer and use it in GitHub Desktop.
Roman Numerals Scala (2)
This file contains 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
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