这是两段代码。
工作:
joins :: [String] -> String -> String
joins [] _ = ""
joins [x] _ = x
joins xs d = head xs ++ d ++ (joins (tail xs) d)
不工作:
joins :: [String] -> String -> String
joins [] _ = ""
joins [x] _ = x
joins [x:xs] d = x ++ d ++ (joins xs d)
后者的错误日志是:
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)'
我在这里缺少什么?
答案 0 :(得分:5)
使用括号,而不是括号:
-- vvvvvv
joins (x:xs) d = x ++ d ++ (joins xs d)
模式[x:xs]
仅与长度为1的列表匹配,其单个元素是非空列表x:xs
。
由于您的是字符串列表,[x:xs]
与["banana"]
(其中x='b', xs="anana"
)匹配,["a"]
(x='a', xs=""
)但不匹配{{ 1}}也不与["banana", "split"]
。
这显然不是你想要的,所以请使用普通括号。
(顺便说一句,不需要[""]
中的括号:函数应用程序比Haskell中的任何二元运算符绑定更多。)