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)
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.
There are four different types of calculation operators: arithmetic, comparison, text concatenation, and reference.
Excel's default order of operator precedence mandates that Excel perform multiplication before addition.
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.
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.
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