Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In what cases does NegativeLiterals change behavior?

While describing the NegativeLiterals School of Haskell shows an example of how using the language extension might change the performance of some code and then says

Other examples might actually change behavior rather than simply be less efficient

After fooling around with the extension a bit I was not able to find any of these instances of behavior changes. I was only able to find the performance changes they were talking about and a few programs that will error with and without the extension.

What are these programs that change their behavior when the NegativeLiterals extension is enabled?

like image 335
Wheat Wizard Avatar asked Jan 15 '18 18:01

Wheat Wizard


2 Answers

The difference of negative literals is the difference of if we negate the integer then call fromInteger or call fromInteger then negate the type of the codomain. That is, fromInteger . negate is not the same as negate . fromInteger. I would expect this to happen when you are on the bounds of some type - one might saturate while another wraps.

For example I have a pretty trivially bad type:

data Bad = Bad Integer
    deriving (Show)

instance Num Bad where
    negate (Bad a) = Bad (a + 1)
    fromInteger = Bad

And the result:

*Main> (-1) :: Bad
Bad 2
*Main> :set -XNegativeLiterals
*Main> (-1) :: Bad
Bad (-1)
*Main>
like image 173
Thomas M. DuBuisson Avatar answered Oct 25 '22 16:10

Thomas M. DuBuisson


NegativeLiterals also changes how some expressions are parsed. Unary - is interpreted as an operator with the same precedence as binary - (i.e. 6), but with NegativeLiterals a - that is directly (without whitespace) followed by a number will be part of the literal. Here is an example of how this can make a difference:

>>> :set -XNoNegativeLiterals
>>> -1 `mod` 2
-1
>>> :set -XNegativeLiterals
>>> -1 `mod` 2
1
>>> - 1 `mod` 2
-1

I have got this from this StackOverflow question.

like image 30
Julia Path Avatar answered Oct 25 '22 17:10

Julia Path