Skip to content

Instantly share code, notes, and snippets.

@dsimunic
Created October 2, 2014 20:17
Show Gist options
  • Save dsimunic/b525b66c7c6b7524f6d4 to your computer and use it in GitHub Desktop.
Save dsimunic/b525b66c7c6b7524f6d4 to your computer and use it in GitHub Desktop.
Parse roman numerals
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