1

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
  • _ - _ is even easier, or, if type inference is not available, (_: Int) - (_: Int). Commented Jul 31, 2014 at 14:34

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.