Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Haskell can I make numeric literals not polymorphic by default?

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)

like image 958
Owen Avatar asked Jul 25 '11 06:07

Owen


1 Answers

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.

like image 57
C. A. McCann Avatar answered Oct 25 '22 05:10

C. A. McCann