#! /usr/bin/env stack -- stack --resolver lts-12.20 --install-ghc script module Main where loopRight :: b -> (b -> Either a b) -> a loopRight b f = case f b of Left a -> a Right b' -> loopRight b' f main :: IO () main = interact $ show . \input -> let codes = lines input :: [[Char]] in loopRight ([], codes) $ \(seen, c:cs) -> case filter (`isSimilarTo` c) seen of [] -> Right (c:seen, cs) (x:_) -> Left (c, x, foldMap (\(a,b) -> if a == b then [a] else []) (zip c x)) isSimilarTo :: (Eq a) => [a] -> [a] -> Bool (x:xs) `isSimilarTo` (y:ys) | x == y = xs `isSimilarTo` ys | otherwise = xs == ys _ `isSimilarTo` _ = False