This appendix covers built-in functions for basic operations. For numerical linear algebra (eigenvalues, SVD, etc.), see LAPACK Functions.
Functions for displaying values:
| Function | Aliases | Description |
out(x) | show(x), print(x) | Pretty-print value and return it |
out([[1, 2], [3, 4]])
// Prints:
// ┌ ┐
// │ 1 2 │
// │ 3 4 │
// └ ┘
| Function | Aliases | Description | Example |
negate(x) | | Unary negation | negate(5) → -5 |
abs(x) | fabs | Absolute value | abs(-3) → 3 |
sqrt(x) | | Square root | sqrt(16) → 4 |
pow(x, y) | power | x^y | pow(2, 3) → 8 |
floor(x) | | Round down | floor(3.7) → 3 |
ceil(x) | ceiling | Round up | ceil(3.2) → 4 |
round(x) | | Round to nearest | round(3.5) → 4 |
trunc(x) | truncate | Truncate toward zero | trunc(-3.7) → -3 |
frac(x) | fract | Fractional part | frac(3.7) → 0.7 |
sign(x) | signum | Sign (-1, 0, or 1) | sign(-5) → -1 |
min(x, y) | | Minimum | min(3, 7) → 3 |
max(x, y) | | Maximum | max(3, 7) → 7 |
mod(x, y) | fmod, remainder | Modulo/remainder | mod(7, 3) → 1 |
hypot(x, y) | | √(x² + y²) stable | hypot(3, 4) → 5 |
All trigonometric functions use radians, not degrees. Use radians(deg) to convert.
| Function | Aliases | Description | Example |
sin(x) | | Sine | sin(0) → 0 |
cos(x) | | Cosine | cos(0) → 1 |
tan(x) | | Tangent | tan(0) → 0 |
asin(x) | arcsin | Arcsine | asin(1) → π/2 |
acos(x) | arccos | Arccosine | acos(1) → 0 |
atan(x) | arctan | Arctangent | atan(1) → π/4 |
atan2(y, x) | arctan2 | 2-arg arctangent | atan2(1, 1) → π/4 |
radians(deg) | deg_to_rad | Degrees to radians | radians(180) → π |
| Function | Aliases | Description |
sinh(x) | | Hyperbolic sine |
cosh(x) | | Hyperbolic cosine |
tanh(x) | | Hyperbolic tangent |
asinh(x) | arcsinh | Inverse hyperbolic sine |
acosh(x) | arccosh | Inverse hyperbolic cosine |
atanh(x) | arctanh | Inverse hyperbolic tangent |
Identity: cosh(x)² - sinh(x)² = 1
| Function | Aliases | Description | Example |
exp(x) | | e^x | exp(1) → 2.718... |
exp2(x) | | 2^x | exp2(3) → 8 |
log(x) | ln | Natural logarithm | log(e()) → 1 |
log10(x) | | Base-10 logarithm | log10(100) → 2 |
log2(x) | | Base-2 logarithm | log2(8) → 3 |
| Function | Aliases | Description | Example |
Cons(x, xs) | cons | Prepend element | Cons(1, Nil) |
Nil | nil | Empty list | Nil |
head(xs) | car | First element | head([1,2,3]) → 1 |
tail(xs) | cdr | Rest of list | tail([1,2,3]) → [2,3] |
length(xs) | list_length | List length | length([1,2,3]) → 3 |
nth(xs, n) | list_nth | Get nth element (0-indexed) | nth([1,2,3], 1) → 2 |
[1, 2, 3] // Bracket list (preferred for numeric work)
[] // Empty list
| Function | Description | Example |
range(n) | Integers 0 to n-1 | range(4) → [0, 1, 2, 3] |
range(start, end) | Integers from start to end-1 | range(2, 5) → [2, 3, 4] |
linspace(start, end) | 50 evenly spaced floats | linspace(0, 1) → [0, 0.0204..., ...] |
linspace(start, end, n) | n evenly spaced floats | linspace(0, 1, 5) → [0, 0.25, 0.5, 0.75, 1] |
These functions take a lambda as their first argument.
| Function | Aliases | Description |
list_map(f, xs) | | Apply f to each element |
list_filter(pred, xs) | | Keep elements where pred returns true |
list_fold(f, init, xs) | | Left fold with accumulator |
list_flatmap(f, xs) | flatmap, concat_map | Map then flatten results |
list_zip(xs, ys) | | Pair corresponding elements |
Apply a function to each element:
list_map(lambda x . x * 2, [1, 2, 3])
// → [2, 4, 6]
list_map(lambda x . x * x, range(5))
// → [0, 1, 4, 9, 16]
Keep elements satisfying a predicate:
list_filter(lambda x . x > 2, [1, 2, 3, 4, 5])
// → [3, 4, 5]
Reduce a list with an accumulator (left fold):
// Sum: f(f(f(0, 1), 2), 3) = ((0+1)+2)+3 = 6
list_fold(lambda acc x . acc + x, 0, [1, 2, 3])
// → 6
// Product
list_fold(lambda acc x . acc * x, 1, [2, 3, 4])
// → 24
Map a function that returns lists, then flatten:
list_flatmap(lambda x . [x, x*10], [1, 2, 3])
// → [1, 10, 2, 20, 3, 30]
Pair corresponding elements (stops at shorter list):
list_zip([1, 2, 3], ["a", "b", "c"])
// → [Pair(1, "a"), Pair(2, "b"), Pair(3, "c")]
Use fst and snd to extract pair components:
let p = Pair(1, "a") in fst(p) // → 1
let p = Pair(1, "a") in snd(p) // → "a"
| Function | Aliases | Description | Example |
list_concat(xs, ys) | list_append, append | Concatenate two lists | list_concat([1,2], [3,4]) → [1,2,3,4] |
list_flatten(xss) | list_join | Flatten nested list | list_flatten([[1,2], [3,4]]) → [1,2,3,4] |
list_slice(xs, start, end) | | Sublist from start to end-1 | list_slice([a,b,c,d], 1, 3) → [b,c] |
list_rotate(xs, n) | | Rotate left by n positions | list_rotate([a,b,c], 1) → [b,c,a] |
reverse(xs) | | Reverse a list | reverse([1,2,3]) → [3,2,1] |
isEmpty(xs) | null?, isNil | Check if list is empty | isEmpty([]) → true |
| Function | Aliases | Description | Example |
sum(xs) | | Sum of numeric list | sum([1, 2, 3]) → 6 |
product(xs) | | Product of numeric list | product([2, 3, 4]) → 24 |
all(pred, xs) | | True if pred holds for all elements | all(lambda x . x > 0, [1,2,3]) → true |
any(pred, xs) | | True if pred holds for any element | any(lambda x . x > 5, [1,2,3]) → false |
foldr(f, z, xs) | | Right fold | foldr(lambda x acc . x + acc, 0, [1,2,3]) → 6 |
| Function | Description | Example |
vec_add(xs, ys) | Element-wise addition | vec_add([1,2], [3,4]) → [4,6] |
| Function | Aliases | Description | Example |
concat(a, b, ...) | | Concatenate strings | concat("hello", " ", "world") → "hello world" |
strlen(s) | | String length | strlen("hello") → 5 |
contains(s, sub) | | Check substring | contains("hello", "ell") → true |
substr(s, start, len) | substring | Extract substring | substr("hello", 1, 3) → "ell" |
replace(s, old, new) | | Replace first occurrence | replace("hello", "l", "L") → "heLlo" |
replaceAll(s, old, new) | | Replace all occurrences | replaceAll("hello", "l", "L") → "heLLo" |
str_eq(a, b) | | String equality | str_eq("abc", "abc") → true |
| Function | Description | Example |
indexOf(s, sub) | Find index of substring (-1 if not found) | indexOf("hello", "ll") → 2 |
charAt(s, i) | Get character at index (0-based) | charAt("hello", 1) → "e" |
hasPrefix(s, prefix) | Check if string starts with prefix | hasPrefix("hello", "he") → true |
hasSuffix(s, suffix) | Check if string ends with suffix | hasSuffix("hello", "lo") → true |
| Function | Description | Example |
trim(s) | Remove leading and trailing whitespace | trim(" hi ") → "hi" |
trimLeft(s) | Remove leading whitespace | trimLeft(" hi") → "hi" |
trimRight(s) | Remove trailing whitespace | trimRight("hi ") → "hi" |
| Function | Description | Example |
isAscii(s) | All chars printable ASCII | isAscii("hello") → true |
isDigits(s) | All chars are digits | isDigits("123") → true |
isAlpha(s) | All chars are alphabetic | isAlpha("abc") → true |
isAlphaNum(s) | All chars are alphanumeric | isAlphaNum("abc123") → true |
| Function | Aliases | Description | Example |
intToStr(n) | int_to_str, fromInt | Number to string | intToStr(42) → "42" |
strToInt(s) | str_to_int, toInt | String to number (-1 if invalid) | strToInt("42") → 42 |
| Function | Description | Example |
splitLines(s) | Split into list by newlines | splitLines("a\nb\nc") → ["a", "b", "c"] |
countLines(s) | Count lines | countLines("a\nb\nc") → 3 |
nthLine(s, n) | Get nth line (0-indexed) | nthLine("a\nb\nc", 1) → "b" |
foldLines(f, init, s) | Fold over lines with accumulator | See below |
Iterate over lines of a string without building a list:
// Count non-empty lines
foldLines(lambda line acc . if strlen(line) > 0 then acc + 1 else acc, 0, source)
For advanced operations (eigenvalues, SVD), see LAPACK Functions.
| Function | Aliases | Description | Example |
matrix([[row1], [row2], ...]) | | Create matrix from nested list | matrix([[1,2],[3,4]]) |
eye(n) | identity(n) | Identity matrix | eye(3) |
zeros(m, n) | | Zero matrix | zeros(2, 3) |
ones(m, n) | | Matrix of ones | ones(2, 3) |
diag_matrix(elements) | diagonal | Diagonal matrix | diag_matrix([1,2,3]) |
[[1, 2, 3],
[4, 5, 6]] // 2×3 matrix
| Function | Aliases | Description |
size(A) | shape, dims | Dimensions [rows, cols] |
nrows(A) | num_rows | Number of rows |
ncols(A) | num_cols | Number of columns |
| Function | Aliases | Description |
matrix_get(A, i, j) | element | Get element at (i, j) |
matrix_row(A, i) | row | Get row i |
matrix_col(A, j) | col | Get column j |
matrix_diag(A) | diag | Get diagonal |
| Function | Description |
set_element(A, i, j, val) | Set element at (i, j) |
set_row(A, i, row) | Set row i |
set_col(A, j, col) | Set column j |
set_diag(A, diag) | Set diagonal |
| Function | Aliases | Description |
matrix_add(A, B) | builtin_matrix_add | A + B |
matrix_sub(A, B) | builtin_matrix_sub | A - B |
multiply(A, B) | matmul, builtin_matrix_mul | A × B |
scalar_matrix_mul(c, A) | builtin_matrix_scalar_mul | c × A |
transpose(A) | builtin_transpose | Aᵀ |
trace(A) | builtin_trace | tr(A) |
det(A) | builtin_determinant | det(A) |
| Function | Aliases | Description |
vstack(A, B) | append_rows | Stack vertically |
hstack(A, B) | append_cols | Stack horizontally |
prepend_row(A, row) | | Add row at top |
append_row(A, row) | | Add row at bottom |
prepend_col(A, col) | | Add column at left |
append_col(A, col) | | Add column at right |
| Function | Aliases | Description |
mpow(A, k) | matrix_pow | Matrix power A^k (integer k, uses binary exponentiation) |
assemble_matrix(n, entries) | | Build n×n from sparse [row, col, value] triples (scatter-add) |
assemble_vector(n, entries) | | Build length-n vector from sparse [index, value] pairs |
| Function | Aliases | Description |
complex_add(z1, z2) | cadd | Complex addition |
complex_sub(z1, z2) | csub | Complex subtraction |
complex_mul(z1, z2) | cmul | Complex multiplication |
conj(z) | conjugate, complex_conj | Complex conjugate |
abs(z) | | Magnitude |z| (works for complex) |
abs_sq(z) | complex_abs_squared | |z|² = a² + b² |
Re(z) | re, real_part, real | Real part |
Im(z) | im, imag_part, imag | Imaginary part |
Complex numbers are represented as complex(re, im) expressions. The imaginary unit i is available as a constant.
Operations on complex matrices represented as (RealPart, ImagPart) pairs.
| Function | Description |
cmat_zero(m, n) | Zero complex matrix |
cmat_eye(n) | Complex identity matrix |
cmat_from_real(A) | Promote real matrix to complex (A, 0) |
cmat_from_imag(B) | Pure imaginary matrix (0, B) |
| Function | Aliases | Description |
cmat_real(M) | real_part_matrix | Extract real part |
cmat_imag(M) | imag_part_matrix | Extract imaginary part |
| Function | Description |
cmat_add(M1, M2) | Complex matrix addition |
cmat_sub(M1, M2) | Complex matrix subtraction |
cmat_mul(M1, M2) | Complex matrix multiplication |
cmat_scale_real(r, M) | Scale by real scalar |
cmat_conj(M) | Element-wise conjugate |
cmat_transpose(M) | Transpose |
cmat_dagger(M) | Conjugate transpose (Hermitian adjoint) |
cmat_trace(M) | Complex trace |
| Function | Description |
cmat_eigenvalues(M) | Complex eigenvalues |
cmat_eig(M) | Full eigendecomposition |
cmat_svd(M) | Singular value decomposition |
cmat_solve(M, b) | Solve complex linear system |
cmat_inv(M) | Complex matrix inverse |
cmat_qr(M) | QR decomposition |
cmat_det(M) | Complex determinant |
cmat_expm(M) | Complex matrix exponential |
cmat_mpow(M, k) | Complex matrix power |
cmat_rank(M) | Complex matrix rank |
cmat_cond(M) | Complex condition number |
cmat_norm(M) | Complex Frobenius norm |
| Function | Description |
realify(M) | Embed complex n×n into real 2n×2n: [[A, -B], [B, A]] |
complexify(R) | Extract complex n×n from real 2n×2n block structure |
| Function | Description | Example |
random(count) | Uniform random values in [0, 1] (seed=42) | random(5) → [0.38..., ...] |
random(count, seed) | Reproducible uniform random | random(5, 123) |
random_normal(count) | Normal distribution N(0, 1) | random_normal(100) |
random_normal(count, seed) | Reproducible normal random | random_normal(100, 42) |
random_normal(count, seed, scale) | N(0, scale) distribution | random_normal(100, 42, 0.5) |
Uses a deterministic LCG (Linear Congruential Generator) with Box-Muller transform for normal distribution. Same seed always produces same sequence.
ode45(f, y0, t_span)
ode45(f, y0, t_span, dt)
Dormand-Prince 5(4) adaptive-step ODE integrator.
| Parameter | Type | Description |
f | Lambda (t, y) → [dy/dt...] | Dynamics function |
y0 | List | Initial state vector |
t_span | [t0, t1] | Time interval |
dt | Number (optional) | Initial step size (default 0.1) |
Returns: List of [t, [y0, y1, ...]] pairs (trajectory).
// x'' = -x → y = [x, x'] → dy/dt = [x', -x]
let f = lambda t y . [nth(y, 1), negate(nth(y, 0))]
let traj = ode45(f, [1, 0], [0, 10], 0.05)
// traj is [[0, [1, 0]], [0.05, [0.998, -0.05]], ...]
The diagram function creates SVG visualizations from plot elements.
diagram(options, element1, element2, ...)
options is a string of key-value pairs: "title=My Plot; xlabel=x; ylabel=y; width=600; height=400"
| Function | Description |
plot(xs, ys, options) | Line plot |
scatter(xs, ys, options) | Scatter plot |
bar(xs, heights, options) | Vertical bar chart |
hbar(xs, heights, options) | Horizontal bar chart |
stem(xs, ys, options) | Stem plot (vertical) |
hstem(xs, ys, options) | Stem plot (horizontal) |
fill_between(xs, y_lower, y_upper, options) | Filled region between curves |
stacked_area(xs, ys_list, options) | Stacked area chart |
boxplot(data, options) | Box-and-whisker plot (vertical) |
hboxplot(data, options) | Box-and-whisker plot (horizontal) |
heatmap(matrix, options) | Heatmap / color mesh |
contour(matrix, options) | Contour plot |
quiver(xs, ys, us, vs, options) | Vector field |
path(commands, options) | SVG path element |
| Function | Description |
yaxis(options) | Configure secondary Y axis |
xaxis(options) | Configure secondary X axis |
place(element, options) | Position an element manually |
let xs = linspace(0, 6.28, 100)
let ys = list_map(lambda x . sin(x), xs)
diagram("title=Sine Wave; xlabel=x; ylabel=sin(x)",
plot(xs, ys, "color=blue; label=sin"))
Functions for generating Typst document fragments from Kleis data.
| Function | Description |
export_typst(expr) | Export expression as Typst code |
export_typst_fragment(expr) | Export as Typst fragment (no document wrapper) |
table_typst(headers, rows) | Generate Typst table from data |
table_typst_raw(headers, rows) | Raw Typst table string |
typst_raw(code) | Emit raw Typst code string |
render_to_typst(editor_ast) | Render Editor AST node to Typst |
lighten(color, amount) | Typst color manipulation helper |
Requires numerical feature.
| Function | Description | Example |
dft(xs) | Discrete Fourier Transform | dft([1, 0, -1, 0]) |
fft(xs) | Fast Fourier Transform (power-of-2 optimized) | fft(signal) |
idft(Xs) | Inverse DFT | idft(spectrum) |
ifft(Xs) | Inverse FFT | ifft(spectrum) |
Input/output are lists of complex numbers represented as [re, im] pairs.
| Function | Description | Example |
readFile(path) | Read file contents as string | readFile("data.csv") |
Note: Paths are relative to the working directory. Returns an error if the file cannot be read.
These zero-argument functions are available inside review policy files.
They return the intent and file path set by the current check_code,
check_file, or diff_check_file invocation.
| Function | Returns | Description |
review_intent() | String | The change intent passed by the caller (empty string if none) |
review_path() | String | The file path being reviewed (empty string if none) |
See Agent MCP Servers — Intent-Aware Review.
| Function | Unicode | Value | Description |
pi() | π | 3.14159… | Pi |
e() | | 2.71828… | Euler’s number |
tau() | τ | 6.28318… | τ = 2π |
i | | √(-1) | Imaginary unit |
Note: pi(), e(), and tau() are zero-argument functions.
| Constant | Description |
True / true | Boolean true |
False / false | Boolean false |