Files
lux/examples/datatypes.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.5 KiB
Plaintext

// Demonstrating algebraic data types and pattern matching
//
// Expected output:
// Tree sum: 8
// Tree depth: 3
// Safe divide 10/2: Result: 5
// Safe divide 10/0: Division by zero!
// Define a binary tree
type Tree =
| Leaf(Int)
| Node(Tree, Tree)
// Sum all values in a tree
fn sumTree(tree: Tree): Int =
match tree {
Leaf(n) => n,
Node(left, right) => sumTree(left) + sumTree(right)
}
// Find the depth of a tree
fn depth(tree: Tree): Int =
match tree {
Leaf(_) => 1,
Node(left, right) => {
let leftDepth = depth(left)
let rightDepth = depth(right)
1 + (if leftDepth > rightDepth then leftDepth else rightDepth)
}
}
// Example tree:
// Node
// / \
// Node Leaf(5)
// / \
// Leaf(1) Leaf(2)
let myTree = Node(Node(Leaf(1), Leaf(2)), Leaf(5))
let treeSum = sumTree(myTree)
let treeDepth = depth(myTree)
// Option type example
fn safeDivide(a: Int, b: Int): Option<Int> =
if b == 0 then None
else Some(a / b)
fn showResult(result: Option<Int>): String =
match result {
None => "Division by zero!",
Some(n) => "Result: " + toString(n)
}
// Print results
fn printResults(): Unit with {Console} = {
Console.print("Tree sum: " + toString(treeSum))
Console.print("Tree depth: " + toString(treeDepth))
Console.print("Safe divide 10/2: " + showResult(safeDivide(10, 2)))
Console.print("Safe divide 10/0: " + showResult(safeDivide(10, 0)))
}
let output = run printResults() with {}