Reputation: 39356
This is probably not possible, since I already checked the list of all GHC extensions and this is not in there, but I thought I'd ask just in case.
Is there any way to make it so that 2
has type Int
(or Integer
) rather than the usual Num a => a
?
(The reason I'd like this behavior is that it makes error messages clearer and type inference more likely to be possible (esp with type classes). I could always write (2::Int) everywhere but I'd rather the "more safe" behavior be the less explicit one)
Upvotes: 11
Views: 1669
Reputation: 8153
I think I should add "default()" to these answers, though I think gatoatigrado mentioned it in passing. The Haskell 98 standard has a section 4.3.4 which eventually describes how to alter some defaulting of Num a => a values. The implicit defaulting order is given by
default (Integer, Double)
and can be changed, e.g. by putting
default (Int)
or
default ()
in the source file.
Upvotes: 4
Reputation: 77374
There is a (slightly abusive and inconvenient) way to do this using GHC extensions.
{-# LANGUAGE RebindableSyntax #-}
import qualified Prelude as P
import Prelude hiding (Num(..))
fromInteger :: Integer -> Integer
fromInteger = id
In GHCi:
> :set -XRebindableSyntax
> :t 2
2 :: Integer
With the RebindindableSyntax
extension enabled, GHC will use whatever fromInteger
is in scope to handle numeric literals. The only constraint is that it must take an argument of type Integer
(actually, even this isn't required, but if it doesn't you'll get a type error from numeric literals).
Note that, because the standard fromInteger
is part of the Num
class, you may need to hack some things around to get things working properly.
Upvotes: 14