进一步优化F#中的Number to Roman Numeral函数

Cha*_*had 3 f# functional-programming

我是F#的新手,我很好奇这是否仍然可以进一步优化.我不是特别确定我是否也正确地做到了这一点.我特别对最后一行感到好奇,因为它看起来很长很可怕.

我搜索了谷歌,但只有罗马数字到数字解决方案只显示,所以我很难比较.

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 ) ) ] )
Run Code Online (Sandbox Code Playgroud)

感谢任何可以帮助解决此问题的人.

Phi*_*ord 6

递归查找可从值中减去的最大数字表示的稍微缩短的方法(使用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)
Run Code Online (Sandbox Code Playgroud)