Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Haskell 如何将mergeWords函数扩展到任意数量的字符串?_Haskell_Functional Programming_Purely Functional - Fatal编程技术网

Haskell 如何将mergeWords函数扩展到任意数量的字符串?

Haskell 如何将mergeWords函数扩展到任意数量的字符串?,haskell,functional-programming,purely-functional,Haskell,Functional Programming,Purely Functional,下面是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” "hw\neo\nlr\nll\nod\n" 我不知道

下面是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”

"hw\neo\nlr\nll\nod\n"

我不知道如何将此扩展到字符串列表。与将其应用于3个字符串一样,应首先获取每个字符串的第一个字符,然后放置“\n”,然后放置第二个字符,依此类推

如果分步骤进行,听起来相当容易:

cutWords :: [String] -> [[String]]    -- ["ab", "cd", "e"] -> [["a", "c", "e"], ["b", "d"]]
concatWord :: [String] -> String       -- ["a", "c", "e"] -> "ace\n"
concatWords :: [String] -> String    -- use mergeWord on all of them
最有趣的部分当然是
cutWords
部分。你想要的是一种类似拉链的行为,如果我们“安全”尾部和头部,这会有所帮助:

head' (x:xs) = [x]
head' "" = ""

tail' (x:xs) = xs
tail' "" = ""
现在,我们可以实现我们的
剪切词
,确保及时停止:

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

难题是有效地将单词列表(一次一个字符)合并到带有尾随换行符的行中

mergeWords :: [String] -> String
我们需要一份清单,比如

[ "hello"
, "jim"
, "nice"
, "day"
]
并将其重新排列到给定位置的事物列表中

[ "hjnd"
, "eiia"
, "lmcy"
, "le"
, "o"
]
这就是库函数
transpose
的作用

然后我们需要制作一个字符串,将这些字符串作为行,用换行符分隔。这就是
取消线的作用

所以


我们完成了。

这取决于您的决定:如何推广函数。但是你的概括是有道理的,是的。我认为你的例子是错误的。这是在
“howdie”“world”
上调用它时的结果吗?很抱歉,将其更正为hello world的结果。我尝试使用类似于
映射头[“hello”,“world”]
的方法返回
“hw”
,但我无法进行递归。如何生成已删除h和w的列表并对其应用相同的映射头。请查看
Data.list
中的
transpose
。这是一个不错的解决方案,但我正在尝试自己编写转置函数。
mergeWords = unlines . transpose