Skip to content

Ratio Int is not well ordered

Ratio Int is declared to be in class Ord, which means (according to http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Ord.html#t%3AOrd) that < should be a total ordering. Yet consider the following interactive session in GHCI (on a 32 bit computer!):

Prelude> :m + Ratio
Prelude Ratio> let a = 1 % (2 :: Int)
Prelude Ratio> let b = 883177231 % (662415279 :: Int)
Prelude Ratio> let c = 1616076535 % (430549561 :: Int)
Prelude Ratio> a < b && b < c
True
Prelude Ratio> a < c
False

The problem is that overflow occurs in Real.lhs (from the GHC source code), in the definition

(x:%y) <  (x':%y')  =  x * y' <  x' * y

That works for unbounded types (such as Integer). But to define a total order on bounded types, a more complicated method is necessary.

See http://boost.cvs.sourceforge.net/boost/boost/boost/rational.hpp?revision=1.21&view=markup, line 374, for a correct implementation in C++.

Trac metadata
Trac field Value
Version 6.6.1
Type Bug
TypeOfFailure OtherFailure
Priority normal
Resolution Unresolved
Component libraries/base
Test case
Differential revisions
BlockedBy
Related
Blocking
CC
Operating system Multiple
Architecture Multiple
To upload designs, you'll need to enable LFS and have an admin enable hashed storage. More information