如何使用分隔符加入字符列表?

问题描述 投票:0回答:1

我基本上正在寻找与以下Python代码等效的Haskell:

' '.join(['_','a','b','1'])

我知道Python将它们视为字符串而不是字符,但是......我离题了。

MRE:

[if <some condition is true> then '#' else chr elem | elem <- lst] -- lst is [Integer] (appropriate Integer -> Int conversion function applied, but not specified here)

预期输出:

['#',' ','a',' ','b',... you get the idea]

我目前拥有的:

['#','a','b',...]

我能实现的最好成绩是:

concat [if <some condition is true> then "# " else [chr elem] ++ " " | elem <- lst]

这似乎有点矫枉过正。有没有更简单的方法来实现这一目标?

PS:

unwords
不需要
Char
s。

string list haskell char
1个回答
0
投票

intersperse
函数将在
Char
中的每对字符之间插入一个
String
(或者更一般地说,在列表
a
中的每对元素之间插入
[a]
类型的单个元素)。例如:

> intersperse ' ' ['a','b','c']
"a b c"
> intersperse ' ' "abc"
"a b c"

您还可以通过将函数

singleton
映射到列表上,将字符列表转换为单字符字符串列表,如下所示:

> map singleton ['a','b','c']
["a","b","c"]

这将允许您应用

unwords
,或使用
intercalate
在字符之间插入多字符字符串,如下所示:

> intercalate ", " $ map singleton ['a','b','c']
"a, b, c"
© www.soinside.com 2019 - 2024. All rights reserved.