Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Numeric behave differently than Ordered?

Scala has a number of traits that you can use as type classes, for example Ordered and Numeric in the package scala.math.

I can, for example, write a generic method using Ordered like this:

def f[T <% Ordered[T]](a: T, b: T) = if (a < b) a else b

I wanted to do a similar thing with Numeric, but this doesn't work:

def g[T <% Numeric[T]](a: T, b: T) = a * b

Why is there an apparent discrepancy between Ordered and Numeric?

I know there are other ways to do this, the following will work (uses a context bound):

def g[T : Numeric](a: T, b: T) = implicitly[Numeric[T]].times(a, b)

But that looks more complicated than just being able to use * to multiply two numbers. Why does the Numeric trait not include methods like *, while Ordered does include methods like <?

I know there's also Ordering which you can use in the same way as Numeric, see also this answer:

def f[A : Ordering](a: A, b: A) = implicitly[Ordering[A]].compare(a, b)
like image 729
Jesper Avatar asked Jan 26 '11 10:01

Jesper


People also ask

How is a list different from an atomic vector?

Atomic Vectors An atomic vector is also different from a list. The elements of a vector are all of the same types while a list can contain any arbitrary type. Atomic vectors are constructed with the c() function or the vector function.

What are the four different types of operators use in Excel 2010?

There are four different types of calculation operators: arithmetic, comparison, text concatenation, and reference.

What is operator precedence in Excel?

Excel's default order of operator precedence mandates that Excel perform multiplication before addition.

What does as matrix () do when applied to a data frame with columns of different types?

matrix() do when applied to a data frame with columns of different types? A: From ?as. matrix : The method for data frames will return a character matrix if there is only atomic columns and any non-(numeric/logical/complex) column, applying as.


1 Answers

The symbolic operators are available if you import them from the implicit Numeric[T]

def g[T : Numeric](a: T, b: T) = {
  val num = implicitly[Numeric[T]]
  import num._
  a * b
}

This is clearly a bit unwieldy if you want to make use of just a single operator, but in non-trivial cases the overhead of the import isn't all that great.

Why are the operators not available without an explicit import? The usual considerations against making implicits visible by default apply here, perhaps more so because these operators are so widely used.

like image 101
Miles Sabin Avatar answered Oct 13 '22 20:10

Miles Sabin