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{-# Control.ArrowLANGUAGE TupleSections #-}
 
import Data.List
import Data.OrdList (maximumBy, sort, unfoldr)
import Data.ListOrd (comparing)
import qualified Data.Map as M
import qualified Data.Set as S
 
-- Group listsLists of words basedgrouped onby their "signatures". A signature is a sorted
-- list of characters. Handle duplicate inputDuplicate words by storing themstored in sets.
groupBySig =:: map[String] -> [(sort &&&String, S.singletonSet String)]
groupBySig = map ((,) . sort <*> S.singleton)
 
-- ConvertGroups groups toas lists of equivalent words.
equivs :: [(String, S.Set String)] -> [[String]]
equivs = map (S.toList . snd) . M.toList . M.fromListWith S.union
 
-- IndicateTrue whetherif thea pair of words differdiffers in all character positions.
isDerangement :: (String, String) -> Bool
isDerangement (a, b) = and $ zipWith (/=) a b
 
-- Return allAll pairs of elements, ignoring order.
pairs :: [t] -> [(t, t)]
pairs = concat . unfoldr step
where
where step (x:xs) = Just (map ((,) x) xs, xs)
step (x:xs) = Just step(map [](x, ) xs, = Nothingxs)
step [] = Nothing
 
-- Return allAll anagram pairs in the input string.
anagrams :: [String] -> [(String, String)]
anagrams = concatMap pairs . equivs . groupBySig
 
-- Return theThe pair of words makingforming the longest deranged anagram.
maxDerangedAnagram :: [String] -> Maybe (String, String)
maxDerangedAnagram = maxByLen . filter isDerangement . anagrams
where maxByLen [] = Nothing
maxByLen xs[] = Just $ maximumBy (comparing (length . fst)) xsNothing
maxByLen xs = Just $ maximumBy (comparing (length . fst)) xs
 
main :: IO ()
main = do
input <- getContentsreadFile "unixdict.txt"
case maxDerangedAnagram $ words input of
Nothing -> putStrLn "No deranged anagrams were found."
Just (a, b) -> putStrLn $ "Longest deranged anagrams: " ++<> a ++<> " and " ++<> b</lang>
{{out}}
<pre>Longest deranged anagrams: excitation and intoxicate</pre>
<pre>
Longest deranged anagrams: excitation and intoxicate
</pre>
 
=={{header|Icon}} and {{header|Unicon}}==
9,655

edits