feat: add comprehensive example programs
Standard examples (examples/standard/): - hello_world: Basic effect usage - fizzbuzz: Classic programming exercise - factorial: Recursive and tail-recursive versions - primes: Prime number generation - guessing_game: Interactive Random + Console effects - stdlib_demo: Demonstrates List, String, Option, Math modules Showcase examples (examples/showcase/): - ask_pattern: Resumable effects for config/environment - custom_logging: Custom effect with handler - early_return: Fail effect for clean error handling - effect_composition: Combining multiple effects - higher_order: Closures and function composition - pattern_matching: ADTs and exhaustive matching Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
40
examples/showcase/higher_order.lux
Normal file
40
examples/showcase/higher_order.lux
Normal file
@@ -0,0 +1,40 @@
|
||||
// Higher-Order Functions and Closures
|
||||
//
|
||||
// Functions are first-class values in Lux.
|
||||
// Closures capture their environment.
|
||||
//
|
||||
// Expected output:
|
||||
// Square of 5: 25
|
||||
// Cube of 3: 27
|
||||
// Add 10 to 5: 15
|
||||
// Add 10 to 20: 30
|
||||
// Composed: 15625 (cube(square(5)) = cube(25) = 15625)
|
||||
|
||||
fn apply(f: fn(Int): Int, x: Int): Int = f(x)
|
||||
|
||||
fn compose(f: fn(Int): Int, g: fn(Int): Int): fn(Int): Int =
|
||||
fn(x: Int): Int => f(g(x))
|
||||
|
||||
fn square(n: Int): Int = n * n
|
||||
|
||||
fn cube(n: Int): Int = n * n * n
|
||||
|
||||
fn makeAdder(n: Int): fn(Int): Int =
|
||||
fn(x: Int): Int => x + n
|
||||
|
||||
fn main(): Unit with {Console} = {
|
||||
// Apply functions
|
||||
Console.print("Square of 5: " + toString(apply(square, 5)))
|
||||
Console.print("Cube of 3: " + toString(apply(cube, 3)))
|
||||
|
||||
// Closures
|
||||
let add10 = makeAdder(10)
|
||||
Console.print("Add 10 to 5: " + toString(add10(5)))
|
||||
Console.print("Add 10 to 20: " + toString(add10(20)))
|
||||
|
||||
// Function composition
|
||||
let squareThenCube = compose(cube, square)
|
||||
Console.print("Composed: " + toString(squareThenCube(5)))
|
||||
}
|
||||
|
||||
let output = run main() with {}
|
||||
Reference in New Issue
Block a user