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

Fop*_*tin 116 haskell concat list

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

> foobar " " ["is","there","such","a","function","?"]
["is there such a function ?"]
Run Code Online (Sandbox Code Playgroud)

谢谢你的回复!

Nik*_* B. 208

是的,:

Prelude> import Data.List
Prelude Data.List> intercalate " " ["is","there","such","a","function","?"]
"is there such a function ?"
Run Code Online (Sandbox Code Playgroud)

intersperse 有点笼统:

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

此外,对于您想要与空格字符连接的特定情况,还有unwords:

Prelude> unwords ["is","there","such","a","function","?"]
"is there such a function ?"
Run Code Online (Sandbox Code Playgroud)

unlines工作方式类似,只是字符串使用换行符进行内爆,并且还会在末尾添加换行符.(这使得序列化文本文件非常有用,每个POSIX标准结尾必须有一个尾随换行符)

  • @CMCDragonkai不确定你究竟是指什么,但是,这些函数都允许任意字符串作为分隔符和元素.例如,`intercalate',"["some","","string"] ="some ,, string"`和`intercalate""["foo","bar"] ="foobar"` (3认同)
  • “ unlines”会在每行中添加一个换行符,即“ unlines [“ A”,“ B”] =“ A \ nB \ n”`,因此它与插值不同。 (2认同)

Ily*_*mov 7

使用foldr写一行字并不难

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

  • 对此添加描述会很有帮助;有人将其标记为低质量。 (6认同)