Files
lux/examples/tailcall.lux
Brandon Lucas 15a820a467 fix: make all example programs work correctly
- Add string concatenation support to + operator in typechecker
- Register ADT constructors in both type environment and interpreter
- Bind handlers as values so they can be referenced in run...with
- Fix effect checking to use subset instead of exact match
- Add built-in effects (Console, Fail, State) to run block contexts
- Suppress dead code warnings in diagnostics, modules, parser

Update all example programs with:
- Expected output documented in comments
- Proper run...with statements to execute code

Add new example programs:
- behavioral.lux: pure, idempotent, deterministic, commutative functions
- pipelines.lux: pipe operator demonstrations
- statemachine.lux: ADT-based state machines
- tailcall.lux: tail call optimization examples
- traits.lux: type classes and pattern matching

Add documentation:
- docs/IMPLEMENTATION_PLAN.md: feature roadmap and status
- docs/PERFORMANCE_AND_TRADEOFFS.md: performance analysis

Add benchmarks for performance testing.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-13 09:05:06 -05:00

51 lines
1.3 KiB
Plaintext

// 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 {}