Add runtime support for the State, Reader, and Fail effects that were already defined in the type system. These effects can now be used in effectful code blocks. Changes: - Add builtin_state and builtin_reader fields to Interpreter - Implement State.get and State.put in handle_builtin_effect - Implement Reader.ask in handle_builtin_effect - Add Reader effect definition to types.rs - Add Reader to built-in effects list in typechecker - Add set_state/get_state/set_reader/get_reader methods - Add 6 new tests for built-in effects - Add examples/builtin_effects.lux demonstrating usage Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
46 lines
1.3 KiB
Plaintext
46 lines
1.3 KiB
Plaintext
// Demonstrating built-in effects in Lux
|
|
//
|
|
// Lux provides several built-in effects:
|
|
// - Console: print and read from terminal
|
|
// - Fail: early termination with error
|
|
// - State: get/put mutable state (requires runtime initialization)
|
|
// - Reader: read-only environment access (requires runtime initialization)
|
|
//
|
|
// This example demonstrates Console and Fail effects.
|
|
//
|
|
// Expected output:
|
|
// Starting computation...
|
|
// Step 1: validating input
|
|
// Step 2: processing
|
|
// Result: 42
|
|
// Done!
|
|
|
|
// A function that can fail
|
|
fn safeDivide(a: Int, b: Int): Int with {Fail} =
|
|
if b == 0 then Fail.fail("Division by zero")
|
|
else a / b
|
|
|
|
// A function that validates input
|
|
fn validatePositive(n: Int): Int with {Fail} =
|
|
if n < 0 then Fail.fail("Negative number not allowed")
|
|
else n
|
|
|
|
// A computation that uses multiple effects
|
|
fn compute(input: Int): Int with {Console, Fail} = {
|
|
Console.print("Starting computation...")
|
|
Console.print("Step 1: validating input")
|
|
let validated = validatePositive(input)
|
|
Console.print("Step 2: processing")
|
|
let result = safeDivide(validated * 2, 1)
|
|
Console.print("Result: " + toString(result))
|
|
result
|
|
}
|
|
|
|
// Main function
|
|
fn main(): Unit with {Console} = {
|
|
let result = run compute(21) with {}
|
|
Console.print("Done!")
|
|
}
|
|
|
|
let output = run main() with {}
|