import qualified Data.ByteString.Char8 as B import Data.List wd = '|' main = do getLine bs <- map (flip B.snoc wd) . B.lines <$> B.getContents putStrLn (merge bs) merge bs = reverse $ fst $ until (null . snd) conc ("", sort bs) conc (r,(b:bs)) = (c:r, sort (filter notNull (b':bs))) where (Just (c,b')) = B.uncons b notNull = not . (== wd) . B.head