Skip to content

Instantly share code, notes, and snippets.

@grantwwoodford
Created February 16, 2016 20:26
Show Gist options
  • Save grantwwoodford/f81c7b260d8f2cfffb91 to your computer and use it in GitHub Desktop.
Save grantwwoodford/f81c7b260d8f2cfffb91 to your computer and use it in GitHub Desktop.
Convert integers to Roman Numerals
let rec repeat x (s : string) : string =
match x with
| 0 -> ""
| x -> s + (repeat (x-1) s)
let roman_numeral_ordering n (one : string) (five : string) (ten : string) =
match n with
| 0 -> ""
| n when n < 4 -> repeat n one
| n when n = 4 -> one + five
| n when n = 5 -> five
| n when 5 < n && n < 9 -> five + (repeat (n - 5) one)
| n when n = 9 -> one + ten
| n -> "unknown"
let century_roman m =
match m with
| 0 -> ""
| 1 -> "M"
| m -> "unknown"
let hundreds_roman m =
match m with
| m when m < 10 -> roman_numeral_ordering m "C" "D" "M"
| m -> "unknown"
let tens_roman m =
match m with
| m when m < 10 -> roman_numeral_ordering m "X" "L" "C"
| m -> "unknown"
let ones_roman m =
match m with
| m when m < 10 -> roman_numeral_ordering m "I" "V" "X"
| m -> "unknown"
let rec convert_to_roman x : string =
match x with
| x when (float x)/1000.0 >= 1.0 -> (century_roman (x/1000)) + convert_to_roman (x%1000)
| x when (float x)/100.0 >= 1.0 -> hundreds_roman (x/100) + convert_to_roman (x%100)
| x when (float x)/10.0 >= 1.0 -> tens_roman (x/10) + convert_to_roman (x%10)
| x when (float x) >= 1.0 -> ones_roman x
| x -> ""
let rec print_roman_numerals i =
match i with
| 1999 -> printfn "Done"
| i -> printfn "%i : %s\n" i (convert_to_roman (i)); print_roman_numerals (i+1)
// single example
convert_to_roman 1984 |> printfn "%A"
// print all
print_roman_numerals 1;;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment