Sunday, January 1, 2012
Active Patterns to transform number
Today I read through the active pattern in F# and was inspired to use it somehow. The following is a very simple sample to convert number. I will continue improving this code and, in the meanwhile, improve my F# skill.
the following code convert int 1002 to string "One Thousand and Two".
let ( | Billion | Million | Thousand | Hundred | Less |) x =
match x with
| _ when x >=1000000000 -> Billion
| _ when x >=1000000 -> Million
| _ when x >=1000 -> Thousand
| _ when x >=100 -> Hundred
| _ -> Less
let rec getStr2 x =
match x with
| 0 -> ""
| 1 -> "One"
| 2 -> "Two"
| 3 -> "Three"
| 4 -> "Four"
| 5 -> "Five"
| 6 -> "Six"
| 7 -> "Seven"
| 8 -> "Eight"
| 9 -> "Nine"
| 10 -> "Ten"
| 11 -> "Eleven"
| 12 -> "Twelve"
| 13 -> "Thirteen"
| 14 -> "Fourteen"
| 15 -> "Fifteen"
| 16 -> "Sixteen"
| 17 -> "Seventeen"
| 18 -> "Eighteen"
| 19 -> "Nineteen"
| _ when x >= 20 && x < 30 -> "Twenty " + (getStr2 (x%20))
| _ when x >= 30 && x < 40 -> "Thirty " + (getStr2 (x%30))
| _ when x >= 40 && x < 50 -> "Forty " + (getStr2 (x%40))
| _ when x >= 50 && x < 60 -> "Fifty " + (getStr2 (x%50))
| _ when x >= 60 && x < 70 -> "Sixty " + (getStr2 (x%60))
| _ when x >= 70 && x < 80 -> "Seventy " + (getStr2 (x%70))
| _ when x >= 80 && x < 90 -> "Eighty " + (getStr2 (x%80))
| _ when x >= 90 && x < 100 -> "Ninety " + (getStr2 (x%90))
let rec getStr x =
let joinStr numberBase word =
let a = getStr (x % numberBase)
let b = getStr (x / numberBase)
sprintf "%s %s %s" b word a
match x with
| Less -> getStr2 x
| Hundred -> joinStr 100 "Hundred"
| Thousand -> joinStr 1000 "Thousand"
| Million -> joinStr 1000000 "Million"
| Billion -> joinStr 1000000000 "Billion"
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment