// Demonstrating tail call optimization (TCO) in Lux // TCO allows recursive functions to run in constant stack space // // Expected output: // factorial(20) = 2432902008176640000 // fib(30) = 832040 // sumTo(1000) = 500500 // countdown(10000) completed // Factorial with accumulator - tail recursive fn factorialTCO(n: Int, acc: Int): Int = if n <= 1 then acc else factorialTCO(n - 1, n * acc) fn factorial(n: Int): Int = factorialTCO(n, 1) // Fibonacci with accumulator - tail recursive fn fibTCO(n: Int, a: Int, b: Int): Int = if n <= 0 then a else fibTCO(n - 1, b, a + b) fn fib(n: Int): Int = fibTCO(n, 0, 1) // Count down - simple tail recursion fn countdown(n: Int): Int = if n <= 0 then 0 else countdown(n - 1) // Sum with accumulator - tail recursive fn sumToTCO(n: Int, acc: Int): Int = if n <= 0 then acc else sumToTCO(n - 1, acc + n) fn sumTo(n: Int): Int = sumToTCO(n, 0) // Test the functions let fact20 = factorial(20) let fib30 = fib(30) let sum1000 = sumTo(1000) let countResult = countdown(10000) // Print results fn printResults(): Unit with {Console} = { Console.print("factorial(20) = " + toString(fact20)) Console.print("fib(30) = " + toString(fib30)) Console.print("sumTo(1000) = " + toString(sum1000)) Console.print("countdown(10000) completed") } let output = run printResults() with {}