连接字符串列表,使用foldl Haskell在两者之间添加分隔符

我有一个函数,旨在将列表中的字符串组合在一起,在每个字符串之间添加一个分隔符,并使用foldl输出单个字符串。这是我的功能,以及该功能的某些预期行为-它无法正常工作,我不确定为什么。

-- | `sepconcat sep [s1,...,sn]` returns `s1 ++ sep ++ s2 ++ ... ++ sep ++ sn`
--
-- >>> sepconcat "---" []
-- ""
--
-- >>> sepconcat "," ["foo","bar","baz"]
-- "foo,bar,baz"
--
-- >>> sepconcat "#" ["a","b","c","d","e"]
-- "a#b#c#d#e"

sepconcat :: String -> [String] -> String
sepconcat sep []     = ""
sepconcat sep (x:xs) = foldLeft f base l
  where
    f a x            = a ++ sep ++ x
    base             = ""
    l                = xs
h0712027 回答:连接字符串列表,使用foldl Haskell在两者之间添加分隔符

我认为您可以通过检查第一个参数是否为空字符串并进行相应处理来简单地解决此问题

sepConcat sep = foldl (\x y -> if x == "" then y else x ++ sep ++ y) ""
-- or
sepConcat sep = foldl combine ""
  where combine "" x = x
        combine x y = x ++ sep ++ y

,

最大的问题是您的模式匹配:

sepConcat sep []     = ""
sepConcat sep (x:xs) = foldLeft f base l

您不需要在[](x:xs)中再次划分模式,因为 foldl folder 会同时照顾案例。这是foldl可以定义为递归列出的方式:

foldLeft :: (b -> a -> b) -> b -> [a] -> b
foldLeft f base []     = base
foldLeft f base (x:xs) = f (foldLeft f base xs) x

您只需要正确应用这两种情况:

sepConcat :: String -> [String] -> String
sepConcat sep xs = foldLeft (\rs s ->
 if null rs 
 then s ++ rs
 else s ++ sep ++ rs) "" xs

这里空列表的大小写为"",该函数用于列表的递归大小写

以您的示例为例:

sepConcat "," ["foo","bar","baz"]
=> "foo,bar,baz"
本文链接:https://www.f2er.com/3147825.html

大家都在问