No instance for (Fractional a0) arising from a use of ‘it’

这一生的挚爱 提交于 2020-01-07 03:03:11

问题


Does anyone know why this code fails in 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:


Just use div:

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

Notice the types of the operators:

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

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

/ is for fractional numbers div for integrals ones

If you need floating point result use (**) operator instead of (^):

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

Mind the types once more:

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

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


来源:https://stackoverflow.com/questions/34650949/no-instance-for-fractional-a0-arising-from-a-use-of-it

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!