Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Appendix: Built-in Functions

This appendix covers built-in functions for basic operations. For numerical linear algebra (eigenvalues, SVD, etc.), see LAPACK Functions.

Output Functions

Functions for displaying values:

FunctionAliasesDescription
out(x)show(x), print(x)Pretty-print value and return it

Example

out([[1, 2], [3, 4]])
// Prints:
// ┌      ┐
// │ 1  2 │
// │ 3  4 │
// └      ┘

Arithmetic Functions

FunctionAliasesDescriptionExample
negate(x)Unary negationnegate(5)-5
abs(x)fabsAbsolute valueabs(-3)3
sqrt(x)Square rootsqrt(16)4
pow(x, y)powerx^ypow(2, 3)8
floor(x)Round downfloor(3.7)3
ceil(x)ceilingRound upceil(3.2)4
round(x)Round to nearestround(3.5)4
trunc(x)truncateTruncate toward zerotrunc(-3.7)-3
frac(x)fractFractional partfrac(3.7)0.7
sign(x)signumSign (-1, 0, or 1)sign(-5)-1
min(x, y)Minimummin(3, 7)3
max(x, y)Maximummax(3, 7)7
mod(x, y)fmod, remainderModulo/remaindermod(7, 3)1
hypot(x, y)√(x² + y²) stablehypot(3, 4)5

Trigonometric Functions (radians)

All trigonometric functions use radians, not degrees. Use radians(deg) to convert.

FunctionAliasesDescriptionExample
sin(x)Sinesin(0)0
cos(x)Cosinecos(0)1
tan(x)Tangenttan(0)0
asin(x)arcsinArcsineasin(1)π/2
acos(x)arccosArccosineacos(1)0
atan(x)arctanArctangentatan(1)π/4
atan2(y, x)arctan22-arg arctangentatan2(1, 1)π/4
radians(deg)deg_to_radDegrees to radiansradians(180)π

Hyperbolic Functions

FunctionAliasesDescription
sinh(x)Hyperbolic sine
cosh(x)Hyperbolic cosine
tanh(x)Hyperbolic tangent
asinh(x)arcsinhInverse hyperbolic sine
acosh(x)arccoshInverse hyperbolic cosine
atanh(x)arctanhInverse hyperbolic tangent

Identity: cosh(x)² - sinh(x)² = 1

Exponential and Logarithmic

FunctionAliasesDescriptionExample
exp(x)e^xexp(1)2.718...
exp2(x)2^xexp2(3)8
log(x)lnNatural logarithmlog(e())1
log10(x)Base-10 logarithmlog10(100)2
log2(x)Base-2 logarithmlog2(8)3

List Operations

Basic List Functions

FunctionAliasesDescriptionExample
Cons(x, xs)consPrepend elementCons(1, Nil)
NilnilEmpty listNil
head(xs)carFirst elementhead([1,2,3])1
tail(xs)cdrRest of listtail([1,2,3])[2,3]
length(xs)list_lengthList lengthlength([1,2,3])3
nth(xs, n)list_nthGet nth element (0-indexed)nth([1,2,3], 1)2

List Literal Syntax

[1, 2, 3]           // Bracket list (preferred for numeric work)
[]                  // Empty list

List Generation

FunctionDescriptionExample
range(n)Integers 0 to n-1range(4)[0, 1, 2, 3]
range(start, end)Integers from start to end-1range(2, 5)[2, 3, 4]
linspace(start, end)50 evenly spaced floatslinspace(0, 1)[0, 0.0204..., ...]
linspace(start, end, n)n evenly spaced floatslinspace(0, 1, 5)[0, 0.25, 0.5, 0.75, 1]

Higher-Order List Functions

These functions take a lambda as their first argument.

FunctionAliasesDescription
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_mapMap then flatten results
list_zip(xs, ys)Pair corresponding elements

list_map

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]

list_filter

Keep elements satisfying a predicate:

list_filter(lambda x . x > 2, [1, 2, 3, 4, 5])
// → [3, 4, 5]

list_fold

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

list_flatmap

Map a function that returns lists, then flatten:

list_flatmap(lambda x . [x, x*10], [1, 2, 3])
// → [1, 10, 2, 20, 3, 30]

list_zip

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"

List Manipulation

