Skip to content

Instantly share code, notes, and snippets.

@tos-kamiya
Last active December 11, 2015 04:38
Show Gist options
  • Save tos-kamiya/4546344 to your computer and use it in GitHub Desktop.
Save tos-kamiya/4546344 to your computer and use it in GitHub Desktop.
import Data.List
import qualified Data.Set as S
import Data.String.Utils
genEquivalentClass :: Ord a => [(a, a)] -> [[a]]
genEquivalentClass pairs =
sort . map (sort . S.toList) $ foldr eqcs [] pairs
where
eqcs (n, m) cs = case (lookupClass n cs, lookupClass m cs) of
(Nothing, Nothing) -> S.fromList [n, m] : cs
(Nothing, Just mci) -> S.insert n (cs !! mci) : (cs !!~ [mci])
(Just nci, Nothing) -> S.insert m (cs !! nci) : (cs !!~ [nci])
(Just nci, Just mci)
| nci == mci -> cs
| otherwise -> S.union (cs !! nci) (cs !! mci) : (cs !!~ [nci, mci])
lookupClass n cs = findIndex (n `S.member`) cs
a !!~ is = snd . unzip . (filter $ (`notElem` is) . fst) . zip [0..] $ a
main = do
str <- getContents
let namePairs = map ((\[a, b] -> (a, b)) . (split "=") . rstrip) $ lines str
putStr . unlines . map (intercalate "=") . genEquivalentClass $ namePairs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment