通过使用折叠函数(无递归)将分隔符放在它们之间,将列表中的字符串连接成单个字符串

Joining Strings from List into a Single String by Putting Separator in Between Them Using a Fold Function (No Recursion)

我们应该在 Haskell 中创建一个函数,它接受一个字符串(分隔符)和一个字符串列表,并通过在它们之间放置分隔符将它们连接成一个字符串。我们不允许使用递归,我们必须使用折叠函数。

示例如下:

*Main> join ", " ["one","two","three"]
"one, two, three"
*Main> join "+" ["1","2","3"]
"1+2+3"
*Main> join "X" ["abc"]
"abc"
*Main> join "X" []
""

现在,这是我的代码:

join :: String -> [String] -> String
join _ [] = ""
join a xs = foldr1 (concat) xs
  where
    concat b c = b ++ a ++ c

我的代码适用于前两个测试用例,但当我必须处理 "X" 分隔符时会产生错误。

错误信息如下:

*Main> "X" []

<interactive>:190:1: error:
    • Couldn't match expected type ‘[a0] -> t’
                  with actual type ‘[Char]’
    • The function ‘"X"’ is applied to one argument,
      but its type ‘[Char]’ has none
      In the expression: "X" []
      In an equation for ‘it’: it = "X" []
    • Relevant bindings include it :: t (bound at <interactive>:190:1)

*Main> "X" ["abc"]

<interactive>:191:1: error:
    • Couldn't match expected type ‘[[Char]] -> t’
                  with actual type ‘[Char]’
    • The function ‘"X"’ is applied to one argument,
      but its type ‘[Char]’ has none
      In the expression: "X" ["abc"]
      In an equation for ‘it’: it = "X" ["abc"]
    • Relevant bindings include it :: t (bound at <interactive>:191:1)

我不太确定是什么导致了这些错误。任何帮助将不胜感激。谢谢

简而言之:您没有调用函数。在示例情况下,调用 join 函数:

*Main> <b>join</b> ", " ["one","two","three"]
"one, two, three"
*Main> <b>join</b> "+" ["1","2","3"]
"1+2+3"
*Main> <b>join</b> "X" ["abc"]
"abc"
*Main> <b>join</b> "X" []
""

如果你在shell中写"X" ["abc"],Haskell的目标是用"X"函数执行函数应用,但是由于String是不是函数,类型不匹配。

如果你调用函数,你会得到:

Prelude> :{
Prelude| join :: String -> [String] -> String
Prelude| join _ [] = ""
Prelude| join a xs = foldr1 (concat) xs
Prelude|   where
Prelude|     concat b c = b ++ a ++ c
Prelude| :}
Prelude> join ", " ["one", "two", "three"]
"one, two, three"
Prelude> join "+" ["1", "2", "3"]
"1+2+3"
Prelude> join "X" ["abc"]
"abc"
Prelude> join "X" []
""