FunctionAliasesDescriptionExample
list_concat(xs, ys)list_append, appendConcatenate two listslist_concat([1,2], [3,4])[1,2,3,4]
list_flatten(xss)list_joinFlatten nested listlist_flatten([[1,2], [3,4]])[1,2,3,4]
list_slice(xs, start, end)Sublist from start to end-1list_slice([a,b,c,d], 1, 3)[b,c]
list_rotate(xs, n)Rotate left by n positionslist_rotate([a,b,c], 1)[b,c,a]
reverse(xs)Reverse a listreverse([1,2,3])[3,2,1]
isEmpty(xs)null?, isNilCheck if list is emptyisEmpty([])true

Aggregation

FunctionAliasesDescriptionExample
sum(xs)Sum of numeric listsum([1, 2, 3])6
product(xs)Product of numeric listproduct([2, 3, 4])24
all(pred, xs)True if pred holds for all elementsall(lambda x . x > 0, [1,2,3])true
any(pred, xs)True if pred holds for any elementany(lambda x . x > 5, [1,2,3])false
foldr(f, z, xs)Right foldfoldr(lambda x acc . x + acc, 0, [1,2,3])6

Vector Operations

FunctionDescriptionExample
vec_add(xs, ys)Element-wise additionvec_add([1,2], [3,4])[4,6]

String Operations

Basic String Functions

FunctionAliasesDescriptionExample
concat(a, b, ...)Concatenate stringsconcat("hello", " ", "world")"hello world"
strlen(s)String lengthstrlen("hello")5
contains(s, sub)Check substringcontains("hello", "ell")true
substr(s, start, len)substringExtract substringsubstr("hello", 1, 3)"ell"
replace(s, old, new)Replace first occurrencereplace("hello", "l", "L")"heLlo"
replaceAll(s, old, new)Replace all occurrencesreplaceAll("hello", "l", "L")"heLLo"
str_eq(a, b)String equalitystr_eq("abc", "abc")true

Search and Access

FunctionDescriptionExample
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 prefixhasPrefix("hello", "he")true
hasSuffix(s, suffix)Check if string ends with suffixhasSuffix("hello", "lo")true

Trimming

FunctionDescriptionExample
trim(s)Remove leading and trailing whitespacetrim(" hi ")"hi"
trimLeft(s)Remove leading whitespacetrimLeft(" hi")"hi"
trimRight(s)Remove trailing whitespacetrimRight("hi ")"hi"

Character Classification

FunctionDescriptionExample
isAscii(s)All chars printable ASCIIisAscii("hello")true
isDigits(s)All chars are digitsisDigits("123")true
isAlpha(s)All chars are alphabeticisAlpha("abc")true
isAlphaNum(s)All chars are alphanumericisAlphaNum("abc123")true

Conversion

FunctionAliasesDescriptionExample
intToStr(n)int_to_str, fromIntNumber to stringintToStr(42)"42"
strToInt(s)str_to_int, toIntString to number (-1 if invalid)strToInt("42")42

Line Operations

FunctionDescriptionExample
splitLines(s)Split into list by newlinessplitLines("a\nb\nc")["a", "b", "c"]
countLines(s)Count linescountLines("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 accumulatorSee below

foldLines

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)

Matrix Operations (Basic)

For advanced operations (eigenvalues, SVD), see LAPACK Functions.

Matrix Creation

FunctionAliasesDescriptionExample
matrix([[row1], [row2], ...])Create matrix from nested listmatrix([[1,2],[3,4]])
eye(n)identity(n)Identity matrixeye(3)
zeros(m, n)Zero matrixzeros(2, 3)
ones(m, n)Matrix of onesones(2, 3)
diag_matrix(elements)diagonalDiagonal matrixdiag_matrix([1,2,3])

Matrix Literals

[[1, 2, 3],
 [4, 5, 6]]         // 2×3 matrix

Matrix Properties

FunctionAliasesDescription
size(A)shape, dimsDimensions [rows, cols]
nrows(A)num_rowsNumber of rows
ncols(A)num_colsNumber of columns

Element Access

FunctionAliasesDescription
matrix_get(A, i, j)elementGet element at (i, j)
matrix_row(A, i)rowGet row i
matrix_col(A, j)colGet column j
matrix_diag(A)diagGet diagonal

