list 是否有任何 haskell 函数将列表与分隔符连接起来?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9220986/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 01:47:08  来源:igfitidea点击:

Is there any haskell function to concatenate list with separator?

listhaskellconcat

提问by Fopa Léon Constantin

Is there a function to concatenate elements of a list with a separator? For example:

是否有使用分隔符连接列表元素的函数?例如:

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

Thanks for any reply!

感谢您的任何回复!

回答by Niklas B.

Yes, there is:

是的,

Prelude> import Data.List
Prelude Data.List> intercalate " " ["is","there","such","a","function","?"]
"is there such a function ?"

intersperseis a bit more general:

intersperse更笼统一点:

Prelude> import Data.List
Prelude Data.List> concat (intersperse " " ["is","there","such","a","function","?"])
"is there such a function ?"

Also, for the specific case where you want to join with a space character, there is unwords:

此外,对于您想要加入空格字符的特定情况,还有unwords

Prelude> unwords ["is","there","such","a","function","?"]
"is there such a function ?"

unlinesworks similarly, only that the strings are imploded using the newline character and that a newline character is also added to the end. (This makes it useful for serializing text files, which must per POSIX standard end with a trailing newline)

unlines工作原理类似,只是使用换行符对字符串进行内爆,并在末尾添加一个换行符。(这对于序列化文本文件很有用,根据 POSIX 标准,文本文件必须以尾随换行符结尾)

回答by Ilya Kharlamov

It's not hard to write one-liner using foldr

用foldr写单行不难

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

回答by Alexis

Some other ideas of implementations of intersperse and intercalate, if someone is interested:

如果有人感兴趣的话,还有一些实现 intersperse 和 intercalate 的其他想法:

myIntersperse :: a -> [a] -> [a]
myIntersperse _ [] = []
myIntersperse e xs = init $ xs >>= (:[e])

myIntercalate :: [a] -> [[a]] -> [a]
myIntercalate e xs = concat $ myIntersperse e xs

xs >>= fis equivalent to concat (map f xs).

xs >>= f相当于concat (map f xs)

回答by Alaya

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

回答by Zoey Hewll

If you wanted to write your own versions of intercalateand intersperse:

如果您想编写自己的intercalateand版本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)