- SKILLS.md: Update roadmap phases with actual completion status - Phase 0-1 complete, Phase 2-5 partial, resolved design decisions - OVERVIEW.md: Add HttpServer, Test effect, JIT to completed features - ROADMAP.md: Add HttpServer, Process, Test effects to done list - VISION.md: Update Phase 2-3 tables with current status - guide/05-effects.md: Add Time, HttpServer, Test to effects table - guide/09-stdlib.md: Add HttpServer, Time, Test effect docs - reference/syntax.md: Fix interpolation syntax, remove unsupported literals - testing.md: Add native Test effect documentation Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
368 lines
8.7 KiB
Markdown
368 lines
8.7 KiB
Markdown
# Chapter 9: Standard Library
|
|
|
|
Lux comes with a comprehensive standard library. This chapter covers the built-in modules.
|
|
|
|
## Built-in Functions
|
|
|
|
Always available, no import needed:
|
|
|
|
```lux
|
|
toString(42) // "42" - convert any value to string
|
|
typeOf(42) // "Int" - get type name
|
|
print("hello") // Print to console (shortcut)
|
|
```
|
|
|
|
## List Module
|
|
|
|
Operations on lists:
|
|
|
|
```lux
|
|
let nums = [1, 2, 3, 4, 5]
|
|
|
|
// Transformations
|
|
List.map(nums, fn(x: Int): Int => x * 2) // [2, 4, 6, 8, 10]
|
|
List.filter(nums, fn(x: Int): Bool => x > 2) // [3, 4, 5]
|
|
List.fold(nums, 0, fn(acc: Int, x: Int): Int => acc + x) // 15
|
|
|
|
// Access
|
|
List.head(nums) // Some(1)
|
|
List.tail(nums) // [2, 3, 4, 5]
|
|
List.get(nums, 2) // Some(3)
|
|
List.length(nums) // 5
|
|
List.isEmpty([]) // true
|
|
|
|
// Building
|
|
List.range(1, 5) // [1, 2, 3, 4]
|
|
List.concat([1,2], [3,4]) // [1, 2, 3, 4]
|
|
List.reverse(nums) // [5, 4, 3, 2, 1]
|
|
|
|
// Searching
|
|
List.find(nums, fn(x: Int): Bool => x > 3) // Some(4)
|
|
List.any(nums, fn(x: Int): Bool => x > 3) // true
|
|
List.all(nums, fn(x: Int): Bool => x > 0) // true
|
|
|
|
// Slicing
|
|
List.take(nums, 3) // [1, 2, 3]
|
|
List.drop(nums, 3) // [4, 5]
|
|
```
|
|
|
|
## String Module
|
|
|
|
String manipulation:
|
|
|
|
```lux
|
|
let s = "Hello, World!"
|
|
|
|
// Info
|
|
String.length(s) // 13
|
|
String.isEmpty("") // true
|
|
|
|
// Search
|
|
String.contains(s, "World") // true
|
|
String.startsWith(s, "Hello") // true
|
|
String.endsWith(s, "!") // true
|
|
|
|
// Transform
|
|
String.toUpper(s) // "HELLO, WORLD!"
|
|
String.toLower(s) // "hello, world!"
|
|
String.trim(" hi ") // "hi"
|
|
String.replace(s, "World", "Lux") // "Hello, Lux!"
|
|
|
|
// Split/Join
|
|
String.split("a,b,c", ",") // ["a", "b", "c"]
|
|
String.join(["a","b","c"], "-") // "a-b-c"
|
|
String.lines("a\nb\nc") // ["a", "b", "c"]
|
|
String.chars("abc") // ["a", "b", "c"]
|
|
|
|
// Substring
|
|
String.substring(s, 0, 5) // "Hello"
|
|
```
|
|
|
|
## Option Module
|
|
|
|
Working with optional values:
|
|
|
|
```lux
|
|
let some = Some(42)
|
|
let none: Option<Int> = None
|
|
|
|
// Check
|
|
Option.isSome(some) // true
|
|
Option.isNone(none) // true
|
|
|
|
// Transform
|
|
Option.map(some, fn(x: Int): Int => x * 2) // Some(84)
|
|
Option.flatMap(some, fn(x: Int): Option<Int> => Some(x + 1)) // Some(43)
|
|
|
|
// Extract
|
|
Option.getOrElse(some, 0) // 42
|
|
Option.getOrElse(none, 0) // 0
|
|
```
|
|
|
|
## Result Module
|
|
|
|
Working with results:
|
|
|
|
```lux
|
|
let ok: Result<Int, String> = Ok(42)
|
|
let err: Result<Int, String> = Err("oops")
|
|
|
|
// Check
|
|
Result.isOk(ok) // true
|
|
Result.isErr(err) // true
|
|
|
|
// Transform
|
|
Result.map(ok, fn(x: Int): Int => x * 2) // Ok(84)
|
|
Result.mapErr(err, fn(e: String): String => "Error: " + e) // Err("Error: oops")
|
|
Result.flatMap(ok, fn(x: Int): Result<Int, String> => Ok(x + 1)) // Ok(43)
|
|
|
|
// Extract
|
|
Result.getOrElse(ok, 0) // 42
|
|
Result.getOrElse(err, 0) // 0
|
|
```
|
|
|
|
## Math Module
|
|
|
|
Mathematical functions:
|
|
|
|
```lux
|
|
Math.abs(-5) // 5
|
|
Math.min(3, 7) // 3
|
|
Math.max(3, 7) // 7
|
|
Math.pow(2, 10) // 1024
|
|
Math.sqrt(16) // 4.0
|
|
Math.floor(3.7) // 3
|
|
Math.ceil(3.2) // 4
|
|
Math.round(3.5) // 4
|
|
```
|
|
|
|
## Json Module
|
|
|
|
JSON parsing and generation:
|
|
|
|
```lux
|
|
// Parse JSON string
|
|
let data = Json.parse("{\"name\": \"Alice\", \"age\": 30}")
|
|
|
|
// Access fields
|
|
Json.get(data, "name") // Some("Alice")
|
|
Json.getInt(data, "age") // Some(30)
|
|
|
|
// Create JSON
|
|
let obj = Json.object([
|
|
("name", Json.string("Bob")),
|
|
("age", Json.int(25))
|
|
])
|
|
|
|
// Convert to string
|
|
Json.stringify(obj) // "{\"name\":\"Bob\",\"age\":25}"
|
|
Json.prettyPrint(obj) // Formatted with indentation
|
|
```
|
|
|
|
## Standard Library Modules (std/)
|
|
|
|
Import from the `std/` directory:
|
|
|
|
### std/prelude
|
|
|
|
```lux
|
|
import std/prelude.*
|
|
|
|
identity(42) // 42
|
|
compose(f, g) // Function composition
|
|
flip(f) // Flip argument order
|
|
not(true) // false
|
|
and(true, false) // false
|
|
or(true, false) // true
|
|
```
|
|
|
|
### std/io
|
|
|
|
```lux
|
|
import std/io
|
|
|
|
io.println("Hello") // Print with newline
|
|
io.print("No newline") // Print without newline
|
|
io.readLine() // Read line from input
|
|
io.debug("label", value) // Debug print, returns value
|
|
```
|
|
|
|
### std/option
|
|
|
|
```lux
|
|
import std/option as opt
|
|
|
|
opt.some(42) // Some(42)
|
|
opt.none() // None
|
|
opt.map(x, f) // Map function over option
|
|
opt.flatMap(x, f) // FlatMap
|
|
opt.filter(x, pred) // Filter by predicate
|
|
opt.toList(x) // Convert to list
|
|
```
|
|
|
|
### std/result
|
|
|
|
```lux
|
|
import std/result as res
|
|
|
|
res.ok(42) // Ok(42)
|
|
res.err("oops") // Err("oops")
|
|
res.mapOk(r, f) // Map over Ok value
|
|
res.mapErr(r, f) // Map over Err value
|
|
res.unwrapOr(r, default) // Get value or default
|
|
```
|
|
|
|
## Built-in Effects
|
|
|
|
### Console
|
|
|
|
```lux
|
|
fn example(): Unit with {Console} = {
|
|
Console.print("Hello") // Print string
|
|
let line = Console.readLine() // Read line
|
|
let num = Console.readInt() // Read integer
|
|
}
|
|
```
|
|
|
|
### File
|
|
|
|
```lux
|
|
fn example(): Unit with {File} = {
|
|
let content = File.read("file.txt") // Read file
|
|
File.write("out.txt", "content") // Write file
|
|
let exists = File.exists("file.txt") // Check existence
|
|
let files = File.list("./dir") // List directory
|
|
File.mkdir("newdir") // Create directory
|
|
File.delete("file.txt") // Delete file
|
|
}
|
|
```
|
|
|
|
### Process
|
|
|
|
```lux
|
|
fn example(): Unit with {Process} = {
|
|
let output = Process.exec("ls", ["-la"]) // Run command
|
|
let home = Process.env("HOME") // Get env var
|
|
let args = Process.args() // Get CLI args
|
|
let cwd = Process.cwd() // Current directory
|
|
Process.exit(0) // Exit program
|
|
}
|
|
```
|
|
|
|
### Http
|
|
|
|
```lux
|
|
fn example(): Unit with {Http} = {
|
|
let body = Http.get("https://api.example.com/data")
|
|
let response = Http.post("https://api.example.com/data", jsonBody)
|
|
Http.put("https://api.example.com/data/1", updatedBody)
|
|
Http.delete("https://api.example.com/data/1")
|
|
}
|
|
```
|
|
|
|
### HttpServer
|
|
|
|
```lux
|
|
fn example(): Unit with {HttpServer, Console} = {
|
|
HttpServer.listen(8080) // Start server on port
|
|
Console.print("Server listening on port 8080")
|
|
|
|
let req = HttpServer.accept() // Wait for request
|
|
// req is { method: String, path: String, body: String, headers: List<(String, String)> }
|
|
|
|
Console.print("Got " + req.method + " " + req.path)
|
|
HttpServer.respond(200, "Hello, World!") // Send response
|
|
|
|
HttpServer.stop() // Stop server
|
|
}
|
|
```
|
|
|
|
### Time
|
|
|
|
```lux
|
|
fn example(): Unit with {Time, Console} = {
|
|
let start = Time.now() // Current timestamp (milliseconds)
|
|
Time.sleep(1000) // Sleep for 1 second
|
|
let elapsed = Time.now() - start
|
|
Console.print("Elapsed: " + toString(elapsed) + "ms")
|
|
}
|
|
```
|
|
|
|
### Random
|
|
|
|
```lux
|
|
fn example(): Unit with {Random} = {
|
|
let n = Random.int(1, 100) // Random int in range
|
|
let f = Random.float() // Random float 0.0-1.0
|
|
let b = Random.bool() // Random boolean
|
|
}
|
|
```
|
|
|
|
### State
|
|
|
|
```lux
|
|
fn example(): Int with {State} = {
|
|
let current = State.get() // Get current state
|
|
State.put(current + 1) // Update state
|
|
State.get()
|
|
}
|
|
|
|
// Initialize with value
|
|
run example() with { State = 0 }
|
|
```
|
|
|
|
### Fail
|
|
|
|
```lux
|
|
fn example(): Int with {Fail} = {
|
|
if condition then Fail.fail("Error message")
|
|
else 42
|
|
}
|
|
```
|
|
|
|
### Test
|
|
|
|
Native testing framework:
|
|
|
|
```lux
|
|
fn runTests(): Unit with {Test, Console} = {
|
|
Test.assert(1 + 1 == 2, "basic math")
|
|
Test.assertEqual(List.length([1,2,3]), 3, "list length")
|
|
Test.assertTrue(String.contains("hello", "ell"), "contains check")
|
|
Test.assertFalse(List.isEmpty([1]), "non-empty list")
|
|
}
|
|
|
|
// Run with test handler
|
|
fn main(): Unit with {Console} = {
|
|
run runTests() with { Test = testReporter }
|
|
}
|
|
```
|
|
|
|
## Quick Reference
|
|
|
|
| Module | Key Functions |
|
|
|--------|---------------|
|
|
| List | map, filter, fold, head, tail, length, concat |
|
|
| String | split, join, trim, contains, replace, toUpper |
|
|
| Option | map, flatMap, getOrElse, isSome, isNone |
|
|
| Result | map, mapErr, flatMap, getOrElse, isOk |
|
|
| Math | abs, min, max, pow, sqrt, floor, ceil |
|
|
| Json | parse, stringify, get, object, array |
|
|
|
|
| Effect | Operations |
|
|
|--------|------------|
|
|
| Console | print, readLine, readInt |
|
|
| File | read, write, exists, list, mkdir, delete |
|
|
| Process | exec, env, args, cwd, exit |
|
|
| Http | get, post, put, delete |
|
|
| HttpServer | listen, accept, respond, stop |
|
|
| Time | now, sleep |
|
|
| Random | int, float, bool |
|
|
| State | get, put |
|
|
| Fail | fail |
|
|
| Test | assert, assertEqual, assertTrue, assertFalse |
|
|
|
|
## Next
|
|
|
|
[Chapter 10: Advanced Topics](10-advanced.md) - Traits, generics, and optimization.
|