文字列を先頭から見て同じところまで除去
ふむ。Haskell だとどうなるか。
素直に書くとこうかな。
sameAll :: Eq a => [a] -> Bool sameAll (x:xs) = all (x==) xs sameAll [] = True dropCommonPrefix :: Eq a => [[a]] -> [[a]] dropCommonPrefix strings | any null strings = strings | sameAll (map head strings) = dropCommonPrefix (map tail strings) | otherwise = strings
こゆのもありか。面倒なので、longestCommonPrefix はソートして先頭と末尾だけ比較。(なので、対象が Ord クラスに限られる)
longestCommonPrefix :: Ord a => [[a]] -> [a] longestCommonPrefix lst = map fst $ takeWhile eq $ zip (minimum lst) (maximum lst) where eq (x, y) = x == y dropCommonPrefix :: Ord a => [[a]] -> [[a]] dropCommonPrefix lst = map (drop longestCommonPrefixLength) lst where longestCommonPrefixLength = length $ longestCommonPrefix lst
Python だとこんな感じか。
longestCommonPrefix :: Ord a => [[a]] -> [a] longestCommonPrefix lst = map fst $ takeWhile eq $ zip (minimum lst) (maximum lst) where eq (x, y) = x == y dropCommonPrefix :: Ord a => [[a]] -> [[a]] dropCommonPrefix lst = map (drop longestCommonPrefixLength) lst where longestCommonPrefixLength = length $ longestCommonPrefix lst
def dropCommonPrefix(*strings): def commonPrefixLength(xs, ys): maxLen = min(len(xs), len(ys)) for i in xrange(maxLen): if xs[i] != ys[i]: return i return maxLen cpl = commonPrefixLength(min(strings), max(strings)) return tuple(s[cpl:] for s in strings)