gpt4 book ai didi

haskell - 如何在列表上正确进行 Haskell 模式匹配?

转载 作者:行者123 更新时间:2023-12-02 15:25:37 24 4
gpt4 key购买 nike

我正在尝试完成 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)

事实证明,有一些问题。

最佳答案

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

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

关于haskell - 如何在列表上正确进行 Haskell 模式匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41574250/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com