concept recursion in category elixir

appears as: recursions, recursion, recursion, The recursion
Elixir in Action

This is an excerpt from Manning's book Elixir in Action.

Although recursion is the basic building block of any kind of looping, most production Elixir code uses it sparingly. That’s because there are many higher-level abstractions that hide the recursion details. You’ll learn about many of these abstractions throughout the book, but it’s important to understand how recursion works in Elixir, because most of the complex code is based on this mechanism.

3.4.1 Iterating with recursion

Let’s say you want to implement a function that prints the first n natural numbers (positive integers). Because there are no loops, you must rely on recursion. The basic approach is illustrated in the following listing.

Listing 3.7 Printing the first n natural numbers (natural_nums.ex)
defmodule NaturalNums do
  def print(1), do: IO.puts(1)
  def print(n) do
    print(n - 1)
    IO.puts(n)
  end
end

This code relies on recursion, pattern matching, and multiclause functions. The code is very declarative: if n is equal to 1, you print the number. Otherwise, you print the first n – 1 numbers and then the nth one.

Elixir in Action

This is an excerpt from Manning's book Elixir in Action.

Although recursion is the basic building block of any kind of looping, most production Elixir code uses it sparingly. The reason is that there are many higher-level abstractions that hide the recursion details. You’ll learn about many of these abstractions throughout the book. Still, it’s important to understand how recursion works in Elixir, because most of the complex code is based on this mechanism.

3.4.1. Iterating with recursion

Let’s say you want to implement a function that prints the first n natural numbers (positive integers). Because there are no loops, you must rely on recursion. The basic approach is illustrated in the following listing.

Listing 3.7. Printing the first n natural numbers (natural_nums.ex)
defmodule NaturalNums do def print(1), do: IO.puts(1) def print(n) do print(n - 1) IO.puts(n) end end

This code relies on recursion, pattern matching, and multiclause functions. The code is very declarative: if n is equal to 1, you print the number. Otherwise, you print the first n – 1 numbers and then the nth one.