这是我计算数字列表的平均值的功能
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)
关于此错误,我对为什么迫使我将“列表”更改为[Int]感到非常困惑,我认为无论它是哪种类型,它都应该起作用
此外,我认为当我尝试使用“长度”函数时可能发生了某些事情,因为当我在下面编写此代码时,它可以工作
arithMean :: (Fractional a) => [a] -> a
arithMean list = (foldr (+) 0 list)
该类型的(/) :: Fractional a => a -> a -> a
手段的分子和分母需要既需要具有相同的Fractional
类型。
length :: [a] -> Int
但是将可折叠对象映射到Int
。一个Int
是不是一个Fractional
类型。
您可以fromIntegral :: (Integral a, Num b) :: a -> b
在此处使用将转换Int
为Num
typeclass成员的类型。
arithMean :: (Fractional a, Foldable f) => f a -> a
arithMean list = sum list / fromIntegral (length list)
除了在foldr (+) 0 list
这里使用,我们可以sum :: (Foldable f, Num a) => f a -> a
在这里使用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句