Recent versions of ghc
will warn you if an integer literal is outside a given type's range. For example:
$ ghci >>> let x = 330492039485 :: Data.Word.Word8 <interactive>:2:9: Warning: Literal 330492039485 is out of the GHC.Word.Word8 range 0..255
However, ghc
will not warn about negative numeric literals for Data.Word
types. Instead, it underflows (intentionally, according to the documentation):
>>> let x = -1 :: Data.Word.Word8 >>> x 255
Are there any types that will warn about negative literals or is there a way I can create my own custom type that does warn?
An int is signed by default, meaning it can represent both positive and negative values. An unsigned is an integer that can never be negative. If you take an unsigned 0 and subtract 1 from it, the result wraps around, leaving a very large number (2^32-1 with the typical 32-bit integer size).
An unsigned integer is a 32-bit datum that encodes a nonnegative integer in the range [0 to 4294967295]. The signed integer is represented in twos complement notation. The most significant byte is 0 and the least significant is 3.
Unsigned int data type in C++ is used to store 32-bit integers. The keyword unsigned is a data type specifier, which only represents non-negative integers i.e. positive numbers and zero.
There is no difference. unsigned and unsigned int are both synonyms for the same type (the unsigned version of the int type).
By default, a literal like -1
is desugared to negate (fromInteger 1)
. There is however a language extension NegativeLiterals
that causes it to desugar as fromInteger (-1)
instead. If you enable that you do get a warning:
Prelude> :m +Data.Word Prelude Data.Word> :set -W Prelude Data.Word> :set -XNegativeLiterals Prelude Data.Word> -1 :: Word <interactive>:74:1: Warning: Literal -1 is out of the Word range 0..18446744073709551615 18446744073709551615 Prelude Data.Word>
Alternatively, you could make your own type that redefined negate
, but then you would presumably only get a runtime error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With