Haskell Flatten字符串列表

Rah*_*mat 4 haskell functional-programming list

我想展平字符串列表,但有其他要求。例

[["My","Name","is"],["John","Doe"]]

输出: My name is \nJohn Doe

我尝试使用concat函数,但还是没有运气

谢谢

Wil*_*sem 7

您可以使用unwords :: [String] -> String将的列表String转换为单个String,然后使用intercalate :: [a] -> [[a]] -> [a]中间的分隔符将行连接在一起,例如:

tolines :: [[String]] -> String
tolines = intercalate "\n" . map unwords
Run Code Online (Sandbox Code Playgroud)


Joh*_*ler 6

您要查找的功能称为intercalate,它存在于中Data.List。您将不得不使用两次。首先在内部列表的每个单词之间添加一个空格,然后再次\n在外部列表之间添加一个空格。 fmap是你的朋友。

  • 可能值得一提的是`unlines`来代替“ internate” \ n“`。 (5认同)
  • @bradm:`unlines`将在末尾添加一个额外的''\ n'`。当然,这本身并不是问题。 (2认同)