Sorting By Functions in Wolfram 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 Wolfram Language.

```wolfram
(* Define a list of fruits *)
fruits = {"peach", "banana", "kiwi"};

(* We implement a comparison function for string lengths *)
lenCmp[a_, b_] := Order[StringLength[a], StringLength[b]];

(* Now we can use SortBy with this custom comparison function to sort fruits by name length *)
sortedFruits = SortBy[fruits, StringLength];
Print[sortedFruits]

(* We can use the same technique to sort a list of values that aren't built-in types *)
(* Define a Person as an Association *)
person[name_, age_] := <|"name" -> name, "age" -> age|>;

people = {
    person["Jax", 37],
    person["TJ", 25],
    person["Alex", 72]
};

(* Sort people by age using SortBy *)
sortedPeople = SortBy[people, #["age"] &];
Print[sortedPeople]

In this example, we first define a list of fruits and sort them by their string length. We use the SortBy function, which takes a list and a function to apply to each element for comparison.

Then, we define a custom Person structure using Associations (similar to dictionaries or structs in other languages). We create a list of people and sort them by age.

In Wolfram Language, we don’t need to explicitly define comparison functions like in some other languages. Instead, we can use built-in functions like SortBy that allow us to specify the sorting criteria directly.

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

{kiwi, peach, banana}
{<|name -> TJ, age -> 25|>, <|name -> Jax, age -> 37|>, <|name -> Alex, age -> 72|>}

This demonstrates how to perform custom sorting in Wolfram Language, both for built-in types like strings and for custom data structures.