Recursion in Elixir

Elixir supports recursive functions. Here’s a classic example.

defmodule Recursion do
  # This fact function calls itself until it reaches the
  # base case of fact(0).
  def fact(0), do: 1
  def fact(n) when n > 0, do: n * fact(n - 1)

  def main do
    IO.puts(fact(7))

    # In Elixir, we don't need to declare a variable before defining
    # a recursive function. We can define it directly using a named function.
    fib = fn
      0 -> 0
      1 -> 1
      n -> fib.(n - 1) + fib.(n - 2)
    end

    # Since fib is defined as an anonymous function, we need to use
    # the dot notation to call it.
    IO.puts(fib.(7))
  end
end

Recursion.main()

This fact function uses pattern matching to define the base case (fact(0)) and the recursive case separately. The recursive case calls itself with n - 1 until it reaches the base case.

In Elixir, we don’t need to explicitly declare a variable before defining a recursive function, as we do with closures in some other languages. Instead, we can define anonymous functions directly, and they can be recursive.

The fib function is defined as an anonymous function using pattern matching. It defines the base cases for 0 and 1, and the recursive case for any other number.

To run the program:

$ elixir recursion.exs
5040
13

In Elixir, recursion is a fundamental concept and is often used where other languages might use loops. The language is optimized for tail-call recursion, which means that recursive functions can be very efficient when written properly.