Haskell Quiz/Phone Number Words/Solution Jethr0
From HaskellWiki
< Haskell Quiz | Phone Number Words(Difference between revisions)
m |
m |
||
| (One intermediate revision not shown.) | |||
| Line 1: | Line 1: | ||
| - | [[Category: | + | [[Category:Haskell Quiz solutions|Phone Number Words]] |
<haskell> | <haskell> | ||
| Line 8: | Line 8: | ||
-- if no result is found, the original string is returned as possibility | -- if no result is found, the original string is returned as possibility | ||
allPoss xs = if null result then [xs] else result | allPoss xs = if null result then [xs] else result | ||
| - | where result = filter (`elem` dictionary) . | + | where result = filter (`elem` dictionary) . mapM poss $ xs |
| - | poss char = encodings!! | + | poss char = encodings!! digitToInt char |
encodings = ["0", "1", "ABC", "DEF", "GHI", "JKL", "MNO", "PQRS", "TUV", "WXYZ"] | encodings = ["0", "1", "ABC", "DEF", "GHI", "JKL", "MNO", "PQRS", "TUV", "WXYZ"] | ||
| Line 19: | Line 19: | ||
-- > phoneNames "1.800.5646.843.4275355.7849" | -- > phoneNames "1.800.5646.843.4275355.7849" | ||
-- ["1-800-JOIN-THE-HASKELL-QUIZ"] | -- ["1-800-JOIN-THE-HASKELL-QUIZ"] | ||
| - | phoneNames = map (concat . intersperse "-") . | + | phoneNames = map (concat . intersperse "-") . mapM allPoss . splitThem |
</haskell> | </haskell> | ||
Current revision
dictionary = map (map toUpper) ["haskell", "join", "the", "quiz"] -- fetch all possible words represented by a string of consecutive digits -- the results are checked against the dictionary -- if no result is found, the original string is returned as possibility allPoss xs = if null result then [xs] else result where result = filter (`elem` dictionary) . mapM poss $ xs poss char = encodings!! digitToInt char encodings = ["0", "1", "ABC", "DEF", "GHI", "JKL", "MNO", "PQRS", "TUV", "WXYZ"] splitThem [] = [] splitThem xs = y : rest where (y,ys) = break (not . isDigit) xs rest = splitThem . dropWhile (not . isDigit) $ ys -- > phoneNames "1.800.5646.843.4275355.7849" -- ["1-800-JOIN-THE-HASKELL-QUIZ"] phoneNames = map (concat . intersperse "-") . mapM allPoss . splitThem