Element Modification

FunctionDescription
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

Basic Arithmetic

FunctionAliasesDescription
matrix_add(A, B)builtin_matrix_addA + B
matrix_sub(A, B)builtin_matrix_subA - B
multiply(A, B)matmul, builtin_matrix_mulA × B
scalar_matrix_mul(c, A)builtin_matrix_scalar_mulc × A
transpose(A)builtin_transposeAᵀ
trace(A)builtin_tracetr(A)
det(A)builtin_determinantdet(A)

Matrix Stacking

FunctionAliasesDescription
vstack(A, B)append_rowsStack vertically
hstack(A, B)append_colsStack 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

Matrix Power and Assembly

FunctionAliasesDescription
mpow(A, k)matrix_powMatrix 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

Complex Number Operations

FunctionAliasesDescription
complex_add(z1, z2)caddComplex addition
complex_sub(z1, z2)csubComplex subtraction
complex_mul(z1, z2)cmulComplex multiplication
conj(z)conjugate, complex_conjComplex conjugate
abs(z)Magnitude |z| (works for complex)
abs_sq(z)complex_abs_squared|z|² = a² + b²
Re(z)re, real_part, realReal part
Im(z)im, imag_part, imagImaginary part

Complex numbers are represented as complex(re, im) expressions. The imaginary unit i is available as a constant.

Complex Matrix Operations

Operations on complex matrices represented as (RealPart, ImagPart) pairs.

Creation

FunctionDescription
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)

Access

FunctionAliasesDescription
cmat_real(M)real_part_matrixExtract real part
cmat_imag(M)imag_part_matrixExtract imaginary part

Arithmetic

FunctionDescription
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

Advanced (requires numerical feature)

FunctionDescription
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

Realification

FunctionDescription
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

Random Number Generation

FunctionDescriptionExample
random(count)Uniform random values in [0, 1] (seed=42)random(5)[0.38..., ...]
random(count, seed)Reproducible uniform randomrandom(5, 123)
random_normal(count)Normal distribution N(0, 1)random_normal(100)
random_normal(count, seed)Reproducible normal randomrandom_normal(100, 42)
random_normal(count, seed, scale)N(0, scale) distributionrandom_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.

ODE Solver

ode45(f, y0, t_span)
ode45(f, y0, t_span, dt)

Dormand-Prince 5(4) adaptive-step ODE integrator.

ParameterTypeDescription
fLambda (t, y) → [dy/dt...]Dynamics function
y0ListInitial state vector
t_span[t0, t1]Time interval
dtNumber (optional)Initial step size (default 0.1)

Returns: List of [t, [y0, y1, ...]] pairs (trajectory).

Example: Harmonic Oscillator

// 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]], ...]

Plotting and Diagrams

The diagram function creates SVG visualizations from plot elements.

Core Function

diagram(options, element1, element2, ...)

options is a string of key-value pairs: "title=My Plot; xlabel=x; ylabel=y; width=600; height=400"

Plot Elements

FunctionDescription
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

Axis Control

FunctionDescription
yaxis(options)Configure secondary Y axis
xaxis(options)Configure secondary X axis
place(element, options)Position an element manually

Example

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"))

Typst Export Functions

Functions for generating Typst document fragments from Kleis data.

FunctionDescription
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

FFT / Signal Processing

Requires numerical feature.

FunctionDescriptionExample
dft(xs)Discrete Fourier Transformdft([1, 0, -1, 0])
fft(xs)Fast Fourier Transform (power-of-2 optimized)fft(signal)
idft(Xs)Inverse DFTidft(spectrum)
ifft(Xs)Inverse FFTifft(spectrum)

Input/output are lists of complex numbers represented as [re, im] pairs.

File I/O

FunctionDescriptionExample
readFile(path)Read file contents as stringreadFile("data.csv")

Note: Paths are relative to the working directory. Returns an error if the file cannot be read.

Review Context

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.

FunctionReturnsDescription
review_intent()StringThe change intent passed by the caller (empty string if none)
review_path()StringThe file path being reviewed (empty string if none)

See Agent MCP Servers — Intent-Aware Review.

Mathematical Constants

FunctionUnicodeValueDescription
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.

Boolean Constants

ConstantDescription
True / trueBoolean true
False / falseBoolean false

See Also