Recursion in Erlang
Erlang supports recursive functions. Here’s a classic example.
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:
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.