【发布时间】:2012-02-13 15:06:26
【问题描述】:
我想在 Haskell 中做一个简单的平均(mean)函数,所以我在 ghci 中尝试了以下方法:
ghci> let avg xs = (sum xs) / (length xs)
它会抛出以下错误:
No instance for (Fractional Int)
arising from a use of `/'
Possible fix: add an instance declaration for (Fractional Int)
In the expression: (sum xs) / (length xs)
In an equation for `avg': avg xs = (sum xs) / (length xs)
所以,我决定尝试以下方法来分解它:
ghci> let a = (sum [1,2])
ghci> let b = (length [1,2])
一切都很好。
然后我尝试了以下
ghci> a/b
我收到以下错误:
Couldn't match expected type `Integer' with actual type `Int'
In the second argument of `(/)', namely `b'
In the expression: a / b
In an equation for `it': it = a / b
那么,在 Haskell 中 Integer 和 Int 不同吗? - 如果是这样,我怎样才能使原来的功能工作?
【问题讨论】:
-
需要更多
fromIntegral。 =)