下面是mergeWords函数。
mergeWords [] [] = []
mergeWords [] (y:ys) = y:'n':(mergeWords [] ys)
mergeWords (x:xs) [] = x:'n':(mergeWords xs [])
mergeWords (x:xs) (y:ys) = x:y:'n':(mergeWords xs ys)
如果应用于mergeWords "hello" "world"
它会给出
"hwneonlrnllnodn"
我不知道如何将其扩展到字符串列表。就像将其应用于 3 个字符串一样,应该首先采用每个字符串的第一个字符,然后输入"",然后输入第二个字符,依此类推。
这个难题实际上是将单词列表(一次一个字符(合并到带有尾随换行符的行中。
mergeWords :: [String] -> String
我们需要像这样的列表
[ "hello"
, "jim"
, "nice"
, "day"
]
并将其重新排列到给定位置的事物列表中
[ "hjnd"
, "eiia"
, "lmcy"
, "le"
, "o"
]
这就是库函数transpose
的作用。
然后我们需要创建一个字符串,将它们视为行,用换行符分隔。这就是unlines
所做的。
所以
mergeWords = unlines . transpose
我们完成了。
如果你分步执行,听起来相当容易:
cutWords :: [String] -> [[String]] -- ["ab", "cd", "e"] -> [["a", "c", "e"], ["b", "d"]]
concatWord :: [String] -> String -- ["a", "c", "e"] -> "acen"
concatWords :: [String] -> String -- use mergeWord on all of them
最有趣的部分当然是cutWords
部分。你想要的是一种类似zip的行为,为此,如果我们"安全"tail
并head
,这将有所帮助:
head' (x:xs) = [x]
head' "" = ""
tail' (x:xs) = xs
tail' "" = ""
现在我们可以 实施我们的cutWords
,确保我们及时停止:
cutWords xs = heads : rest
where
heads = map head' xs
tails = map tail' xs
rest = if any (/= "") tails then cutWords tails
else []
那么剩下的部分是微不足道的:
concatWord word = concat word ++ "n"
concatWords words = concatMap concatWord word