TL;DR
In the previous post, we explain what Elixir Lists are and when to use them. Today we reveal the recursion concept in Elixir Lists. This post is part of the functional language series, and it is based on the remarkable book Elixir In Action by Sasa Juric.
Recursion
In computer science, recursion is a method of solving a problem where the solution depends on solutions to smaller instances of the same problem [wikipedia].
That means there must be a mechanism (a function) in Elixir that helps us to divide any list to smaller chunks so we could apply the same function on those chunks. We are done when we reach an empty list.
Head and Tail
For recursion support, Elixir has two Kernel
functions, hd
that return the first List element, and tl
that returns the rest of the List without the head. There is a lovely trick in Elixir, where you can get head and tail in the same row. Using [ | ]
the operand, you could also add an element at the list beginning. This is O(1) operation. Remember that add to the end of List is O(n) operation.
Remember
- what is recursion
- tail and head concept
- O(1) notation
hd
andtl
Kernel
functions[ | ]