When does negative literature change behavior?

In describing NegativeLiterals, Haskell provides an example of how using a language extension can change the performance of some code, and then says

Other examples may actually change behavior, and not just be less effective.

After cheating with the extension a bit, I could not find any of these cases of behavior changes. I could only find the performance changes that they were talking about, and several programs that would have an error with and without the extension.

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

+4
source share
3 answers

, , fromInteger fromInteger, . fromInteger . negate negate . fromInteger. , , - - , .

, :

data Bad = Bad Integer
    deriving (Show)

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

:

*Main> (-1) :: Bad
Bad 2
*Main> :set -XNegativeLiterals
*Main> (-1) :: Bad
Bad (-1)
*Main>
+5

, Int8 from Data.Int. , 8. -128 127. , -128 128 Int8, , . NegativeLiterals -128 Int8, .


, ghci 128 , -128 , -128 . , , Int8 , , .

0

NegativeLiteralsalso changes the way you analyze some expressions. Unary is -interpreted as an operator with the same priority as binary -(i.e. 6), but with NegativeLiteralsa -that is, directly (without a space), 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 got this from this StackOverflow question.

0
source

Source: https://habr.com/ru/post/1692225/


All Articles