Sorting By Functions in Erlang

Our example demonstrates how to implement custom sorting in Erlang. We’ll sort strings by their length and a list of tuples by a specific element.

-module(sorting_by_functions).
-export([main/0]).

main() ->
    Fruits = ["peach", "banana", "kiwi"],

    % We implement a comparison function for string lengths
    LenCmp = fun(A, B) -> length(A) =< length(B) end,

    % Now we can use lists:sort/2 with this custom comparison function 
    % to sort Fruits by name length
    SortedFruits = lists:sort(LenCmp, Fruits),
    io:format("~p~n", [SortedFruits]),

    % We can use the same technique to sort a list of tuples
    People = [
        {person, "Jax", 37},
        {person, "TJ", 25},
        {person, "Alex", 72}
    ],

    % Sort People by age using lists:sort/2
    SortedPeople = lists:sort(
        fun({person, _, AgeA}, {person, _, AgeB}) -> AgeA =< AgeB end,
        People
    ),
    io:format("~p~n", [SortedPeople]).

In Erlang, we use the lists:sort/2 function to perform custom sorting. This function takes two arguments: a comparison function and the list to be sorted.

For sorting strings by length, we define LenCmp as an anonymous function that compares the lengths of two strings. The =< operator is used because lists:sort/2 expects the comparison function to return true if the first argument should come before or be equal to the second in the sorted list.

To sort the list of people (represented as tuples) by age, we use a similar approach. The comparison function extracts the age from each tuple and compares them.

Note that in Erlang, we don’t need to worry about whether to use pointers or not, as Erlang uses immutable data structures and has automatic memory management.

To run this program, save it as sorting_by_functions.erl and use the Erlang shell:

$ erl
1> c(sorting_by_functions).
{ok,sorting_by_functions}
2> sorting_by_functions:main().
["kiwi","peach","banana"]
[{person,"TJ",25},{person,"Jax",37},{person,"Alex",72}]
ok

This example demonstrates how Erlang’s powerful pattern matching and functional programming features can be used to implement custom sorting logic in a concise and readable manner.