Recursion in Erlang

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

-module(recursion).
-export([main/0]).

% This fact function calls itself until it reaches the
% base case of fact(0).
fact(0) -> 1;
fact(N) when N > 0 -> N * fact(N-1).

main() ->
    io:format("~p~n", [fact(7)]),

    % In Erlang, we don't need to declare functions before defining them.
    % We can define a recursive anonymous function directly.
    Fib = fun F(N) when N < 2 -> N;
              F(N) -> F(N-1) + F(N-2)
          end,

    io:format("~p~n", [Fib(7)]).

This fact function uses pattern matching and guards to define the base case and the recursive case. The function calls itself until it reaches the base case of fact(0).

In the main function, we first call fact(7) and print the result.

In Erlang, we can define recursive anonymous functions directly. The Fib function is defined as an anonymous function that calls itself recursively. The F in the function definition is used to refer to the function itself in the recursive calls.

To run this program, save it as recursion.erl and use the Erlang shell:

$ erl
1> c(recursion).
{ok,recursion}
2> recursion:main().
5040
13

In this output, 5040 is the factorial of 7, and 13 is the 7th number in the Fibonacci sequence.

Erlang’s support for recursion and pattern matching makes it particularly well-suited for implementing recursive algorithms in a clean and readable manner.