Logo

Programming-Idioms

  • Scheme
  • Ruby
  • Rust

Idiom #100 Sort by a comparator

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

items.sort_by(c);
items.sort!(&c)

Idiomatic would be using a block instead of named procedure c.
items.sort!{|a,b| a-b }

sort! sorts in_place (sort would leave items unmodified). Comparator c is not idiomatic, items is sorted according to the code in the block.
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...