Created
October 2, 2014 20:17
-
-
Save dsimunic/b525b66c7c6b7524f6d4 to your computer and use it in GitHub Desktop.
Parse roman numerals
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
type RomanDigit = Nil | I | V | X | L | C | D | M | |
let romanDigitToInt aRomanDigit = | |
match aRomanDigit with | |
| Nil -> 0 | |
| I -> 1 | |
| V -> 5 | |
| X -> 10 | |
| L -> 50 | |
| C -> 100 | |
| D -> 500 | |
| M -> 1000 | |
let sumTwoDigits f s = | |
match romanDigitToInt f, romanDigitToInt s with | |
| fi, si when fi < si -> si - fi | |
| fi, si -> fi + si | |
let rec sumOfRomanDigits aList sumSoFar = | |
match aList with | |
| [] -> sumSoFar | |
| f::s::rest when f < s -> sumOfRomanDigits rest (sumSoFar + sumTwoDigits f s) | |
| f::rest -> sumOfRomanDigits rest (sumSoFar + romanDigitToInt f) | |
let romanNumeralToInt aList = | |
sumOfRomanDigits aList 0 | |
let charToRomanDigit ch = | |
match ch with | |
| 'I' -> I | |
| 'V' -> V | |
| 'X' -> X | |
| 'L' -> L | |
| 'C' -> C | |
| 'D' -> D | |
| 'M' -> M | |
| _ -> Nil | |
let stringToRomanDigits (str:string) = | |
str.ToCharArray() | |
|> Array.toList | |
|> List.map charToRomanDigit | |
let romanNumeralStringToInt str = | |
str | |
|> stringToRomanDigits | |
|> romanNumeralToInt |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment