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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With