println
println(...values: any): voidWrites values to stdout separated by spaces, then appends a newline.
| Parameter | Type | Contract |
|---|---|---|
values | any... | Zero or more values to format and print. |
Returns void
A detailed reference for Rey v0.3.1 syntax and its evolving standard library target. Entries marked Early API may use names that differ from the current compiler catalog.
Semicolons (;) are mandatory statement terminators for all variable declarations, assignments, return statements, break/continue transfers, and expression statements. Block-closing braces (}) do not require a trailing semicolon.
var count: int = 10;
count += 5;
println("Count: " + count.toString());Rey supports single-line comments and non-nesting multi-line block comments:
// Single-line comment extending to end of line
/* Multi-line block comment
spanning multiple lines */_), followed by alphanumeric characters or underscores.camelCase for variables, functions, and struct fields; PascalCase for structs, enums, and namespaces; SCREAMING_SNAKE_CASE or camelCase for constants.The following tokens are reserved keywords in Rey v0.3.1:
Note: export is reserved exclusively to emit a compile-time migration diagnostic pointing users to pub.
0, 42, -100, 1_000_000 (underscores permitted between digits).0x1A3F, 0xFF.0b1010_0110, 0b0.3.14159, 0.0, -0.5, 1.0e-5.char): Exactly one raw byte enclosed in single quotes: 'a', 'Z', '\n', '\x41'.string): Double quotes ("..."). UTF-8 encoded byte strings.\n, \t, \r, \\, \", \', \0, \xNN.Unescaped single braces {expr} inside strings evaluate expressions at runtime. Doubled braces {{ or }} produce literal brace characters.
var name = "Rey";
var version = 3;
println("Welcome to {name} v0.{version}!"); // "Welcome to Rey v0.3!"
println("Use {{x}} for syntax templates."); // "Use {x} for syntax templates."
// Triple-Quoted Strings (verbatim whitespace + newlines)
var query = """
SELECT id, email, created_at
FROM users
WHERE status = 'active'
""";Rey enforces static typing at compile time. Primitive type keywords must always be written in lowercase (int, float, bool, char, string, void, any). Capitalized spellings raise a compile-time error.
| Type | Description | Representation / Size |
|---|---|---|
int | 64-bit signed two's-complement integer | 8 bytes (i64) |
float | 64-bit IEEE-754 double precision float | 8 bytes (double) |
bool | Boolean flag (true or false) | 1 byte (i1 / u8) |
char | Exactly one 8-bit byte | 1 byte (u8, unsigned 0..255) |
string | Immutable UTF-8 / byte string | Heap pointer (i8*) |
void | Absence of value (function returns only) | 0 bytes |
any | Dynamic escape-hatch type | Tagged dynamic value box |
| Kind | Syntax Example | Description |
|---|---|---|
| Tuples | (int, string, bool) | Fixed-size immutable heterogeneous product type. Access via .0, .1, .2. |
| Vectors | Vec<T> or [T] | Dynamic growable array of homogeneous elements. |
| HashMaps | HashMap<string, V> | Associative hash table keyed by UTF-8 strings. |
| Options | Option<T> | Null-safe container: Option::Some(v) or Option::None. |
| Results | Result<T, E> | Error handling container: Result::Ok(v) or Result::Err(e). |
| Functions | (int, string) -> bool | First-class callable function signature. |
Append ? to any type to mark it as nullable. Rey enforces compile-time safety and prevents null pointer dereferences:
var age: int? = null;
var title: string? = "Engineer";
if title != null {
// title is safely narrowed to string inside this scope
println(title.toUpper());
}The pipe operator | denotes heterogeneous union types:
var id: int | string = 101;
id = "REY-101"; // ValidinstanceofThe instanceof operator checks nominal structs, enums, or dynamic primitives at runtime. Branching on instanceof automatically narrows the variable's type within that branch:
func inspect(val: int | string | Vec<int>): void {
if val instanceof int {
println("Integer: " + val.toString());
} else if val instanceof string {
println("String: " + val);
} else if val instanceof Vec {
println("Vector length: " + val.len().toString());
}
}var declares a mutable variable.const declares an immutable variable that cannot be reassigned after declaration.var counter: int = 0;
counter += 1; // Valid
const MAX_USERS: int = 1024;
// MAX_USERS = 2048; // Compile Error: cannot reassign constType annotations can be omitted when the initializer can be inferred:
var score = 100; // Inferred as int
var message = "Hello"; // Inferred as stringvar x = 10;
x += 5; // x = 15
x -= 3; // x = 12
x *= 2; // x = 24
x /= 4; // x = 6
x %= 4; // x = 2Prefix and postfix ++ and -- are valid on mutable integer variables:
var n = 5;
n++; // Postfix: increments to 6
++n; // Prefix: increments to 7
n--; // Postfix: decrements to 6
--n; // Prefix: decrements to 5| Level | Operators / Syntactic Forms | Associativity |
|---|---|---|
| 1 | Calls (), Indexing [], Member ., Path ::, Postfix ++, -- | Left-to-right |
| 2 | Unary !, Unary -, Prefix ++, -- | Right-to-left |
| 3 | Multiplicative: *, /, % | Left-to-right |
| 4 | Additive: +, - | Left-to-right |
| 5 | Relational: <, <=, >, >= | Left-to-right |
| 6 | Type Introspection: instanceof | Left-to-right |
| 7 | Equality: ==, != | Left-to-right |
| 8 | Logical AND: && | Left-to-right |
| 9 | Logical OR: || | Left-to-right |
| 10 | Assignment: =, +=, -=, *=, /=, %= | Right-to-left |
+, -, *, /, %) perform strict runtime overflow checking. Overflowing 263−1 or −263 immediately terminates the process with an overflow diagnostic.wrapAdd(a, b), wrapSub(a, b), wrapMul(a, b).int, float, bool, char compare strictly by numerical/boolean value."rey" == "rey" is true).Vec, HashMap, and struct instances compare by reference pointer identity.Logical && and || guarantee short-circuit evaluation:
if ptr != null && ptr.isValid() {
// ptr.isValid() is guaranteed to execute only when ptr is non-null
}if, else if, elseParentheses around conditions are optional; the condition must evaluate to bool.
if score >= 90 {
println("Grade: A");
} else if score >= 80 {
println("Grade: B");
} else {
println("Grade: C");
}while Loopvar i = 0;
while i < 5 {
println(i.toString());
i += 1;
}loopExecutes continuously until interrupted by an explicit break; statement:
var n = 0;
loop {
if n >= 10 {
break;
}
n += 1;
}for ... in LoopIterates over vector elements, array literals, or numeric ranges:
// Collection iteration
for name in ["Alice", "Bob", "Charlie"] {
println("Hello, " + name);
}
// Range iteration (start-inclusive, end-exclusive)
for idx in range(0, 5) {
println("Index: " + idx.toString()); // 0, 1, 2, 3, 4
}matchPattern matching in Rey is strictly exhaustive. Arms are evaluated top-to-bottom. Patterns can match enum variants (with or without payloads), scalar literals, integer ranges a..b, or a wildcard fallback _:
enum Status {
Idle,
Processing(int),
Failed(string)
}
func logStatus(s: Status): void {
match s {
Status::Idle => {
println("System is idle.");
},
Status::Processing(progress) => {
println("Progress: " + progress.toString() + "%");
},
Status::Failed(err) => {
println("Error encountered: " + err);
},
_ => {
println("Unknown state");
}
}
}Functions are declared with func. Return types are specified using : Type. Omitting the return type defaults to void or inferable types.
func add(a: int, b: int): int {
return a + b;
}
pub func greet(name: string): void {
println("Hello, {name}!");
}Rey supports trailing default values and final variadic parameters (collected as Vec<T>):
// Default parameter values
func connect(host: string, port: int = 8080, secure: bool = true): void {
// ...
}
// Variadic parameters
func sum(first: int, ...rest: int): int {
var total = first;
for val in rest {
total += val;
}
return total;
}Lambdas use arrow syntax (args) => expr.
int, float, bool, char, string are captured by immutable value snapshot at creation time.Vec, HashMap, struct capture by reference identity, sharing mutable heap state with outer scopes.var factor = 3;
var triple = (x: int) => x * factor;
println(triple(10).toString()); // 30
var nums = [1, 2, 3, 4, 5];
var doubled = nums.map((n: int) => n * 2);Struct fields are private to the defining module by default. Prepend pub to make fields or methods accessible externally.
struct Vector2D {
pub x: float,
pub y: float,
pub func length(): float {
return sqrt(x * x + y * y);
}
pub func scale(factor: float): void {
x *= factor;
y *= factor;
}
}
// Construction & method invocation
var v = Vector2D { x: 3.0, y: 4.0 };
println("Magnitude: " + v.length().toString()); // 5.0
v.scale(2.0);
println("New X: " + v.x.toString()); // 6.0Enums support pure unit variants or algebraic variants carrying typed payloads:
enum WebEvent {
PageLoad,
KeyPress(char),
Click(int, int),
Paste(text: string)
}
var ev = WebEvent::Click(100, 250);Rey supports namespace imports, selective symbol imports, and direct relative file paths:
// 1. Import namespace
import std::math;
var s = math.sin(1.57);
// 2. Import selective symbols from module
import std::math::{sin, cos, PI};
// 3. Import via relative file path
import "helpers/parser.rey";
var p = parser.create();child/main.rey (directory priority), then child.rey.src/: src/child/main.rey, then src/child.rey.<root>/child/main.rey, then <root>/child.rey.src/: <root>/src/child/main.rey, then <root>/src/child.rey.$HOME/.reyc/std/src/.$HOME/.reyc/packages/.pub vs PrivateDeclarations without pub are strictly private to their defining file. pub func, pub struct, and pub enum are exported for external consumers.
func main(): void in the root file.Vec<T>Dynamic array storing elements in contiguous memory:
var nums = Vec.new();
nums.push(10);
nums.push(20);
nums.push(30);
var last = nums.pop(); // 30
var first = nums[0]; // 10
var totalLen = nums.len(); // 2
nums[1] = 99; // Index assignmentHashMap<string, V>High-performance associative key-value map keyed by strings:
var userAges = HashMap.new();
userAges.set("Alice", 28);
userAges.set("Bob", 34);
if userAges.has("Alice") {
var age = userAges.get("Alice");
println("Alice is " + age.toString());
}
userAges.delete("Bob");Option<T>Type-safe representation of optional values:
var present: Option<int> = Option::Some(42);
var empty: Option<int> = Option::None;
if present.isSome() {
println("Value: " + present.unwrap().toString());
}
var fallback = empty.unwrapOr(100); // 100Result<T, E>Standard container for recoverable operations:
func parsePort(s: string): Result<int, string> {
if s == "80" { return Result::Ok(80); }
return Result::Err("Invalid port number");
}
var res = parsePort("80");
if res.isOk() {
println("Port: " + res.unwrap().toString());
} else {
println("Error: " + res.unwrapErr());
}LinkedList, Stack, Queue// Stack (LIFO)
var st = Stack.new();
st.push("first");
st.push("second");
var top = st.pop(); // "second"
// Queue (FIFO)
var q = Queue.new();
q.enqueue(1);
q.enqueue(2);
var item = q.dequeue(); // 1
// LinkedList (Doubly-linked)
var list = LinkedList.new();
list.push(10);
list.unshift(5);| Function | Parameter | Return | Description |
|---|---|---|---|
int(c) | char | int | Converts 1-byte char to its 0..255 unsigned integer ASCII/byte code. |
char(i) | int | char | Converts integer 0..255 to single-byte char. Exits 1 if out of range. |
float(x) | int | float | float | Converts integer or float to 64-bit IEEE-754 binary64 float. |
string(x) | scalar | string | Converts any scalar primitive directly to its UTF-8 string representation. |
| Function | Parameters | Return | Description |
|---|---|---|---|
abs(x) | int or float | Same as x | Returns absolute value. Panics on INT64_MIN. |
min(a, b) | Numbers | Number | Returns the smaller of two numbers. |
max(a, b) | Numbers | Number | Returns the larger of two numbers. |
pow(base, exp) | (int, int) or (float, float) | Number | Computes base raised to power exponent. |
sqrt(x) | float | float | Square root. Exits 1 if x < 0.0. |
exp(x) | float | float | Exponential function (e^x). |
log(x) | float | float | Natural logarithm (ln x). Exits 1 if x <= 0.0. |
sin(x) | float | float | Sine in radians. |
cos(x) | float | float | Cosine in radians. |
tan(x) | float | float | Tangent in radians. |
floor(x) | float | int | Greatest integer <= x. |
ceil(x) | float | int | Least integer >= x. |
round(x) | float | int | Rounds to the nearest integer. |
random() | void | float | Generates pseudo-random float in range [0.0, 1.0). |
PI | — | float | Mathematical constant π (approximately 3.141592653589793). |
E | — | float | Mathematical constant e (approximately 2.718281828459045). |
| Function | Parameters | Return | Description |
|---|---|---|---|
wrapAdd(a, b) | (int, int) | int | 64-bit integer addition with two's-complement modular wrapping. |
wrapSub(a, b) | (int, int) | int | 64-bit integer subtraction with two's-complement modular wrapping. |
wrapMul(a, b) | (int, int) | int | 64-bit integer multiplication with two's-complement modular wrapping. |
bitAnd(a, b) | (int, int) | int | Bitwise AND (a & b). |
bitOr(a, b) | (int, int) | int | Bitwise OR (a | b). |
bitXor(a, b) | (int, int) | int | Bitwise XOR (a ^ b). |
bitNot(a) | int | int | Bitwise inversion (~a). |
bitShl(a, n) | (int, int) | int | Bitwise shift left (a << n). |
bitShr(a, n) | (int, int) | int | Arithmetic shift right (a >> n). |
| Function | Signature | Description |
|---|---|---|
print(...values) | (...any): void | Prints values space-separated to stdout without newline. |
println(...values) | (...any): void | Prints values space-separated to stdout with newline. |
eprint(...values) | (...any): void | Prints values space-separated to stderr without newline. |
eprintln(...values) | (...any): void | Prints values space-separated to stderr with newline. |
input(prompt?) | (string?): string | Prompts user and reads a line of text from stdin. |
read_line() | (): string | Reads one line from standard input. |
assert(cond, msg) | (bool, string): void | Asserts condition is true; panics with msg if false. |
typeof(val) | (any): string | Returns the runtime type name of the given value. |
type_of(val) | (any): string | Returns the runtime type name of the given value. |
panic(message) | (string): never | Emits a fatal runtime diagnostic and terminates execution. |
| Function | Signature | Description |
|---|---|---|
readFile(path) | (string): string | Reads entire file contents into a string. Exits 1 if missing. |
writeFile(path, data) | (string, string): void | Writes string contents to file (creates or truncates). |
appendFile(path, data) | (string, string): void | Appends string contents to an existing or new file. |
fileExists(path) | (string): bool | Returns true if file exists on disk, false otherwise. |
deleteFile(path) | (string): void | Deletes a file from the file system. |
copyFile(src, dst) | (string, string): void | Copies file from src to dst. |
moveFile(src, dst) | (string, string): void | Moves or renames file from src to dst. |
isFile(path) | (string): bool | Returns true if path points to a regular file. |
isDir(path) | (string): bool | Returns true if path points to a directory. |
mkdir(path) | (string): void | Creates a single directory. |
mkdirAll(path) | (string): void | Recursively creates directories along the path. |
removeDir(path) | (string): void | Removes an empty directory. |
removeDirAll(path) | (string): void | Recursively removes directory and all its contents. |
listDir(path) | (string): Vec<string> | Returns list of filenames within directory. |
listDirPaths(path) | (string): Vec<string> | Returns list of absolute/relative full paths within directory. |
pathJoin(a, b) | (string, string): string | Joins two filesystem path segments. |
basename(path) | (string): string | Returns filename portion of path. |
dirname(path) | (string): string | Returns directory portion of path. |
extname(path) | (string): string | Returns file extension including the leading dot. |
| Function | Signature | Description |
|---|---|---|
args() | (): Vec<string> | Returns CLI arguments passed to the program. |
getEnv(name) | (string): Option<string> | Reads an environment variable into an Option. |
setEnv(name, val) | (string, string): void | Sets an environment variable in the current process. |
unsetEnv(name) | (string): void | Unsets an environment variable. |
envAll() | (): HashMap<string, string> | Returns all environment variables as a key-value map. |
cwd() | (): string | Returns current working directory path. |
chdir(path) | (string): Result<string, string> | Changes current working directory. |
tempDir() | (): string | Returns system temporary directory path. |
exec(cmd) | (string): Result<string, string> | Runs shell command via /bin/sh -c and returns stdout. |
execDetailed(cmd) | (string): ExecResult | Runs shell command and returns struct with stdout, stderr, exit code. |
which(bin) | (string): Option<string> | Resolves executable binary path using PATH. |
sleepMs(ms) | (int): void | Suspends execution for specified milliseconds. |
exit(code) | (int): void | Terminates process immediately with specified status code. |
Each entry includes a signature, parameter contract, return type, and syntax-highlighted example. The requested v0.3.1 target spellings are read_line, type_of, and fold. The current syntax catalog calls these operations input, typeof, and reduce.
Standard output, input, file access, process execution, assertions, fatal errors, and runtime type inspection.
printlnprintln(...values: any): voidWrites values to stdout separated by spaces, then appends a newline.
| Parameter | Type | Contract |
|---|---|---|
values | any... | Zero or more values to format and print. |
Returns void
println("Build", "ready", 3);printprint(...values: any): voidWrites values to stdout separated by spaces without a trailing newline.
| Parameter | Type | Contract |
|---|---|---|
values | any... | Zero or more values to format and print. |
Returns void
print("Downloading ");
print("package");read_lineread_line(): stringReads one line of text from standard input.
| Parameter | Type | Contract |
|---|---|---|
| No parameters. | ||
Returns string
var answer: string = read_line();
println("You entered: " + answer);readFilereadFile(path: string): stringReads the complete file contents. A missing or unreadable file terminates with a runtime error.
| Parameter | Type | Contract |
|---|---|---|
path | string | Path to the file to read. |
Returns string
var contents: string = readFile("notes.txt");
println(contents);writeFilewriteFile(path: string, data: string): voidCreates or truncates a file, then writes the supplied string contents.
| Parameter | Type | Contract |
|---|---|---|
path | string | Destination file path. |
data | string | Complete contents to write. |
Returns void
writeFile("notes.txt", "Rey standard library");execexec(command: string): Result<string, string>Runs a shell command and captures stdout. A failed command is returned as an Err value.
| Parameter | Type | Contract |
|---|---|---|
command | string | Command passed to the system shell. |
Returns Result<string, string>
var output: Result<string, string> = exec("pwd");
if output.isOk() { println(output.unwrap()); }assertassert(condition: bool, message: string): voidChecks an invariant and stops execution with the supplied message when the condition is false.
| Parameter | Type | Contract |
|---|---|---|
condition | bool | Condition that must be true. |
message | string | Diagnostic used when the condition fails. |
Returns void
var port: int = 8080;
assert(port > 0, "port must be positive");panicpanic(message: string): neverEmits a fatal runtime diagnostic and terminates the current program.
| Parameter | Type | Contract |
|---|---|---|
message | string | Reason for the unrecoverable failure. |
Returns never
var denominator: int = 0;
if denominator == 0 {
panic("division by zero");
}type_oftype_of(value: any): stringReturns the runtime type name of a value, such as int, float, string, or bool.
| Parameter | Type | Contract |
|---|---|---|
value | any | Value whose runtime type should be inspected. |
Returns string
var value: any = 42;
println(type_of(value)); // intFloating-point trigonometry, numeric helpers, rounding, and common mathematical constants.
sinsin(radians: float): floatComputes the sine of an angle measured in radians.
| Parameter | Type | Contract |
|---|---|---|
radians | float | Angle in radians. |
Returns float
var quarterTurn: float = PI / 2.0;
println(sin(quarterTurn));coscos(radians: float): floatComputes the cosine of an angle measured in radians.
| Parameter | Type | Contract |
|---|---|---|
radians | float | Angle in radians. |
Returns float
var angle: float = PI;
println(cos(angle));tantan(radians: float): floatComputes the tangent of an angle measured in radians.
| Parameter | Type | Contract |
|---|---|---|
radians | float | Angle in radians. |
Returns float
var angle: float = PI / 4.0;
println(tan(angle));sqrtsqrt(value: float): floatComputes the non-negative square root. Negative input is a runtime error.
| Parameter | Type | Contract |
|---|---|---|
value | float | Non-negative value to take the square root of. |
Returns float
var diagonal: float = sqrt(3.0 * 3.0 + 4.0 * 4.0);powpow(base: int | float, exponent: int | float): int | floatRaises base to exponent for matching numeric argument types.
| Parameter | Type | Contract |
|---|---|---|
base | int | float | Number being raised to a power. |
exponent | int | float | Power applied to base; use the same numeric type as base. |
Returns int | float
var cube: float = pow(4.0, 3.0);absabs(value: int | float): same typeReturns the magnitude of an integer or floating-point value. Panics on INT64_MIN.
| Parameter | Type | Contract |
|---|---|---|
value | int | float | Numeric value whose sign should be removed. |
Returns int | float
var offset: int = abs(-12);floorfloor(value: float): intRounds toward negative infinity to the greatest integer no greater than value.
| Parameter | Type | Contract |
|---|---|---|
value | float | Number to round down. |
Returns int
var lower: int = floor(4.9); // 4ceilceil(value: float): intRounds toward positive infinity to the least integer no less than value.
| Parameter | Type | Contract |
|---|---|---|
value | float | Number to round up. |
Returns int
var upper: int = ceil(4.1); // 5minmin(a: number, b: number): numberReturns the smaller of two numeric values of the same type.
| Parameter | Type | Contract |
|---|---|---|
a | int | float | First numeric value. |
b | int | float | Second numeric value of the same type. |
Returns int | float
var shorter: int = min(12, 8);maxmax(a: number, b: number): numberReturns the larger of two numeric values of the same type.
| Parameter | Type | Contract |
|---|---|---|
a | int | float | First numeric value. |
b | int | float | Second numeric value of the same type. |
Returns int | float
var taller: float = max(1.72, 1.81);PIPI: floatMathematical constant π, approximately 3.141592653589793.
| Parameter | Type | Contract |
|---|---|---|
| No parameters. | ||
Returns float
var radius: float = 2.0;
var circumference: float = 2.0 * PI * radius;EE: floatMathematical constant e, approximately 2.718281828459045.
| Parameter | Type | Contract |
|---|---|---|
| No parameters. | ||
Returns float
var one: float = pow(E, 0.0);| Method | Returns | Description |
|---|---|---|
s.len() | int | Returns byte count in string. |
s[i] | string | Returns 1-character string at index i. |
s.slice(start, end) | string | Returns half-open substring [start, end). |
s.indexOf(sub) | int | First byte index of sub, or -1 if absent. |
s.lastIndexOf(sub) | int | Last byte index of sub, or -1 if absent. |
s.contains(needle) | bool | true if needle exists in string. |
s.startsWith(prefix) | bool | true if string begins with prefix. |
s.endsWith(suffix) | bool | true if string ends with suffix. |
s.toUpper() | string | Converts ASCII characters to uppercase. |
s.toLower() | string | Converts ASCII characters to lowercase. |
s.trim() | string | Strips leading and trailing ASCII whitespace. |
s.trimStart() | string | Strips leading ASCII whitespace. |
s.trimEnd() | string | Strips trailing ASCII whitespace. |
s.padLeft(w, pad) | string | Pads left side to width w using pad. |
s.padRight(w, pad) | string | Pads right side to width w using pad. |
s.replace(from, to) | string | Replaces occurrences of from with to. |
s.repeat(n) | string | Repeats string n times. |
s.split(delim) | Vec<string> | Splits string by delimiter ("" splits into characters). |
s.toInt() | int | Parses decimal string to integer. Exits 1 if invalid. |
s.toFloat() | float | Parses decimal string to float. Exits 1 if invalid. |
s.hash() | int | Returns numeric value of first byte. |
s.toString() | string | Identity conversion. |
| Method | Returns | Description |
|---|---|---|
v.push(item) | void | Appends item to end of vector. |
v.pop() | T | Removes and returns last item. Exits 1 if empty. |
v.len() | int | Returns element count in vector. |
v.get(i) | T | Returns item at index i (bounds checked). |
v.set(i, val) | void | Overwrites item at index i (bounds checked). |
v.contains(item) | bool | true if vector contains item. |
v.indexOf(item) | int | Returns index of item, or -1 if absent. |
v.insert(i, item) | void | Inserts item at index i. |
v.remove(i) | T | Removes and returns item at index i. |
v.clear() | void | Removes all elements. |
v.reverse() | void | In-place reverses elements. |
v.sort() | void | In-place stable sort (ints, floats, strings, bools). |
v.slice(start, end) | Vec<T> | Returns sub-vector from start to end. |
v.join(sep) | string | Joins string vector elements separated by sep. |
v.map(fn) | Vec<U> | Transforms elements via mapping function (T) -> U. |
v.filter(fn) | Vec<T> | Filters elements satisfying predicate (T) -> bool. |
v.reduce(fn, init) | U | Folds elements using accumulator (U, T) -> U. |
v.fold(fn, init) | U | Folds elements left to right from an initial accumulator. |
| Method | Returns | Description |
|---|---|---|
m.set(key, val) | void | Inserts or updates key-value pair. |
m.get(key) | V | Retrieves value for key (panics if absent). |
m.has(key) | bool | Returns true if key exists in map. |
m.delete(key) | void | Removes key and value from map. |
m.keys() | Vec<string> | Returns vector of all keys in map. |
m.values() | Vec<V> | Returns vector of all values in map. |
m.entries() | Vec<Vec<any>> | Returns vector of [key, value] pairs. |
m.len() | int | Returns entry count in map. |
m.clear() | void | Removes all entries from map. |
| Method | Receiver | Returns | Description |
|---|---|---|---|
.isSome() | Option<T> | bool | true if value is Option::Some. |
.isNone() | Option<T> | bool | true if value is Option::None. |
.unwrap() | Option<T> | T | Returns payload. Panics if None. |
.unwrapOr(def) | Option<T> | T | Returns payload if Some, otherwise def. |
.isOk() | Result<T, E> | bool | true if value is Result::Ok. |
.isErr() | Result<T, E> | bool | true if value is Result::Err. |
.unwrap() | Result<T, E> | T | Returns Ok payload. Panics if Err. |
.unwrapErr() | Result<T, E> | E | Returns Err payload. Panics if Ok. |
.unwrapOr(def) | Result<T, E> | T | Returns Ok payload if Ok, otherwise def. |
.unwrapStr() | Result<string, E> | string | Unwraps string Ok payload directly. |
.unwrapOrStr(def) | Result<string, E> | string | Returns string Ok payload or string default. |
These API cards expand the quick reference with parameter contracts, return types, and syntax-highlighted examples. The collection and error-handling APIs are early and experimental in v0.3.1.
Growable homogeneous sequences with indexed access, transforms, filtering, folding, and string joining.
Vec.pushVec<T>.push(item: T): voidAppends one element to the end of a vector.
| Parameter | Type | Contract |
|---|---|---|
item | T | Value to append; it must match the vector element type. |
Returns void
var scores: Vec<int> = [];
scores.push(92);Vec.popVec<T>.pop(): TRemoves and returns the last element. Calling pop on an empty vector is a runtime error.
| Parameter | Type | Contract |
|---|---|---|
| No parameters. | ||
Returns T
var scores: Vec<int> = [84, 92];
var latest: int = scores.pop();Vec.lenVec<T>.len(): intReturns the number of elements currently stored in the vector.
| Parameter | Type | Contract |
|---|---|---|
| No parameters. | ||
Returns int
var scores: Vec<int> = [84, 92];
var count: int = scores.len();Vec.getVec<T>.get(index: int): TReads the element at a zero-based index. An out-of-range index is a runtime error.
| Parameter | Type | Contract |
|---|---|---|
index | int | Zero-based element index. |
Returns T
var scores: Vec<int> = [84, 92];
var first: int = scores.get(0);Vec.mapVec<T>.map(transform: (T) -> U): Vec<U>Applies a transform to each element and returns a new vector of transformed values.
| Parameter | Type | Contract |
|---|---|---|
transform | (T) -> U | Function called once for each element. |
Returns Vec<U>
var scores: Vec<int> = [2, 4, 6];
var doubled: Vec<int> = scores.map((n: int) => n * 2);Vec.filterVec<T>.filter(predicate: (T) -> bool): Vec<T>Keeps elements whose predicate returns true, preserving their order.
| Parameter | Type | Contract |
|---|---|---|
predicate | (T) -> bool | Function that selects elements to keep. |
Returns Vec<T>
var scores: Vec<int> = [55, 82, 91];
var passing: Vec<int> = scores.filter((n: int) => n >= 60);Vec.foldVec<T>.fold(reducer: (U, T) -> U, initial: U): UWalks the vector from left to right, carrying an accumulator through each element.
| Parameter | Type | Contract |
|---|---|---|
reducer | (U, T) -> U | Combines the current accumulator with one element. |
initial | U | Starting accumulator; also the result for an empty vector. |
Returns U
var scores: Vec<int> = [10, 20, 30];
var total: int = scores.fold((sum: int, n: int) => sum + n, 0);Vec.joinVec<string>.join(separator: string): stringConcatenates string elements, placing the separator between adjacent values.
| Parameter | Type | Contract |
|---|---|---|
separator | string | Text inserted between each pair of elements. |
Returns string
var parts: Vec<string> = ["rey", "stdlib"];
var label: string = parts.join(" / ");String-keyed associative storage. Check has(key) before get(key) when a key may be absent.
HashMap.setHashMap<string, V>.set(key: string, value: V): voidInserts a key-value pair or replaces the current value for an existing key.
| Parameter | Type | Contract |
|---|---|---|
key | string | UTF-8 string key. |
value | V | Value stored under the key. |
Returns void
var ages: HashMap<string, int> = HashMap.new();
ages.set("Ada", 36);HashMap.getHashMap<string, V>.get(key: string): VRetrieves a value. A missing key is a runtime error; use has first when absence is expected.
| Parameter | Type | Contract |
|---|---|---|
key | string | Key whose value should be retrieved. |
Returns V
var ages: HashMap<string, int> = HashMap.new();
ages.set("Ada", 36);
var age: int = ages.get("Ada");HashMap.hasHashMap<string, V>.has(key: string): boolChecks whether a key is present without retrieving its value.
| Parameter | Type | Contract |
|---|---|---|
key | string | Key to look up. |
Returns bool
var ages: HashMap<string, int> = HashMap.new();
ages.set("Ada", 36);
if ages.has("Ada") { println(ages.get("Ada")); }HashMap.keysHashMap<string, V>.keys(): Vec<string>Collects the keys currently stored in the map into a vector.
| Parameter | Type | Contract |
|---|---|---|
| No parameters. | ||
Returns Vec<string>
var ages: HashMap<string, int> = HashMap.new();
ages.set("Ada", 36);
var names: Vec<string> = ages.keys();HashMap.valuesHashMap<string, V>.values(): Vec<V>Collects the values currently stored in the map into a vector.
| Parameter | Type | Contract |
|---|---|---|
| No parameters. | ||
Returns Vec<V>
var ages: HashMap<string, int> = HashMap.new();
ages.set("Ada", 36);
var allAges: Vec<int> = ages.values();HashMap.lenHashMap<string, V>.len(): intReturns the number of key-value pairs currently stored in the map.
| Parameter | Type | Contract |
|---|---|---|
| No parameters. | ||
Returns int
var ages: HashMap<string, int> = HashMap.new();
ages.set("Ada", 36);
var entryCount: int = ages.len();Represents a value that may be present. Guard unwrap with isSome, or provide a fallback with unwrapOr.
Option.isSomeOption<T>.isSome(): boolChecks whether the option contains a value.
| Parameter | Type | Contract |
|---|---|---|
| No parameters. | ||
Returns bool
var maybeAge: Option<int> = Option::Some(36);
if maybeAge.isSome() { println(maybeAge.unwrap()); }Option.isNoneOption<T>.isNone(): boolChecks whether the option represents an absent value.
| Parameter | Type | Contract |
|---|---|---|
| No parameters. | ||
Returns bool
var maybeAge: Option<int> = Option::None;
if maybeAge.isNone() { println("no age"); }Option.unwrapOption<T>.unwrap(): TExtracts the contained value. Calling unwrap on Option::None is a runtime error.
| Parameter | Type | Contract |
|---|---|---|
| No parameters. | ||
Returns T
var maybeAge: Option<int> = Option::Some(36);
var age: int = maybeAge.unwrap();Option.unwrapOrOption<T>.unwrapOr(fallback: T): TReturns the contained value or a fallback when the option is empty.
| Parameter | Type | Contract |
|---|---|---|
fallback | T | Value to use when the option is None. |
Returns T
var maybeAge: Option<int> = Option::None;
var age: int = maybeAge.unwrapOr(0);Represents success or failure. Inspect the variant before extracting its payload.
Result.isOkResult<T, E>.isOk(): boolChecks whether the result represents a successful value.
| Parameter | Type | Contract |
|---|---|---|
| No parameters. | ||
Returns bool
var saved: Result<string, string> = Result::Ok("done");
if saved.isOk() { println("saved"); }Result.isErrResult<T, E>.isErr(): boolChecks whether the result represents a failure.
| Parameter | Type | Contract |
|---|---|---|
| No parameters. | ||
Returns bool
var saved: Result<string, string> = Result::Err("disk full");
if saved.isErr() { println("save failed"); }Result.unwrapResult<T, E>.unwrap(): TExtracts a successful value. Calling unwrap on Result::Err is a runtime error.
| Parameter | Type | Contract |
|---|---|---|
| No parameters. | ||
Returns T
var saved: Result<string, string> = Result::Ok("done");
var message: string = saved.unwrap();Result.unwrapOrResult<T, E>.unwrapOr(fallback: T): TReturns the successful value or a fallback when the result is an error.
| Parameter | Type | Contract |
|---|---|---|
fallback | T | Value to use when the result is Err. |
Returns T
var saved: Result<string, string> = Result::Err("disk full");
var message: string = saved.unwrapOr("not saved");Result.unwrapErrResult<T, E>.unwrapErr(): EExtracts the error payload. Calling unwrapErr on Result::Ok is a runtime error.
| Parameter | Type | Contract |
|---|---|---|
| No parameters. | ||
Returns E
var saved: Result<string, string> = Result::Err("disk full");
var reason: string = saved.unwrapErr();