18

I know that for a type to have an instance of the Num typeclass, there must be one from Eq and Show

class (Eq a, Show a) => Num a

I'm wondering why it's required to be Eq rather than Ord. Does it make sense for a numerical type to be in Eq but not in Ord?

Odin
  • 677
  • 3
  • 15

2 Answers2

35

Complex numbers, for example, can be added, subtracted, multiplied and tested for equality, but not ordered. See Complex a from Data.Complex in base.

dave4420
  • 46,404
  • 6
  • 118
  • 152
  • 3
    Complex numbers can be ordered (e.g. lexicographic ordering is both partial and total). Note that this isn't a particularly useful ordering (and they don't permit and ordering which makes them an ordered field). – cmh Feb 04 '13 at 23:02
  • @cmh I would say it is a very useful ordering, in the sense that it makes `Set.fromList [1 :+ 1]` work, as well as `Map.fromList [(1 :+ 1, 1)]` work. I would also say it is useful for searching through values as the ordering is easy to search (for both humans and computers (binary search)). – semicolon Mar 20 '16 at 03:05
  • @semicolon agreed, it does have some useful computational value. I think when I wrote this comment I mean that it wasn't particularly useful from a mathematicians perspective, although it was 3 years ago! – cmh Mar 22 '16 at 00:24
22

Note that the Eq and Show constraints were also widely considered a misfeature. For example, they prevent perfectly valid instances of Num for things containing functions. In the latest version of GHC, those constraints are also removed, leaving Num with no superclass constraints at all.

sclv
  • 38,665
  • 7
  • 99
  • 204
  • 4
    We should have an instance `Num b => Num (a -> b)`. In math the function that in Haskell we would write `const 2` is almost always just called `2`, and it is silly that in a language with support for proper overloading we have not historically lifted the numeric types to functions. The numeric hierarchy is still broken because `Num` is still way to big. (I wish the standard had classes like `AdditiveMonoid`, `AdditiveGroup`, `AdditionCommutes`, `Ring`, etc) – Philip JF Feb 04 '13 at 19:47
  • And for those who haven't discovered what sclv means, just think of what `liftA2 (+)` does... – Luis Casillas Feb 04 '13 at 19:52
  • @leftaroundabout yes, more programs would type check unintentionally, but not that many more. Usually you would get the error to show up eventually. – Philip JF Feb 04 '13 at 20:00
  • @sclv I don't think it should be lifted to any applicative functor, first of all because Haskell's type class system still chokes on things like this, but secondly because some applicative may have alternative numerical structure. See my answer to http://stackoverflow.com/questions/14641864/what-monads-can-be-expressed-as-free-over-some-functor/ for a cool but probably useless example – Philip JF Feb 04 '13 at 20:09