如何在列表中正确执行Haskell模式匹配?

时间:2017-01-10 17:01:21

标签: haskell pattern-matching

我试图在this page底部完成Haskell练习。我正在努力的是#7。这就是问题所在:

定义一个使用分隔符值将列表列表连接在一起的函数。

这是类型签名:

-- file: ch03/Intersperse.hs
intersperse :: a -> [[a]] -> [a]

这就是它应该表现的方式:

ghci> :load Intersperse
[1 of 1] Compiling Main             ( Intersperse.hs, interpreted )
Ok, modules loaded: Main.
ghci> intersperse ',' []
""
ghci> intersperse ',' ["foo"]
"foo"
ghci> intersperse ',' ["foo","bar","baz","quux"]
"foo,bar,baz,quux"

所以这就是我想出来的:

intersperse :: a -> [[a]] -> [a]
intersperse a [] = ""
intersperse a [x] = x
intersperse a [x:xs] = x ++ a ++ (intersperse a xs)

但是我收到了这个错误:

intersperse.hs:4:24: error:
    • Couldn't match expected type ‘[a]’ with actual type ‘a’
      ‘a’ is a rigid type variable bound by
        the type signature for:
          intersperse :: forall a. a -> [[a]] -> [a]
        at intersperse.hs:1:16
    • In the first argument of ‘(++)’, namely ‘x’
      In the expression: x ++ a ++ (intersperse a xs)
      In an equation for ‘intersperse’:
          intersperse a [x : xs] = x ++ a ++ (intersperse a xs)
    • Relevant bindings include
        xs :: [a] (bound at intersperse.hs:4:18)
        x :: a (bound at intersperse.hs:4:16)
        a :: a (bound at intersperse.hs:4:13)
        intersperse :: a -> [[a]] -> [a] (bound at intersperse.hs:2:1)

我在Haskell真的很新,所以我真的不明白这个错误。我究竟做错了什么?

编辑:

有了这个:

intersperse :: a -> [[a]] -> [a]
intersperse a [] = []
intersperse a [x] = x
intersperse a (x:xs) = x ++ [a] ++ (intersperse a xs)

原来有一些错误。

1 个答案:

答案 0 :(得分:4)

模式[x:xs]仅与长度为1的列表匹配,其单个元素为非空(与x:xs匹配)。例如。它与[[1,2,3]]x=1以及xs=[2,3]匹配。它与[[1],[2,3]][][[]]不匹配。

您想要(x:xs)。这可以将[[1,2],[3],[4,5]]x=[1,2]xs=[[3],[4,5]]匹配。