定义haskell的平均值

时间:2014-11-09 18:43:02

标签: haskell

如何使用类型[Float]定义均值,而不使用递归?也给出小数点后两位的答案。我是Haskell的新手,所以任何帮助都会非常感激。即mean :: [Float] -> Float

对于mean xs = sum xs / length xs,我得到以下内容:

 No instance for (Fractional Int)
   arising from a use of `/' at test.hs:8:10-27
 Possible fix: add an instance declaration for (Fractional Int)
 In the expression: sum xs / length xs
 In the definition of `mean': mean xs = sum xs / length xs

2 个答案:

答案 0 :(得分:6)

让我们看一下/

(/) :: Fractional a => a -> a -> a

如您所见,/的结果与操作数的类型相同。

现在让我们看一下length

length :: [a] -> Int

糟糕!您将整数传递给/。由于(忽略0)整数集未在除法下关闭,因此整数不会超载/

因此,首先必须将第二个操作数转换为浮点数:

mean :: [Float] -> Float
mean xs = sum xs / fromIntegral (length xs)

至于给出小数点后两位的答案,我将其留给负责将结果呈现给用户的代码。这不是mean的责任。

答案 1 :(得分:0)

如果您只想要两个小数点而不进行舍入,则可以使用div而不是/(您必须在结果中移动小数点...):< / p>

meanish xs = div (sum xs * 100) (length xs)