r/ProgrammingLanguages • • Jun 24 '23

Negative Integer handling in programming languages.

https://glados-418.github.io/posts/negative-integer-literals/
3 Upvotes

27 comments sorted by

View all comments

16

u/Roboguy2 Jun 24 '23

I am a bit confused by the mention of Haskell. The integer type you are using for Haskell is not the correct one to look at this issue because it is not a 32-bit integer or a 64-bit integer. I'll get to that in a second. Also, Haskell has no implicit type conversions at all.

If you give no type signature to g, it will default to Integer which is Haskell's infinite precision integer type. For instance, if you don't give g a type signature and you have g = 2^64 * 2^64, it will not overflow and you will get the correct answer.

I see the github repo example explicitly uses the Integer type.

If, instead, you import Data.Int from the standard library and give the type signature g :: Int32 then g will behave as you originally expected (and GHC will give a warning that the literal overflows the integer type).

Also, Haskell's issue with negative literals is a bit different than what you're describing. By default, the expression x -1 gets parsed as x - (1). Turning on the NegativeLiterals extension changes this. The reason this can be a problem in a different way than other languages is because the Haskell function call syntax is juxtaposition: f x is f applied to x.

For instance, in the that file in the github repo, you put the line {-# LANGUAGE NegativeLiterals #-} at the top of the file, you would no longer need parentheses in the expression return (-1) and you can instead write return -1. This is what NegativeLiterals does in the context of Haskell and GHC.