Converting Numbers
What does the type of number literals mean, e.g. 5 :: Num a => a
(or more verbosely: 5 :: forall a. Num a => a
)?
Read n :: Num a => a
as saying: n
has any type whatsoever, as long as that type is an instance of the Num
typeclass.
Haskell has a typeclass Num
for numbers which generalized across various concrete number types like Double
, Float
, Int
and Integer
.
Haskell will always give the most general typeclass that supports the numeric operations you are using:
repl example
> :t 5 + 3
5 + 3 :: Num a => a -- (1)!
> :t 5 / 3
5 / 3 :: Fractional a => a -- (2)!
> :t 5 ** 3
5 ** 3 :: Floating a => a -- (3)!
(+)
is an operation supported by theNum
typeclass.(/)
is an operation supported byFractional
, a class that inherits fromNum
(**)
is an operation supported byFloating
, a class that inherits fromNum
Like all universally quantified values, a value of type forall a. Num a => a
can be given as input to any function that takes an concrete number type:
repl example
> n = 5
> :t n
n :: Num a => a
> double = (\x -> x + x) :: Double -> Double
> double n
10