2.3 numbers less than 100
We're getting up there! The pattern for digits less than a hundred is the tens digit is equal to
digits2 :: Int -> (Int, Int)
digits2 n = (div n 10, mod n 10) -- Does division twice...
digits2 n = (n `div` 10, n `mod` 10) -- What's this?
The second way of writing it uses back quotes ` to convert the operators div, mod
into infix operators, so it can be wrapped by its arguments. Note that (just as in most languages, I think), there is already a built-in function to do this called divMod
:
p `divMod` q == (p `div` q, p `mod` q) -- Faster, as its a single division.
digits2 n = n `divMod` 10 -- perfection.
So to combine these we need:
convert2 :: Int -> String
convert2 = combine2 . digits2
combine2 :: (Int, Int) -> String
combine2 (t, u)
| t == 0 = units u
| t == 1 = teens u
| u == 0 = tens t
| otherwise = tens t ++ "-" ++ units u
Again, we're using a switch statement here to split it up into its different cases. The rest of the functions like teens and tens are the same as units:
teens, tens :: Int -> String -- Same type
teens u = teenStrings!!u
tens t = tenStrings!!(t-2)
teenStrings :: [String]
teenStrings = ["ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" ]
tenStrings :: [String]
tenStrings = ["twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]