Sorting in Erlang

Our example demonstrates sorting in Erlang. We’ll look at sorting for lists of different types.

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

main() ->
    % Sorting functions in Erlang work for any comparable type.
    Strs = ["c", "a", "b"],
    SortedStrs = lists:sort(Strs),
    io:format("Strings: ~p~n", [SortedStrs]),

    % An example of sorting integers.
    Ints = [7, 2, 4],
    SortedInts = lists:sort(Ints),
    io:format("Ints:    ~p~n", [SortedInts]),

    % We can also check if a list is already in sorted order.
    IsSorted = lists:sort(SortedInts) =:= SortedInts,
    io:format("Sorted:  ~p~n", [IsSorted]).

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

$ erl
1> c(sorting).
{ok,sorting}
2> sorting:main().
Strings: ["a","b","c"]
Ints:    [2,4,7]
Sorted:  true
3>

In Erlang, the lists module provides various functions for list manipulation, including sorting. The lists:sort/1 function is used to sort lists of any comparable type.

Unlike Go, Erlang doesn’t have a separate boolean type, so we use the atom true to represent a boolean true value.

Erlang’s pattern matching and functional programming paradigm often allow for elegant solutions to sorting and searching problems. The language’s immutable data structures and built-in list manipulation functions make it well-suited for these kinds of operations.