是否有任何 haskell 函数来连接列表和分隔符?

是否有一个函数将列表中的元素与分隔符连接起来? 例如:

> foobar " " ["is","there","such","a","function","?"]
["is there such a function ?"]

谢谢你的回复!

98545 次浏览

是的,有的:

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 标准末尾加一个新行)

joinBy sep cont = drop (length sep) $ concat $ map (\w -> sep ++ w) cont

如果你想写你自己版本的 intercalateintersperse:

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)

使用 Foldr 编写一行程序并不难

join sep xs = foldr (\a b-> a ++ if b=="" then b else sep ++ b) "" xs
join " " ["is","there","such","a","function","?"]

如果有人感兴趣的话,还有其他一些实现点缀和插入的想法:

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)