如何理解这个class类型的错误告诉我我用错了类型?
How to understand this type class error of telling me I use the wrong type?
这是我计算一列数字的平均值的函数
arithMean :: (Fractional a) => [a] -> a
arithMean list = (foldr (+) 0 list)/ (length list)
然而,它引发了以下错误
HigherOrder.hs:10:39: error:
? Couldn't match expected type ‘a’ with actual type ‘Int’
‘a’ is a rigid type variable bound by
the type signature for:
arithMean :: forall a. Fractional a => [a] -> a
at HigherOrder.hs:9:1-39
? In the second argument of ‘(/)’, namely ‘(length list)’
In the expression: (foldr (+) 0 list) / (length list)
In an equation for ‘arithMean’:
arithMean list = (foldr (+) 0 list) / (length list)
? Relevant bindings include
list :: [a] (bound at HigherOrder.hs:10:11)
arithMean :: [a] -> a (bound at HigherOrder.hs:10:1)
关于这个错误,我很困惑为什么它强制我将"list"更改为[Int],我认为无论是什么类型,它都应该有效
此外,我认为当我尝试使用 "length" 函数时可能发生了一些事情,因为当我在下面编写这段代码时,它起作用了
arithMean :: (Fractional a) => [a] -> a
arithMean list = (foldr (+) 0 list)
(/) :: Fractional a => a -> a -> a
means that the numerator and denominator need to be both need to have the same Fractional
类型的类型。
length :: [a] -> Int
但是将可折叠映射到 Int
。一个 Int
是 不是 一个 Fractional
类型。
您可以使用 fromIntegral :: (Integral a, Num b) :: a -> b
here to convert the Int
to an type that is a member of the Num
类型类。
arithMean :: (Fractional a, Foldable f) => f a -> a
arithMean list = sum list / <b>fromIntegral</b> (length list)
我们可以在这里使用sum :: (Foldable f, Num a) => f a -> a
代替foldr (+) 0 list
。
这是我计算一列数字的平均值的函数
arithMean :: (Fractional a) => [a] -> a
arithMean list = (foldr (+) 0 list)/ (length list)
然而,它引发了以下错误
HigherOrder.hs:10:39: error:
? Couldn't match expected type ‘a’ with actual type ‘Int’
‘a’ is a rigid type variable bound by
the type signature for:
arithMean :: forall a. Fractional a => [a] -> a
at HigherOrder.hs:9:1-39
? In the second argument of ‘(/)’, namely ‘(length list)’
In the expression: (foldr (+) 0 list) / (length list)
In an equation for ‘arithMean’:
arithMean list = (foldr (+) 0 list) / (length list)
? Relevant bindings include
list :: [a] (bound at HigherOrder.hs:10:11)
arithMean :: [a] -> a (bound at HigherOrder.hs:10:1)
关于这个错误,我很困惑为什么它强制我将"list"更改为[Int],我认为无论是什么类型,它都应该有效
此外,我认为当我尝试使用 "length" 函数时可能发生了一些事情,因为当我在下面编写这段代码时,它起作用了
arithMean :: (Fractional a) => [a] -> a
arithMean list = (foldr (+) 0 list)
(/) :: Fractional a => a -> a -> a
means that the numerator and denominator need to be both need to have the same Fractional
类型的类型。
length :: [a] -> Int
但是将可折叠映射到 Int
。一个 Int
是 不是 一个 Fractional
类型。
您可以使用 fromIntegral :: (Integral a, Num b) :: a -> b
here to convert the Int
to an type that is a member of the Num
类型类。
arithMean :: (Fractional a, Foldable f) => f a -> a
arithMean list = sum list / <b>fromIntegral</b> (length list)
我们可以在这里使用sum :: (Foldable f, Num a) => f a -> a
代替foldr (+) 0 list
。