Sorting By Functions in D Programming Language

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 D.

import std.stdio;
import std.algorithm;
import std.array;

void main() {
    string[] fruits = ["peach", "banana", "kiwi"];

    // We implement a comparison function for string lengths.
    bool lenCmp(string a, string b) {
        return a.length < b.length;
    }

    // Now we can call sort with this custom comparison function
    // to sort `fruits` by name length.
    fruits.sort!(lenCmp);
    writeln(fruits);

    // We can use the same technique to sort a slice of
    // values that aren't built-in types.
    struct Person {
        string name;
        int age;
    }

    Person[] people = [
        Person("Jax", 37),
        Person("TJ", 25),
        Person("Alex", 72)
    ];

    // Sort `people` by age using sort.
    people.sort!((a, b) => a.age < b.age);
    writeln(people);
}

In this D code:

  1. We import necessary modules: std.stdio for output, std.algorithm for sorting, and std.array for array operations.

  2. We define a lenCmp function that compares strings based on their length.

  3. We use sort!(lenCmp) to sort the fruits array using our custom comparison function. The ! syntax is D’s way of passing a template argument.

  4. For sorting custom types, we define a Person struct.

  5. We sort the people array using an inline lambda function that compares Person objects based on their age.

Note: In D, we don’t need to explicitly implement a Compare function that returns -1, 0, or 1. Instead, we use boolean comparison functions or lambdas that return true if the first argument should be sorted before the second.

When you run this program, you should see output similar to:

["kiwi", "peach", "banana"]
[Person("TJ", 25), Person("Jax", 37), Person("Alex", 72)]

This demonstrates how to perform custom sorting in D, both for built-in types like strings and for user-defined types like structs.