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

前端 未结 1 1515
傲寒
傲寒 2021-01-28 15:29

Does anyone know why this code fails in GHCI?

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

:70:1:
    No ins         


        
相关标签:
1条回答
  • 2021-01-28 15:58

    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
    
    0 讨论(0)
提交回复
热议问题