functional programming - Further optimizing Number to Roman Numeral function in F# -
i'm new f# , i'm curious if can still optimized further. not particularly sure if i've done correctly well. i'm curious particularly on last line looks long , hideous.
i've searched on google, roman numeral number solutions show up, i'm having hard time comparing.
type romandigit = | 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 | 9 -> ix | 5 -> v | 4 -> iv | 1 -> match number | 0 -> [] | int -> seq.tolist ( seq.concat [ [ toromandigit ( capture number values ) ]; romannumeral ( number - ( capture number values ) ) ] )
thanks can problem.
a shorter way of recursively finding largest digit representation can subtracted 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)
Comments
Post a Comment