Ordering with Scala Implicits

Lets say we want to order an Array of Strings that represents Integers ordered by the integer value.

val gradess: Array[String] = Array("6","757", "1", "3", "10", "3", "5")

The one important constraint it that there is no preceding zeros which will imply that a shorter String represents always a bigger number which is the key to solve this problem.

Intuitively we could convert the Strings to Integers, order the Array with sorted method and then convert back to Strings.

Right?

Yes, but … slow. You have to convert the whole Array two times.

To fix this, as sorted is a method that takes a implicit Ordering parameter we can create and Ordering object that would be more precedent than the default Ordering[String] that performs a lexicographical ordering.

The one implementation I have just done takes into account the length of the String as a longer Strings represent bigger numbers.

Then in the case of equally length strings, the lexicographical default String ordering is right so we just can rely on it (Ordering.String.compare(x, y) )

We can implement the Ordering with a new Ordering[String]{override def compare(x:String, y:String):Int = …} but because we have only one method to override we can use a Single Abstract Method pattern as follows:

implicit val orderStrings: Ordering[String] = (x: String, y: String) => { 
 if (x.length > y.length) 1  
 else if (x.length < y.length) -1  
 else Ordering.String.compare(x, y)} 

Javi

I hope you liked, any question please ask

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *