Lists in Elixir are effectively linked lists, which means that they are internally represented in pairs that contain the list’s head and tail.
To implement the reversal of a list, we use the Enum
and reverse()
methods.
Enum
methodEnum
is a method to work with enumerables. In this shot, we’ll concentrate on one of these enumerables, list
.
reverse()
methodThe reverse()
method returns a list that has been turned around.
reverse()
reverse(enumerable)
The reverse()
method takes an enumerable
, like a list
, as a parameter.
Enum
and reverse()
togetherWe can use a dot notation to chain the methods together and pass the list as an argument in the reverse()
method.
Let’s look at an example:
list = [1, 2, 3]reverse = Enum.reverse(list)IO.inspect reverse, label: "The reverse list is"#⇒ The list is: [1, 2, 3]
Line 1: We create a variable called list
and store numbers in it.
Line 2: We use Enum.reverse(list)
to reverse the list and save it in the reverse
variable. The list
there is enumerable, as discussed above.
Line 3: We use IO.inspect
to print the result of the reverse
variable.
The output is a list in its reversed state.