If I force Haskell to infer the type of a number I'll get Num a => a
. For example:
Prelude> :t 1
1 :: Num a => a
But what does a => a
mean?
1 :: Num a => a
means that 1
has some type a
, where a
is an instance of the Num
typeclass. Note that Num
is not a type, but a typeclass, which describes common properties of various types. The Num
typeclass, for example, describes types that are numeric, and so support basic arithmetic. The native machine integer type Int
is an instance of Num
, as is the arbitrary-sized Integer
, the floating point type Double
, and even the rational number type Rational
.
a => a
doesn't mean anything. The complete phrase is Num a => a
. This means "a" is an instance of the Num
type class.
You could also read it as (Num a) => a
. It provides a context to say that a
is numerical.
However, it is not the type of a
; it just says that a
should be in the Num
type class .
Type classes are a little like interfaces in object-oriented programming, in that they define certain behaviours, without defining a
in detail.
Note that there is a difference between ->
and =>
. The first is used for the function signature; the second is used to show type classes.
The typing 1 :: Num a => a
means "1
is of type a
, for all types a
in typeclass Num
". More succintly, it means "1
is of any numeric type".
Because of this typing, you can pass 1
to any function requiring any numeric type, such as Int
, Double
, etc.
Extending your example a bit, we also have [1,2,3] :: Num a => [a]
. This means "[1,2,3]
is a list of values of type a
, for all types a
in typeclass Num
". In other words, "[1,2,3]
is a list of values of any numeric type".
Expression 1::Num a => a
can be broken down in 3 parts for reading/understanding purposes.
Let's build step by step :
1 ::
says 1 has the type of
c :: Char
says c has the type of Char
Everything before => is a "class constraint",so inserting Num a
between :: and =>
i.e. 1 :: Num a => a
says "1 has the type of a
, but not just any type but with a class constraint where a
is a member of Num class.