I am playing around with sorting algorithms. I was curious if there were built-in comparison functions for the primitive types. I know it is really easy just to type (x: Int, y: Int) => x - y. I just want to know if there is a built in comparison, so I'm not reinventing the wheel. Things obviously get more complicated when it comes to Strings (case-sensitive and culture sensitive). I would be surprised if there wasn't something already built-in.
1 Answer
If a type A has an Ordering instance, you can get it by writing Ordering[A], and Ordering has a compare method that you can eta-expand to the function you're looking for:
scala> Ordering[Int].compare _
res0: (Int, Int) => Int = <function2>
As a special case for the primitives (and a few other types), you can refer to the instance directly:
scala> Ordering.Int.compare _
res1: (Int, Int) => Int = <function2>
And more generally, if you've got a type class F and A has an instance, you can get that instance by writing implicitly[F[A]], so the following also works:
scala> implicitly[Ordering[Int]].compare _
res2: (Int, Int) => Int = <function2>
I'd use the first of these choices, though.
_ - _is even easier, or, if type inference is not available,(_: Int) - (_: Int).