Haskell 头/尾与模式匹配

标签 haskell

这里有两段代码。

工作:

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/

相关文章:

regex - Haskell中正则表达式的所有匹配项

haskell - Haskell 中的代码检测

haskell - 查看安装到 cabal 沙箱中的软件包的文档

Haskell 列表理解

c - hscurses 或 ncurses,使用哪一个?

Haskell - 在 QuickCheck 的帮助下进行 Parsec 测试

`otherwise` 函数中的 Haskell 非详尽模式

haskell - ghc 7.8.3 超时

list - groupBy 具有多个测试功能

function - Haskell 使用 $ 代替括号无效