有没有一个函数可以用分隔符将列表中的元素连接起来?
例如:
> foobar " " ["is","there","such","a","function","?"]
["is there such a function ?"]
感谢任何回复!
> foobar " " ["is","there","such","a","function","?"]
["is there such a function ?"]
感谢任何回复!
是的,有这个函数:
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 标准中必须以一个尾随换行符结尾)
intercalate "," ["some", "", "string"] = "some,,string"
和 intercalate "" ["foo", "bar"] = "foobar"
。 - Niklas B.unlines
函数会给每一行添加一个换行符,比如 unlines ["A", "B"] = "A\nB\n"
,因此它与 intercalate
函数是不同的。请注意,翻译过程中不修改原意,也不提供额外的解释或其他内容。 - Kathy Van Stone使用foldr编写一行代码并不难。
join sep xs = foldr (\a b-> a ++ if b=="" then b else sep ++ b) "" xs
join " " ["is","there","such","a","function","?"]
join
,它接受一个分隔符和一个字符串列表。然后它使用匿名 lambda 函数在列表上应用 fold。在 (\a b-> a ++ if b=="" then b else sep ++ b)
中,a 是累加器,b 是列表中的下一个项目。折叠从 "" 开始。 - trevdev如果有人感兴趣,可以实现 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 >>= f
等同于 concat (map f xs)
。
joinBy sep cont = drop (length sep) $ concat $ map (\w -> sep ++ w) cont
intercalate
和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)
intersperse
不需要是 Strings
,但是 intercalate
至少需要是 Show
,如果你确实使用了 Show
,你肯定需要一个方法来处理它们并使用 String
s。我仍在适应 Haskell 如何处理混合中缀和前缀函数 / 运算符,如果我最终想要使用 $
,我更喜欢在混合时加括号。 - Zoey HewllShow
?至于语法,Haskell没有任何前缀运算符(除了“-”,它是一种可憎的东西),而函数应用比任何中缀运算符都紧密:x:s:intersperse s xs
是可以的(但如果你加上空格,它读起来会好得多:x : s : intersperse s xs
(我真的不明白为什么人们喜欢在 :
周围留出空格)。 - melpomene
unwords
函数。 - epsilonhalbe[a] -> (a -> b) -> [b]
会返回map
作为其第一个结果。 - gallais