这是两段代码.
工作:
joins :: [String] -> String -> String
joins [] _ = ""
joins [x] _ = x
joins xs d = head xs ++ d ++ (joins (tail xs) d)
Run Code Online (Sandbox Code Playgroud)
不工作:
joins :: [String] -> String -> String
joins [] _ = ""
joins [x] _ = x
joins [x:xs] d = x ++ d ++ (joins xs d)
Run Code Online (Sandbox Code Playgroud)
后者的错误日志是:
test.hs:4:18:
Couldn't match expected type `[Char]' with actual type `Char'
In the first argument of `(++)', namely `x'
In the expression: x ++ d ++ (joins xs d)
In an equation for `joins':
joins [x : xs] d = x ++ d ++ (joins xs d)
test.hs:4:35:
Couldn't match type `Char' with `[Char]'
Expected type: [String]
Actual type: [Char]
In the first argument of `joins', namely `xs'
In the second argument of `(++)', namely `(joins xs d)'
In the second argument of `(++)', namely `d ++ (joins xs d)'
Run Code Online (Sandbox Code Playgroud)
我在这里错过了什么?
使用括号,而不是括号:
-- vvvvvv
joins (x:xs) d = x ++ d ++ (joins xs d)
Run Code Online (Sandbox Code Playgroud)
该模式[x:xs]仅与长度为1的列表匹配,其单个元素是非空列表x:xs.
因为你的是一个字符串列表,[x:xs]匹配["banana"](where x='b', xs="anana"),with ["a"](x='a', xs="")但不是with ["banana", "split"]和with [""].
这显然不是你想要的,所以使用简单的括号.
(顺便说一句,... ++ (joins xs d)不需要括号:函数应用程序比Haskell中的任何二元运算符绑定更多.)