Reputation: 3939
Can anyone please explain why,
Prelude> let a = 1
Prelude> :type a
a :: Integer
Prelude> :type 1
1 :: Num a => a
Why a is an Integer
and 1
is a Num
?
I can understand why 1+2
would be Num
. But why 1
?
Thanks in advance.
Upvotes: 1
Views: 193
Reputation: 120751
That 1
is just a general Num
instance, not any particular one, is perfectly reasonable and one of the great things about Haskell's type classes. This allows you to use integral literals in any context from actual integers to complex numbers to infinite-dimensional Hilbert-space operators, never having to bother about conversions or horribly ugly "7.0
" (or worse) literals that you find so often in other languages.
A better question would be: why is a
not also such a general instance, but a concrete Integer
type? That has to do with the dreaded monomorphism restriction. As shown by shang, you can switch that off; but in GHCi it's actually sometimes convenient to have the compiler make fixed choices for you, because you usually don't want to bother writing type signatures there.
In Haskell source files, the monomorphism restriction is basically just an artifact, as the Wiki article says nobody is really content with it.
Upvotes: 5
Reputation: 24832
This is just an artifact of how the type inference works in the interactive prompt. All numeric literals are polymorphic for any a
that is an instance of the Num
typeclass, but in the GHCi prompt any let
binding without an explicit signature is inferred with a monomorphic type (more details here).
You can make GHCi infer the more general type by setting
Prelude> :set -XNoMonomorphismRestriction
Prelude> let a = 1
Prelude> :type a
a :: Num a => a
Upvotes: 13