Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the Num typeclass have an abs method?

I’m thinking about standard libraries (or preludes) for functional languages.

If I have Ord instance for n, then it is trivial to implement abs:

abs n = if n > 0 then n else (-n)

In the case of vector spaces, the absolute value (length) of a vector is very important. But the type doesn’t match because the absolute value of a vector is not a vector: it is a real number.

What was the design rationale behind having abs (or signum) as part of the Num typeclass?

like image 514
Boldizsár Németh Avatar asked Sep 12 '13 06:09

Boldizsár Németh


1 Answers

Vectors are not good Num candidates. There's a dedicated class for those.

But Num has many useful instances for which there is no Ord. Basically, (Num, Ord) ≈ Real in Haskell, which hints quite clearly that the obvious non-Ord types are the higher division algebras, foremostly Complex. Here, abs is again not quite perfect because it could return a real number, but as these are a subset of the complex plane returning Complex is not wrong.

Other examples are more abstract types, e.g.

instance (Num n) => Num (a->n) where
  f+g = \x -> f x + g x
  ...
  abs f = abs . f

which is not Ord simply because you can't fully evaluate a function, only its return values. (This also prevents an Eq instance, so this is not legal in Haskell98 where Eq is a superclass of Num).

To adress the question in the title: it is a bit disputed whether it was a good idea to put abs in Num. The numeric prelude has it as a complete seperate class, which allows you to make e.g. also vectors an instance of the other num-classes, but not of Absolute.C. The downside is that this results in a much more complicated class hierarchy, which often just isn't worth the effort.

like image 182
leftaroundabout Avatar answered Oct 10 '22 17:10

leftaroundabout