Skip to content

Instantly share code, notes, and snippets.

@ysimonson
Created October 25, 2011 18:37
Show Gist options
  • Save ysimonson/1313774 to your computer and use it in GitHub Desktop.
Save ysimonson/1313774 to your computer and use it in GitHub Desktop.
Telephone words in Haskell
import Data.Char
telephoneWords :: String -> [String]
telephoneWords [] = [[]]
telephoneWords (digit : digits) =
[letter : rest
| letter <- digitToLetters digit, rest <- telephoneWords digits]
digitToLetters :: Char -> String
digitToLetters c
| n < 0 || n > 9 = error "Illegal telephone number"
| n < 2 = [c]
| n < 7 = [chr (((n - 2) * 3) + baseA + i) | i <- [0..2]]
| n == 7 = "PQRS"
| n == 8 = "TUV"
| n == 9 = "WXYZ"
where
baseA = ord 'A'
n = (ord c) - (ord '0')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment