Logo

Programming-Idioms

  • Kotlin
  • Scala

Idiom #100 Sort by a comparator

Sort elements of array-like collection items, using a comparator c.

val c: Ordering[Int] = Ordering.Int
val sortedItems = items.sorted(c)

// Or using implicits:

val sortedItems = items.sorted

The lines creating & using the variable c can be excluded, as seen below.
The argument c is an "implicit argument", which means that if a suitable, unique, implementation of `Ordering[Int]` can be found, then the argument list can be excluded.
items.sortWith(c)
with Ada.Containers.Vectors;
use Ada.Containers;
type Integer_Comparator is not null access function (Left, Right : Integer) return Boolean;
      
package Integer_Vectors is new Vectors (Positive, Integer);
use Integer_Vectors;
      
procedure Sort_Using_Comparator (V : in out Vector; C : Integer_Comparator) is
   package Vector_Sorting is new Generic_Sorting (C.all);
   use Vector_Sorting;
         
begin
   Sort (V);
end Sort_Using_Comparator;

New implementation...