这是我的代码:
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/