Negative literals and the meaning of case -2 of -2 -> True

Thomas Hallgren hallgren@cse.ogi.edu
Thu, 16 May 2002 15:26:31 -0700


Hi,

The Haskell report seems pretty clear about the meaning of numeric 
literals and negation in expressions: -2 should be interpreted as negate 
(fromInteger 2). That is, negated literals are not treated specially, 
the general rule -(e) ==> negate (e) applies. (See section 3.2 and 3.4 
of the Haskell 98 report [1].)

The mening of numeric literals in patterns also seems clear (section 
3.17.2 says " The interpretation of numeric literals is exactly as 
described in Section 3.2), but the report does not say anything explicit 
about negated literals, although negated numeric literals is a special 
case in the syntax. Presumably, numeric literals should be understood as 
including negated numeric literals in the sections defining the meaning 
of pattern matching?

To find out how Haskell implementations treat negated literals, I tested 
the following program:

------------------------------------------------
main = print (minusTwo,trueOrFalse)

minusTwo = -2::N

trueOrFalse =
    case minusTwo of
      -2 -> True
      _ -> False

data N = Negate N | FromInteger Integer deriving (Eq,Show)

instance Num N where
  negate = Negate
  fromInteger = FromInteger
-------------------------------------------------

The result is:

    * hugs Dec 2001: main outputs: (FromInteger (-2),True)
    * ghc 5.02.2: main outputs: (FromInteger (-2),True)
    * hbc 0.9999.5b: main outputs: (Negate (FromInteger 2),False)
    * nhc98 1.12: compiler outputs: Fail: What? matchAltIf at 7:13

 From this I conclude that hbc is the only Haskell implementation that 
treats negated literals in expressions in accordance with the report, 
but it treats negated literals in patterns differently. Hugs and ghc 
treat expressions and patterns consistently, but they disagree with the 
report. Nhc98 appears to be buggy.

Perhaps this is not a serious problem, but wouldn't it be nice if the 
report and the implementations agreed on this point? I bet Simon PJ will 
suggest that the report is changed to match GHC, rather than vice versa, 
as usual :-) I think the report is right, but the meaning of negated 
literals in patterns could be clearer...

References

[1] Haskell 98 report 
http://research.microsoft.com/~simonpj/haskell98-revised/haskell98-report-html/