是否有一个函数可以使用分隔符连接列表的元素? 例如:
> foobar " " ["is","there","such","a","function","?"]
["is there such a function ?"]
感谢您的回复!
答案 0 :(得分:196)
是的,there is:
Prelude> import Data.List
Prelude Data.List> intercalate " " ["is","there","such","a","function","?"]
"is there such a function ?"
intersperse
有点笼统:
Prelude> import Data.List
Prelude Data.List> concat (intersperse " " ["is","there","such","a","function","?"])
"is there such a function ?"
此外,对于您想要加入空格字符的特定情况,还有unwords
:
Prelude> unwords ["is","there","such","a","function","?"]
"is there such a function ?"
unlines
的工作方式类似,只是字符串使用换行符进行内爆,并且还会在末尾添加换行符。 (这使得序列化文本文件很有用,每个POSIX标准必须以尾随换行符结束)
答案 1 :(得分:3)
如果有人感兴趣,还可以使用一些其他的散布和插入实现方案:
myIntersperse :: a -> [a] -> [a]
myIntersperse _ [] = []
myIntersperse e xs = init $ xs >>= (:[e])
myIntercalate :: [a] -> [[a]] -> [a]
myIntercalate e xs = concat $ myIntersperse e xs
xs >>= f
等效于concat (map f xs)
。
答案 2 :(得分:2)
joinBy sep cont = drop (length sep) $ concat $ map (\w -> sep ++ w) cont
答案 3 :(得分:2)
使用foldr编写单行并不难。
join sep xs = foldr (\a b-> a ++ if b=="" then b else sep ++ b) "" xs
join " " ["is","there","such","a","function","?"]
答案 4 :(得分:1)
如果您想编写自己的intercalate
和intersperse
版本:
intercalate :: [a] -> [[a]] -> [a]
intercalate s [] = []
intercalate s [x] = x
intercalate s (x:xs) = x ++ s ++ (intercalate s xs)
intersperse :: a -> [a] -> [a]
intersperse s [] = []
intersperse s [x] = [x]
intersperse s (x:xs) = x : s : (intersperse s xs)