module TFwH.Anagrams where
import Prelude hiding (Word)
import Data.Char (toLower)
import Data.Function (on)
import Data.List (sort, sortBy, groupBy, intercalate)
import Data.Ord (comparing)
type Word = String
type Label = String
anagrams :: Int -> [Word] -> String
anagrams n = unlines
. map showEntry
. groupByLabel
. sortLabels
. map addLabel
. getWords n
getWords :: Int -> [Word] -> [Word]
getWords n = filter ((n ==) . length)
addLabel :: Word -> (Label, Word)
addLabel w = (sort (map toLower w), w)
sortLabels :: [(Label, Word)] -> [(Label, Word)]
sortLabels = sortBy (comparing fst)
groupByLabel :: [(Label, Word)] -> [(Label, [Word])]
groupByLabel = map mkEntry . groupBy ((==) `on` fst)
where
mkEntry lws = (head ls, ws)
where
(ls,ws) = unzip lws
showEntry :: (Label, [Word]) -> String
showEntry (l, ws)= l ++ ": " ++ intercalate "," ws