Anagrams/Deranged anagrams: Difference between revisions
→{{header|Haskell}}: Minor updates : Applicative in lieu of Arrow, tuple section, signatures, hlint hindent.
m (→{{header|AppleScript}}: Updated to return the co-longest deranged anagrams when there are more than one — unnecessarily, as it turns out. :)) |
(→{{header|Haskell}}: Minor updates : Applicative in lieu of Arrow, tuple section, signatures, hlint hindent.) |
||
Line 1,737:
=={{header|Haskell}}==
If the longest deranged anagram includes three or more words we'll only print two of them. We also correctly handle duplicate words in the input.
<lang haskell>
import Data.List▼
import Data.
import qualified Data.Map as M
import qualified Data.Set as S
--
-- list of characters.
groupBySig
groupBySig = map ((,) . sort <*> S.singleton)
--
equivs :: [(String, S.Set String)] -> [[String]]
equivs = map (S.toList . snd) . M.toList . M.fromListWith S.union
--
isDerangement :: (String, String) -> Bool
isDerangement (a, b) = and $ zipWith (/=) a b
--
pairs :: [t] -> [(t, t)]
pairs = concat . unfoldr step
where
step (x:xs) = Just
step [] = Nothing
--
anagrams :: [String] -> [(String, String)]
anagrams = concatMap pairs . equivs . groupBySig
--
maxDerangedAnagram :: [String] -> Maybe (String, String)
maxDerangedAnagram = maxByLen . filter isDerangement . anagrams
where
maxByLen xs = Just $ maximumBy (comparing (length . fst)) xs
main :: IO ()
main = do
input <-
case maxDerangedAnagram $ words input of
Nothing
Just (a, b) -> putStrLn $ "Longest deranged anagrams: "
{{out}}
<pre>Longest deranged anagrams: excitation and intoxicate</pre>▼
▲Longest deranged anagrams: excitation and intoxicate
=={{header|Icon}} and {{header|Unicon}}==
|