Advertisement
Madotsuki

Phone Number Question

Nov 18th, 2015
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. -- Question of the Day
  2. -- Given a phone number, write a function that outputs every
  3. -- possible letter combination for that number.
  4.  
  5. -- First, we can make an auxiliary function
  6. -- that will take a number and convert it
  7. -- to its corresponding telephone numpad.
  8. -- This function is done via recursion and concatenation with the cons operator.
  9. phoneToString :: Integer -> [String]
  10. phoneToString 0 = []
  11. phoneToString n = (numPick (n `mod` 10)):(phoneToString $ fromIntegral $ floor ((fromIntegral n)/10) )
  12.     where numPick d = case d of 1 -> " "
  13.                                 2 -> "abc"
  14.                                 3 -> "def"
  15.                                 4 -> "ghi"
  16.                                 5 -> "jkl"
  17.                                 6 -> "mno"
  18.                                 7 -> "pqrs"
  19.                                 8 -> "tuv"
  20.                                 9 -> "wxyz"
  21.                                 0 -> " "
  22.                                
  23.                                
  24. -- Then we do a quick n'dirty list comprehension.
  25. -- Just a note that the earlier function actually
  26. -- has the list in reverse because the least sig. num
  27. -- has the most precedence, so we use reverse to get it
  28. -- to the correct order.                                
  29. phoneNumberMapper :: Integer -> [String]
  30. phoneNumberMapper num
  31.     | ( (num < 10^6) || (num > 10^7) ) = ["INVALID"] -- Assuming that a phone number is only 7-digits.
  32.     | otherwise = [ [d0]++[d1]++[d2]++[d3]++[d4]++[d5]++[d6] |
  33.                     d0 <- (numList !! 0),
  34.                     d1 <- (numList !! 1),
  35.                     d2 <- (numList !! 2),
  36.                     d3 <- (numList !! 3),
  37.                     d4 <- (numList !! 4),
  38.                     d5 <- (numList !! 5),
  39.                     d6 <- (numList !! 6)
  40.                     ]
  41.         where numList = reverse $ phoneToString num
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement