Sorting in Elixir
Elixir’s standard library provides sorting functionality for lists. We’ll look at sorting for built-in types first.
# Sorting functions work for any comparable built-in type.
# For a list of comparable types, see Erlang's term ordering:
# https://www.erlang.org/doc/reference_manual/expressions.html#term-comparisons
# Sorting strings
strs = ["c", "a", "b"]
sorted_strs = Enum.sort(strs)
IO.puts("Strings: #{inspect(sorted_strs)}")
# An example of sorting integers
ints = [7, 2, 4]
sorted_ints = Enum.sort(ints)
IO.puts("Ints: #{inspect(sorted_ints)}")
# We can also check if a list is already in sorted order
is_sorted = Enum.sort(sorted_ints) == sorted_ints
IO.puts("Sorted: #{is_sorted}")
To run the program, save it as sorting.exs
and use elixir
:
$ elixir sorting.exs
Strings: ["a", "b", "c"]
Ints: [2, 4, 7]
Sorted: true
In Elixir, we use the Enum.sort/1
function to sort lists. This function works with any comparable built-in type. The comparison is based on Erlang’s term ordering, which defines a total ordering for all terms.
Unlike Go, Elixir doesn’t have a separate package for sorting. The sorting functionality is part of the Enum
module in the standard library. Also, Elixir works with immutable data, so Enum.sort/1
returns a new sorted list instead of sorting the original list in place.
To check if a list is sorted, we can compare the original list with its sorted version. If they’re equal, the list was already sorted.
Elixir’s functional nature and immutable data structures lead to a slightly different approach to sorting compared to Go, but the core concept remains the same.