Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't GHC complain when number constant out of range

Tags:

haskell

GHC silently ignores out-of-range bits in numerical constants.

This behavior led me to wrestle with a rather strange bug today:

[0..256]::[Word8] -- evaluates to [0]!

I know what caused this bug (256 == 0 in a rot256 world).... I am interested in why GHC/Haskell was designed not to complain about it at compile time.

(This behavior is true for Int also- for instance, 18446744073709551617::Int = 1).

I've grown used to Haskell catching trivial compile time issues, and I was surprised when I had to track this down.

like image 293
jamshidh Avatar asked Dec 17 '13 21:12

jamshidh


1 Answers

I suspect the honest answer is "because nobody implemented it yet". But I think there's another layer to that answer, which is that there are some subtle design issues.

For example: how should we know that 256 is out of range for Word8? Well, I suppose one answer might be that the compiler could notice that Word8 is an instance of all three of Integral, Ord, and Bounded. So it could generate a check like

(256 :: Integer) > fromIntegral (maxBound :: Word8)

and evaluate this check at compile time. The problem is that all of a sudden we are running potentially user-written code (e.g. maxBound, fromIntegral, and (>) presumably all come from instance declarations that can be written by a programmer) at compile time. That can be a bit dangerous -- since it's impossible to tell if we'll ever get an answer! So at the very least you would want this check to be off by default, and presumably at least as hard to turn on as Template Haskell is.

On the other hand, it might also be possible to just build in a handful of instances that we "trust" -- e.g. Word8 and Int, as you say. I would find that a bit disappointing, though perhaps such a patch would not be rejected.

like image 103
Daniel Wagner Avatar answered Nov 24 '22 14:11

Daniel Wagner