docs: add comprehensive language documentation
Documentation structure inspired by Rust Book, Elm Guide, and others: Guide (10 chapters): - Introduction and setup - Basic types (Int, String, Bool, List, Option, Result) - Functions (closures, higher-order, composition) - Data types (ADTs, pattern matching, records) - Effects (the core innovation) - Handlers (patterns and techniques) - Modules (imports, exports, organization) - Error handling (Fail, Option, Result) - Standard library reference - Advanced topics (traits, generics, optimization) Reference: - Complete syntax reference Tutorials: - Calculator (parsing, evaluation, REPL) - Dependency injection (testing with effects) - Project ideas (16 projects by difficulty) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
318
docs/guide/09-stdlib.md
Normal file
318
docs/guide/09-stdlib.md
Normal file
@@ -0,0 +1,318 @@
|
||||
# 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")
|
||||
}
|
||||
```
|
||||
|
||||
### 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
|
||||
}
|
||||
```
|
||||
|
||||
## 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 |
|
||||
| Random | int, float, bool |
|
||||
| State | get, put |
|
||||
| Fail | fail |
|
||||
|
||||
## Next
|
||||
|
||||
[Chapter 10: Advanced Topics](10-advanced.md) - Traits, generics, and optimization.
|
||||
Reference in New Issue
Block a user