Sorting by Functions in Chapel

Chapel provides built-in support for sorting through its sort module. We’ll use this to demonstrate custom sorting in Chapel.

use Sort;

// 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 Chapel.

proc main() {
    var fruits = ["peach", "banana", "kiwi"];

    // We implement a comparison function for string
    // lengths. Chapel's `compare` function is helpful for this.
    proc lenCmp(a: string, b: string): int {
        return a.length.compare(b.length);
    }

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

    // We can use the same technique to sort an array of
    // values that aren't built-in types.
    record Person {
        var name: string;
        var age: int;
    }

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

    // Sort `people` by age using a custom comparator.
    // Note: Chapel's records are passed by value by default,
    // so we don't need to worry about reference semantics here.
    proc ageCmp(a: Person, b: Person): int {
        return a.age.compare(b.age);
    }

    sort(people, comparator=ageCmp);
    writeln(people);
}

To run the program:

$ chpl sorting-by-functions.chpl -o sorting-by-functions
$ ./sorting-by-functions
["kiwi", "peach", "banana"]
[(name = "TJ", age = 25), (name = "Jax", age = 37), (name = "Alex", age = 72)]

In this Chapel version, we use the sort function from the Sort module, which allows us to pass a custom comparator. The lenCmp and ageCmp functions serve as these comparators, similar to the original example.

Chapel’s record type is used instead of Go’s struct, and the syntax for defining and initializing records is slightly different. The overall structure and logic of the program remain the same.

Note that Chapel’s sort function modifies the array in-place, unlike some languages where sorting returns a new array. This behavior is similar to the Go example using slices.SortFunc.