Recursion
Nyx supports recursive functions without any special syntax. A function simply calls itself by name. The classic Fibonacci sequence is the canonical demonstration: the base cases return immediately, and every other call reduces the problem toward one of those bases.
Code
// Recursión: fibonacci recursivo clásico
fn fib(n: int) -> int {
if n <= 1 {
return n
}
return fib(n - 1) + fib(n - 2)
}
fn main() -> int {
// Imprimir la secuencia de fibonacci del 0 al 10
print("Secuencia fibonacci (0..10):")
var i: int = 0
while i <= 10 {
let resultado: int = fib(i)
print("fib(" + int_to_string(i) + ") = " + int_to_string(resultado))
i = i + 1
}
// Calcular fib(20)
let f20: int = fib(20)
print("fib(20) = " + int_to_string(f20))
return 0
}
Output
Secuencia fibonacci (0..10): fib(0) = 0 fib(1) = 1 fib(2) = 1 fib(3) = 2 fib(4) = 3 fib(5) = 5 fib(6) = 8 fib(7) = 13 fib(8) = 21 fib(9) = 34 fib(10) = 55 fib(20) = 6765
Explanation
fib has two base cases: n == 0 returns 0 and n == 1 returns 1. Both are covered by the single guard n <= 1. For any larger n the function calls itself twice and adds the results. Each recursive call moves one or two steps closer to the base, so the recursion always terminates.
The naive double-recursive implementation has exponential time complexity — fib(n) recomputes sub-problems many times. For fib(20) this is still instant, but for large inputs (say fib(40)) a memoized or iterative version is preferred. Nyx benchmarks show fib(40) completes in ~166 ms with the naive approach.
Recursion in Nyx compiles directly to native function calls via LLVM. There is no interpreter overhead, and the generated code is equivalent to what you would write in C.