Skip to content

Recursion

Recursion is a technique where a function calls itself to solve a problem by breaking it down into smaller, similar subproblems. Every recursive function needs a base case to stop the recursion, and a recursive case that reduces the problem size.

Recursion is useful for tasks like traversing data structures, performing calculations, and solving problems that have a natural recursive structure.

Example

fn factorial(n: Int): Int {
    if n <= 1 {
        return 1
    }
    return n * factorial(n - 1)
}

print(factorial(5))  # Should print 120

Here, factorial computes the product of all positive integers up to n. The base case is when n is 1 or less.


Next
Up