【发布时间】:2015-05-25 19:46:21
【问题描述】:
haskell 的新人在这里。我正在尝试更好地编写类型签名,而这个简单的签名并不想工作。我想知道为什么:
average :: Num a => [a] -> a
average ns = sum ns `div` length ns
Average 应该取任意数字并返回某个数字。但是我得到了错误
test.hs 11:27:
Couldn't match expected type 'a' with actual type 'Int'
'a' is a rigid type variable bound by
the type signature for average :: Num a => [a] -> a
at test.hs:10:12
Relevant bindings include
ns:: [a] (bound at test.hs:11:9)
average :: [a] -> a (bound at test.hs:11:1)
In the second argument of 'div' namely 'length ns'
In the expression: sum ns `div ` length ns
这似乎是在说长度没有达到它的预期。任何人都可以帮忙吗?
【问题讨论】:
-
这是因为
length ns是Int但div适用于Integral a => a -> a -> a- 试试average ns = sum nsdiv` (fromIntegral $ length ns)` - 它应该可以工作 -
但在小事上:
div无论如何都需要Integral! -
length :: [q] -> Int所以average :: [Int] -> Int.
标签: haskell types type-signature