[Haskell-cafe] Exception for NaN

Casey McCann syntaxglitch at gmail.com
Sat May 14 17:29:13 CEST 2011

On Sat, May 14, 2011 at 9:14 AM, Ketil Malde <ketil at malde.org> wrote:
> Maybe not terribly brilliant, but wouldn't it improve things slightly if
> NaN was considered less or greater than any other value (possibly
> excluding infinities)?

It would improve things in the sense of giving well-behaved instances
for Eq and Ord, yes. It would not improve things in the sense that it
would violate the IEEE floating point spec.

The real issue here, I think, is that we're expecting Ord to serve two
different purposes: Sometimes a logical ordering on the type according
to its semantics, sometimes an essentially arbitrary ordering for the
purpose of structuring data (e.g., for use as a key in Data.Map). For
most types, either there is no meaningful semantic ordering or the
obvious ordering serves both purposes.

In the case of floating point values, the semantics of the type are
that it is not fully ordered and thus arguably shouldn't be an
instance of Ord at all--in particular, there's nothing "compare" can
correctly return when given NaN. An arbitrary ordering, on the other
hand, could be established easily so that things like Data.Map would
work correctly, but only by breaking the semantics of the type (even
more than is already the case due to things like "compare", that is).

The current situation is an awkward compromise that mostly works and
does what you want in most cases except when you get weird silent bugs
due to, say, minimum returning a non-minimal value, or Data.Map.lookup
returning Nothing for a key that actually exists, or whatever else.
Alternative approaches are generally going to be either horribly
inconvenient, cause as many problems as they solve, or require
massively disruptive changes to the standard library.

In short, file this one on the shelf next to "why is Num designed the
way it is?"

- C.

More information about the Haskell-Cafe mailing list