haskell - 无法让类型签名适用于简单的递归函数

标签 haskell recursion

这是我的代码:

test :: (Num a) => [a] -> a
test []     = 0
test [x:xs] = x + test xs

然而,当我通过 ghci 作为 :l test 运行它时,我收到此错误:

[1 of 1] 编译 Main ( test.hs, 解释)
test.hs:3:7:
    Couldn't match type `a' with `[a]'
      `a' is a rigid type variable bound by
          the type signature for spew :: Num a => [a] -> a at test.hs:2:1
    In the pattern: x : xs
    In the pattern: [x : xs]
    In an equation for `spew': spew [x : xs] = x + spew xs
Failed, modules loaded: none.

尽量不要笑 :) 这是我第一次尝试 Haskell。任何帮助或解释都会很棒。

PS:我知道这可以通过折叠轻松完成,但我正在尝试练习编写自己的类型签名。提前致谢!!

最佳答案

你的意思是

test :: (Num a) => [a] -> a
test []     = 0
test (x:xs) = x + test xs -- note round brackets

带圆括号。
[x:xs]是一个包含一个元素的列表,它本身就是一个列表,而 (x:xs)是一个带有第一个元素的列表 x和尾部xs .

如果您输入 length (1:[1,1,1])你会得到 4,但如果你输入 length [1:[1,1,1]]你会得到 1 - 唯一的元素是一个列表。

关于haskell - 无法让类型签名适用于简单的递归函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16179415/

相关文章:

haskell - 在 Haskell 中将两个列表混在一起

list - 使用 foldr 在 haskell 中实现插入

java - 在 Java 中获取用户输入

django:使用保存后信号进行递归

javascript - 遍历相互引用的对象数组并将它们从字符串解析为对象

haskell - "function inside a functor"到底是什么意思

haskell - 如何重新分发 wxHaskell 应用程序?

haskell - 在Servant库中解密DataKind类型提升

java - 如何在二维数组中查找峰值中停止Java递归

保留变量值的Python递归函数