这里有两段代码。
工作:
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)'
我在这里错过了什么?
最佳答案
使用圆括号,而不是方括号:
-- 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=""
) 但不使用 ["banana ", "split"]
也不与 [""]
一起使用。
这显然不是您想要的,因此请使用普通括号。
(顺便说一句,...++ (joins xs d)
中的括号是不需要的:函数应用程序比 Haskell 中的任何二元运算符绑定(bind)更多。)
关于Haskell 头/尾与模式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35465539/