A function that calls itself

Syntax and values

A function can solve a smaller version of a problem by calling itself. This is called recursion. It needs a stopping case, just as a repeating loop needs a way to finish.

Direct recursion is supported. Runtimes enforce a bounded maximum user-function
call depth and produce a structured runtime error instead of overflowing the
host stack. Session runtimes make this bound configurable; the current generated
native runtime fixes it at 256.

Behavior and details

The example has a base case at n <= 1 and makes progress by subtracting one before the recursive call. It prints 120. Calls must still follow source order; direct self-recursion does not make later function declarations visible.

Example

# language: en
function factorial(n):
    if n <= 1:
        return 1
    return n * factorial(n - 1)
say factorial(5)

Syntax and values · Built-ins · Programming guides