Elixir List Recursion — Tentamen Software Testing Blog

Image for post
Image for post


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.


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.


Originally published at https://blog.tentamen.eu on August 9, 2020.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store