【发布时间】:2014-07-22 02:57:07
【问题描述】:
media :: (Num a) => [a] -> a
media [] = 0
media lst = (head lst) + media (tail lst)
这是一个工作函数,它遍历一个数字列表并将每个元素与以下元素相加。
media2 :: (Num a) => [a] -> a
media2 str = (media str) / (length str)
第二个函数应该得到该总和并将其除以列表的长度,从而获得列表的算术平均值。但是编译器返回给我这个
src/Main.hs@6:29-6:39Could not deduce (a ~ Int)
from the context (Num a)
bound by the type signature for media2 :: Num a => [a] -> a
at /home/app/isolation-runner-work/projects/32614/src.207/Main.hs:6:1-39
`a' is a rigid type variable bound by
the type signature for media2 :: Num a => [a] -> a
at /home/app/isolation-runner-work/projects/32614/src.207/Main.hs:6:1
In the return type of a call of `length'
In the second argument of `(/)', namely `(length str)'
In the expression: (media str) / (length str)
我不明白我做错了什么,有人可以告诉我吗?
【问题讨论】:
-
它说
media str的类型为a,length str的类型为Int,您不能将其一分为二,因为它不能证明a实际上是Int. -
Haskell 已经有一个函数可以做
media所做的事情;它被称为sum。