我希望能够将字符串列表展平,但有额外的要求。例如:
[["My","Name","is"],["John","Doe"]]
输出结果应为:
My name is \nJohn Doe
我尝试使用concat函数,但仍然没有成功。
谢谢。
我希望能够将字符串列表展平,但有额外的要求。例如:
[["My","Name","is"],["John","Doe"]]
输出结果应为:
My name is \nJohn Doe
我尝试使用concat函数,但仍然没有成功。
谢谢。
unwords :: [String] -> String
将一组 String
转换为单个 String
,然后使用 intercalate :: [a] -> [[a]] -> [a]
将这些行用分隔符连接在一起,例如:tolines :: [[String]] -> String
tolines = intercalate "\n" . map unwords
unlines
可以作为 intercalate "\n"
的替代方案,值得一提。 - bradrnunlines
会在末尾添加一个额外的'\n'
。虽然这本身并不是问题。 - Willem Van Onsem结合@John F Miller的答案,您只需要进行插入和添加所需元素,并使用concatMap:
import Data.List
ls = [["My","Name","is"],["John","Doe"]]
rs = concatMap (intercalate " ") (insertAt 1 ["\n"] ls)
insertAt _ _ [] = []
insertAt 0 e xs = e:xs
insertAt n e (x:xs) = x : (insertAt (n-1) e xs)
main = do
putStrLn rs
$> My Name is
John Doe
另一种方法是@luqui提出的评论,但我认为应该考虑:
rs = intercalate " " . intercalate ["\n"] $ ls
intercalate "\n" . map (intercalate " ")
怎么样? - luqui
"\n"
,您可以将intercalate "\n"
替换为unlines
。 - Antal Spector-Zabusky