0
votes

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
The (^) operator expects the exponent to be an integral value, but the (/) operator only works on non-integers.MathematicalOrchid

1 Answers

2
votes

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