Sorting By Functions in Mercury

Sometimes we’ll want to sort a collection by something other than its natural order. For example, suppose we wanted to sort strings by their length instead of alphabetically. Here’s an example of custom sorts in Java.

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class CustomSorting {
    public static void main(String[] args) {
        List<String> fruits = Arrays.asList("peach", "banana", "kiwi");

        // We implement a comparison function for string lengths.
        // Comparator.comparingInt is helpful for this.
        Comparator<String> lenCmp = Comparator.comparingInt(String::length);

        // Now we can call sort with this custom comparison function
        // to sort fruits by name length.
        fruits.sort(lenCmp);
        System.out.println(fruits);

        // We can use the same technique to sort a list of
        // values that aren't built-in types.
        class Person {
            String name;
            int age;

            Person(String name, int age) {
                this.name = name;
                this.age = age;
            }

            @Override
            public String toString() {
                return "{" + name + " " + age + "}";
            }
        }

        List<Person> people = Arrays.asList(
            new Person("Jax", 37),
            new Person("TJ", 25),
            new Person("Alex", 72)
        );

        // Sort people by age using Comparator.
        people.sort(Comparator.comparingInt(p -> p.age));
        System.out.println(people);
    }
}

To run the program:

$ javac CustomSorting.java
$ java CustomSorting
[kiwi, peach, banana]
[{TJ 25}, {Jax 37}, {Alex 72}]

In this Java example, we use the Comparator interface to define custom sorting logic. The Comparator.comparingInt method is used to create comparators based on integer values, which is useful for comparing string lengths or ages.

For sorting the list of Person objects, we use a lambda expression to specify the sorting criteria based on the age field. This approach is equivalent to the function we used in the original example.

Note that in Java, we use the sort method on the List interface, which is part of the Collections Framework, rather than a separate sort function. This method modifies the list in place, unlike some implementations in other languages that return a new sorted list.