Further optimizing Number to Roman Numeral function in F#
f#, functional-programming
Solution
A slightly shorter way of recursively finding the largest digit representation that can be subtracted from the value (using List.find):
let units =
[1000, "M"
900, "CM"
500, "D"
400, "CD"
100, "C"
90, "XC"
50, "L"
40, "XL"
10, "X"
9, "IX"
5, "V"
4, "IV"
1, "I"]
let rec toRomanNumeral = function
| 0 -> ""
| n ->
let x, s = units |> List.find (fun (x,s) -> x <= n)
s + toRomanNumeral (n-x)
Problem
I'm new to F# and I'm curious if this can still be optimized further. I am not particularly sure if I've done this correctly as well. I'm curious particularly on the last line as it looks really long and hideous. I've searched over google, but only Roman Numeral to Number solutions only show up, so I'm having a hard time comparing. ``` type RomanDigit = I | IV | V | IX let rec romanNumeral number = let values = [ 9; 5; 4; 1 ] let capture number values = values |> Seq.find ( fun x -> number >= x ) let toRomanDigit x = match x with | 9 -> IX | 5 -> V | 4 -> IV | 1 -> I match number with | 0 -> [] | int -> Seq.toList ( Seq.concat [ [ toRomanDigit ( capture number values ) ]; romanNumeral ( number - ( capture number values ) ) ] ) ``` Thanks for anyone who can help with this problem.