Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an unsigned integer type that will warn about negative literals?

Tags:

haskell

ghc

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?

like image 388
Gabriella Gonzalez Avatar asked Oct 26 '14 14:10

Gabriella Gonzalez


People also ask

What happens when unsigned int goes negative?

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).

What is an unsigned integer?

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.

What is an unsigned integer in C++?

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.

Is unsigned the same as unsigned int?

There is no difference. unsigned and unsigned int are both synonyms for the same type (the unsigned version of the int type).


1 Answers

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.

like image 192
Ørjan Johansen Avatar answered Sep 28 '22 19:09

Ørjan Johansen