使用'it'时没有(Fractional a0)的实例

时间:2016-01-07 09:00:09

标签: haskell

有人知道为什么这段代码在GHCI中失败了吗?

Prelude> let x = 4 in sum [(x^pow) / product[1.. pow] | pow <- [0.. 9]]

<interactive>:70:1:
    No instance for (Fractional a0) arising from a use of ‘it’
    The type variable ‘a0’ is ambiguous

1 个答案:

答案 0 :(得分:2)

只需使用div:

Prelude> let x = 4 in sum [(x^pow) `div` product[1.. pow] | pow <- [0.. 9]]
50

注意运营商的类型:

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

Prelude> :t div
div :: Integral a => a -> a -> a

/适用于积分数为div

如果需要浮点结果使用(**)运算符而不是(^):

Prelude> let x = 4 in sum [(x**pow) / product[1.. pow] | pow <- [0.. 9]]
54.15414462081129

再次记住这些类型:

Prelude> :t (^)
(^) :: (Integral b, Num a) => a -> b -> a

Prelude> :t (**)
(**) :: Floating a => a -> a -> a