Exp x in Haskell and type signature

I defined a custom exponent function exp'in GHCi as:

let exp' x = sum $ take 100 [(x**k) / factorial k | k <- [0..]]

which gives the following type signature:

#> :t exp'
exp' :: (Enum a, Floating a) => a -> a

However, I would expect it to match the function exp, i.e.

#> :t exp
exp :: Floating a => a -> a

Can someone explain the type restriction Enum a => afor my function exp'? Why is it not easy Floating a => a?

Thank.

+4
source share
2 answers

It comes from k <- [0..]- that desugars uses a class Enum.

It then propagates into a signature of the final type, because you use (**)for exponentiality, which expects its arguments to be of the same type:

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

, (^):

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

factorial k - fromIntegral:

exp' x = sum $ take 100 [(x^k) / fromIntegral (factorial k) | k <- [0..]]

, , , , ( ), .

( ), (**), fromIntegral Int , :

let exp' x = sum $ take 100 [(x**fromIntegral k) / fromIntegral (factorial k)
                                                        | k <- [0..]]
+6

[0..]

enumFrom 0

enumFrom Enum a => a -> [a], , k .

+1

Source: https://habr.com/ru/post/1546496/


All Articles