Why does the Num class have an abs method?

I think of standard libraries (or preludes) for functional languages.

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

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

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

What was the constructive rationale for having abs (or signum ) in the Num typeclass?

+7
haskell typeclass
source share
1 answer

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

But Num has many useful instances for which there is no Ord . In principle, (Num, Ord) ≈ Real in Haskell, which quite clearly hints that the obvious types of non-hordes are higher division algebras , especially Complex . Here abs again is not entirely perfect, because it can return a real number, but since this is a subset of the complex plane that returns Complex , it is not an error.

Other examples are more abstract types, for example.

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

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

To address the question in the title: it is a little disputed whether it was a good idea to put abs in Num . the numerical prelude has it as a complete separate class that allows you to do, for example. vectors are also instances of other num classes, but not Absolute.C . The disadvantage is that this leads to a much more complex class hierarchy, which is often simply not worth the effort.

+10
source share

All Articles