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:
55
examples/showcase/pattern_matching.lux
Normal file
55
examples/showcase/pattern_matching.lux
Normal file
@@ -0,0 +1,55 @@
|
||||
// Algebraic Data Types and Pattern Matching
|
||||
//
|
||||
// Lux has powerful ADTs with exhaustive pattern matching.
|
||||
// The type system ensures all cases are handled.
|
||||
//
|
||||
// Expected output:
|
||||
// Evaluating: (2 + 3)
|
||||
// Result: 5
|
||||
// Evaluating: ((1 + 2) * (3 + 4))
|
||||
// Result: 21
|
||||
// Evaluating: (10 - (2 * 3))
|
||||
// Result: 4
|
||||
|
||||
type Expr =
|
||||
| Num(Int)
|
||||
| Add(Expr, Expr)
|
||||
| Sub(Expr, Expr)
|
||||
| Mul(Expr, Expr)
|
||||
|
||||
fn eval(e: Expr): Int =
|
||||
match e {
|
||||
Num(n) => n,
|
||||
Add(a, b) => eval(a) + eval(b),
|
||||
Sub(a, b) => eval(a) - eval(b),
|
||||
Mul(a, b) => eval(a) * eval(b)
|
||||
}
|
||||
|
||||
fn showExpr(e: Expr): String =
|
||||
match e {
|
||||
Num(n) => toString(n),
|
||||
Add(a, b) => "(" + showExpr(a) + " + " + showExpr(b) + ")",
|
||||
Sub(a, b) => "(" + showExpr(a) + " - " + showExpr(b) + ")",
|
||||
Mul(a, b) => "(" + showExpr(a) + " * " + showExpr(b) + ")"
|
||||
}
|
||||
|
||||
fn evalAndPrint(e: Expr): Unit with {Console} = {
|
||||
Console.print("Evaluating: " + showExpr(e))
|
||||
Console.print("Result: " + toString(eval(e)))
|
||||
}
|
||||
|
||||
fn main(): Unit with {Console} = {
|
||||
// (2 + 3)
|
||||
let e1 = Add(Num(2), Num(3))
|
||||
evalAndPrint(e1)
|
||||
|
||||
// ((1 + 2) * (3 + 4))
|
||||
let e2 = Mul(Add(Num(1), Num(2)), Add(Num(3), Num(4)))
|
||||
evalAndPrint(e2)
|
||||
|
||||
// (10 - (2 * 3))
|
||||
let e3 = Sub(Num(10), Mul(Num(2), Num(3)))
|
||||
evalAndPrint(e3)
|
||||
}
|
||||
|
||||
let output = run main() with {}
|
||||
Reference in New Issue
Block a user