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

List 是否有任何haskell函数将列表与分隔符连接起来?,list,haskell,concat,List,Haskell,Concat,是否有一个函数用分隔符连接列表的元素? 例如: > foobar " " ["is","there","such","a","function","?"] ["is there such a function ?"] 谢谢你的回复 是的,: 更一般一点: Prelude> import Data.List Prelude Data.List> concat (intersperse " " ["is","there","such","a","function","?"]) "

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

> foobar " " ["is","there","such","a","function","?"]
["is there such a function ?"]
谢谢你的回复

是的,:

更一般一点:

Prelude> import Data.List
Prelude Data.List> concat (intersperse " " ["is","there","such","a","function","?"])
"is there such a function ?"
此外,对于要使用空格字符连接的特定情况,还有:


工作原理类似,只是字符串使用换行符内爆,并且换行符也添加到末尾。(这对于序列化文本文件非常有用,按照POSIX标准,文本文件必须以尾随换行符结尾)

如果您想编写自己版本的
插入
插入

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)

我知道lmgtfy的答案是错误的,但值得注意的是,在hoogle上搜索“String->[String]->String”会得到您想要的结果。对于连接空格,您还有
unwords
@sigfpe侧注释:如果另一种方法没有返回答案,您必须查找
[String]->String->String
,对吗?@LayGonzález搜索取决于排列。例如,搜索返回的第一个结果是
map
。其中任何一个可以处理可能的空字符串吗?@cmcdragokai不确定您到底指的是什么,但是是的,这些函数都允许任意字符串作为分隔符和元素。例如,
插入“,”[“some”,“string”]=“some”,“string”
插入“[“foo”,“bar”]=“foobar”
取消行为每行添加一个新行,即
取消行[“a”,“B”]=“a\nB\n”
,因此它与插入不同。@KathyVanStone,我想我从未尝试过,只是假设它的工作原理类似于
unwords
。很高兴在标准库中有一些普通的字符串和列表操作函数,很高兴您在这里发布了一个示例,因为在Haskell中很难找到这种日常编程的文档,为什么只限于字符串?此外,函数应用程序周围的参数是多余的。诚然,
intersperse
不必是
Strings
,但是
interlate
至少需要是
Show
,如果您确实使用了
Show
,那么无论如何,您都需要使用
String
来处理它们。我仍然习惯于Haskell如何处理混合中缀和前缀函数/运算符,我更喜欢在混合时使用括号,以防我最终想要使用
$
插入::[a]->[[a]]->[a]
-为什么
显示
?至于语法,Haskell没有任何前缀运算符(除了讨厌的
-
),函数应用程序绑定比任何中缀运算符都要紧密:
x:s:intersperses-xs
很好(但如果将空格放在:
x:s:intersperses-xs
(我真的不明白为什么人们喜欢省略
)周围的空格。对。我一直忘了处理字符串就是处理列表。
Show
是因为我假设你希望结果是
字符串。我的意思是“中缀和前缀函数/运算符”“前缀函数和中缀运算符”,但这还不清楚。一元
-
就是死亡。至于
s和其他中缀运算符,我是否使用空格在很大程度上取决于上下文,但我始终是局部一致的。例如,
(:)
在模式匹配中,从来没有空格,但在其他地方,这取决于是否用括号括起来以及我的心情。为其添加一个描述将是有益的;有人将其标记为低质量。
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)
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