这是我的代码:
test :: (Num a) => [a] -> a
test [] = 0
test [x:xs] = x + test xs
然而,当我通过 ghci as 运行它时: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:我知道这可以通过折叠轻松完成,但我正在尝试练习编写自己的类型签名。提前致谢!!