1. // Euler Problem 17: Number letter counts
2.
3. let rec numberEnglish n =
4. match n with
5. | _ when n < 1 -> ""
6. | 1 -> "one"
7. | 2 -> "two"
8. | 3 -> "three"
9. | 4 -> "four"
10. | 5 -> "five"
11. | 6 -> "six"
12. | 7 -> "seven"
13. | 8 -> "eight"
14. | 9 -> "nine"
15. | 10 -> "ten"
16. | 11 -> "eleven"
17. | 12 -> "twelve"
18. | _ when n >= 13 && n <= 19 -> teens n
19. | _ when n >= 20 && n <= 99 -> teens2 n
20. | _ when n >= 100 && n <= 999 -> hundreds n
21. | 1000 -> "one thousand"
22. | _ -> ""
23.
24. and teens n =
25. match n with
26. | 13 -> "thir"
27. | 14 -> "four"
28. | 15 -> "fif"
29. | 16 -> "six"
30. | 17 -> "seven"
31. | 18 -> "eigh"
32. | 19 -> "nine"
33. | _ -> ""
34. + "teen"
35.
36. and teens2 n =
37. let m1 =
38. match n / 10 with
39. | 2 -> "twenty"
40. | 3 -> "thirty"
41. | 4 -> "forty"
42. | 5 -> "fifty"
43. | 6 -> "sixty"
44. | 7 -> "seventy"
45. | 8 -> "eighty"
46. | 9 -> "ninety"
47. | _ -> ""
48. let m2 =
49. match n % 10 with
50. | 0 -> ""
51. | m -> "-" + numberEnglish m
52. m1 + m2
53.
54. and hundreds n =
55. let m1 = numberEnglish (n / 100) + " hundred"
56. let m2 =
57. match n % 100 with
58. | 0 -> ""
59. | m -> " and " + numberEnglish m
60. m1 + m2
61.
62. let euler017 () =
63. let sb = System.Text.StringBuilder ()
64. (sb, { 1 .. 1000 })
65. ||> Seq.fold (fun b n -> b.Append (numberEnglish n))
66. |> string
67. |> Seq.sumBy (fun c -> if Core.char.IsLetter c then 1 else 0)
68.
69. let timer f =
70. let sw = System.Diagnostics.Stopwatch ()
71. sw.Start ()
72. let r = f ()
73. sw.Stop ()
74. r, sw.Elapsed
75.
76. let _ =
77. let r, t = timer euler017
78. printfn "Result: %A" r
79. printfn "Time: %A" t
80.
Success #stdin #stdout 0.06s 133824KB
stdin
Standard input is empty
stdout
Result: 21124
Time: 00:00:00.0039295