i am very new to the haskell and have a question about Eq.
data Rat = Rat Integer Integer
normaliseRat :: Rat -> Rat
normaliseRat (Rat x y)
|x < 0 && y < 0 = Rat (-x) (-y)
|otherwise = Rat (x `div`(gcd x y)) (y `div` (gcd x y))
So i have a func normaliseRat. And what i need is an instance of Eq and Ord. Of course, Rat 2 4 == Rat 1 2 should be valid.
Thanks for help
Haskell doesn't support function overloading. But
(==)isn't a function; it's declared as a typeclass method, so any type-specific implementations of the method must be defined within aninstancedeclaration, like so:(
x/y == n/mis equivalent, after cross multiplying, tox * m == y * n; multiplication is more efficient and has none of accuracy issues that division would introduce.)The same applies to
Ord, except you have your choice of implementing(<=)orcompare. (Given either of those, default definitions for the other comparison methods will work.)As a typeclass method,
(==)is really an entire family of functions, indexed by the type it's being used with. The purpose of theinstancedeclaration is not to redefine the method, but to add a new function to that family.If you enable the
TypeApplicationsextension, you can view(==)as a mapping from a type to a function.Without a type application, Haskell's type checker automatically figures out which function to use:
but you can be explicit: