2014-02-09

Joy and caution with -XNegativeLiterals in GHC 7.8

The new NegativeLiterals extension in GHC 7.8 scratches an itch I have had for a long time. Namely:

> y = (-41940.917505092) *~ kilo meter

With NegativeLiterals users of dimensional can finally write:

> y = -41940.917505092 *~ kilo meter

Thanks GHC HQ and contributors!

However, be careful so the extension doesn’t break your calculations. Here is an example (not using dimensional) of how you could get bitten. Without NegativeLiterals:

> Prelude> -2 ^ 2
> -4

With NegativeLiterals:

> Prelude> -2 ^ 2
> 4

I certainly prefer the latter behaviour, but having some regression tests in place when enabling NegativeLiterals might be a good idea.

6 comments:

  1. The documentation just talks about the desugaring of the literal after parsing, whereas this difference seems to be down to different parsing. Do you know if this was intentional?

    ReplyDelete
  2. I don't. Interestingly with -XNegativeLiterals one can write e.g. “10 + -2” which would cause a precedence parsing error without NegativeLiterals. On the other hand, “10 -2” will cause a type inference error (“Could not deduce (Num (a0 -> t))”) with NegativeLiterals.

    ReplyDelete
  3. That "-2 ^ 2 == 4" example shows this extension is crazy! Who would want that behavior? Using the extension do you get "-2 ^ 2 == 4" and, with an extra space after the minus sign, "- 2 ^ 2 == -4"? If so, I don't want anything to do with it.

    ReplyDelete
  4. That is what it does. Maybe it is crazy that the whitespace suddenly becomes very significant.

    ReplyDelete
  5. What about "let x = 2 in -x^2"?

    ReplyDelete
  6. “-4.” It only applies to literals numbers.

    ReplyDelete