Created
July 5, 2010 14:08
-
-
Save tormodfj/464380 to your computer and use it in GitHub Desktop.
Calculate Roman numerals with F#
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
module RomanNumerals | |
// Define function | |
let convertToRoman n = | |
let steps = [ | |
(1, 3, "I") | |
(4, 4, "IV") | |
(5, 8, "V") | |
(9, 9, "IX") | |
(10, 39, "X") | |
(40, 49, "XL") | |
(50, 89, "L") | |
(90, 99, "XC") | |
(100, 399, "C") | |
(400, 499, "CD") | |
(500, 899, "D") | |
(900, 999, "CM") | |
(1000, 3999, "M") ] | |
let isWithin n (low, high) = | |
low <= n && n <= high | |
let getStep n = | |
try | |
steps | |
|> List.find (fun (low, high, step) -> isWithin n (low, high)) | |
|> Some | |
with | |
| _ -> None | |
let rec createRoman n accumulator = | |
match getStep n with | |
| Some(low, high, step) -> createRoman (n - low) (accumulator + step) | |
| None -> accumulator | |
createRoman n "" | |
// Run program | |
printfn "Enter a number between 1 and 3999:" | |
System.Console.ReadLine() | |
|> int32 | |
|> convertToRoman | |
|> printfn "%s" | |
printfn "Press any key to exit..." | |
System.Console.ReadKey() | |
|> ignore |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment