Files
lux/examples/functional.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

63 lines
1.7 KiB
Plaintext

// Demonstrating functional programming features
//
// Expected output:
// apply(double, 21) = 42
// compose(addOne, double)(5) = 11
// pipe: 5 |> double |> addOne |> square = 121
// curried add5(10) = 15
// partial times3(7) = 21
// record transform = 30
// Higher-order functions
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))
// Basic functions
fn double(x: Int): Int = x * 2
fn addOne(x: Int): Int = x + 1
fn square(x: Int): Int = x * x
// Using apply
let result1 = apply(double, 21)
// Using compose
let doubleAndAddOne = compose(addOne, double)
let result2 = doubleAndAddOne(5)
// Using the pipe operator
let result3 = 5 |> double |> addOne |> square
// Currying example
fn add(a: Int): fn(Int): Int =
fn(b: Int): Int => a + b
let add5 = add(5)
let result4 = add5(10)
// Partial application simulation
fn multiply(a: Int, b: Int): Int = a * b
let times3 = fn(x: Int): Int => multiply(3, x)
let result5 = times3(7)
// Working with records
let transform = fn(record: { x: Int, y: Int }): Int =>
record.x + record.y
let point = { x: 10, y: 20 }
let recordSum = transform(point)
// Print all results
fn printResults(): Unit with {Console} = {
Console.print("apply(double, 21) = " + toString(result1))
Console.print("compose(addOne, double)(5) = " + toString(result2))
Console.print("pipe: 5 |> double |> addOne |> square = " + toString(result3))
Console.print("curried add5(10) = " + toString(result4))
Console.print("partial times3(7) = " + toString(result5))
Console.print("record transform = " + toString(recordSum))
}
let output = run printResults() with {}