我需要定义一个遍历字符串列表的函数largestPrefix
并在元组中返回列表中两个相邻字符串的最长前缀。元组的第一个元素是前缀的长度。
a.e。:largestPrefix ["a","abca","bca","bcadabca","ca","cdabca"] => (3,"bca")
我已经为两个Stings构建了一个函数,但是不知道如何在列表列表中使用它。为了确保邻接,我考虑使用它:
prefix:: String -> String -> String
prefix (x:xs) (y:ys) | x:xs == "" = ""
| y:ys == "" = ""
| x == y = x:prefix xs ys
| otherwise = ""
答案 0 :(得分:-1)
所以我稍微清理了你的功能并添加了以下想法:
如果你编写一个函数,将一个运算符应用于每两对连续的列表(pairwise
),那么你应该能够完成你的工作:
pairwise :: (a -> a -> b) -> [a] -> [b]
pairwise f (x:xs@(y:_)) = f x y : pairwise f xs
pairwise _ _ = []
prefix:: String -> String -> String
prefix (x:xs) (y:ys)
| x == y = x:prefix xs ys
| otherwise = ""
prefix _ _ = ""
这是一个例子:
λ> pairwise prefix ["a","abca","bca","bcadabca","ca","cdabca"]
["a","","bca","","c"]
所以也许有人不高兴,因为我没有解决所有问题,所以你去了:
largestPrefix :: [String] -> (Int, String)
largestPrefix xs = maximumBy (compare `on` length . snd) $ zip [1..] (pairwise prefix xs)
你必须将其导入工作:
import Data.List (maximumBy)
import Data.Function (on)
λ> largestPrefix ["a","abca","bca","bcadabca","ca","cdabca"]
(3,"bca")