Search code examples
haskelllanguage-extension

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?


Solution

  • 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>