POLYTONE — the AI-native programming language

API reference

Every pub item of the standard library — 185 entries across 24 modules, generated from the code that ships (ptc doc at build time). This page cannot drift.

import audio13

Soundrecord
rate: Int
samples: List[Int]

Rendered sound: sample rate plus 16-bit signed samples (mono).

audio.renderfn
fn render(source: Text) -> Result[Sound, Text]

Synthesizes .pta source text into a Sound (formats/pta-audio.md). This is the MONO mixdown: a v4 `pan` places voices only in `render_stereo`; here every voice plays at full on the one channel (echo and everything else apply identically).

audio.silencefn
fn silence(ms: Int) -> Sound

Silence of the given length in milliseconds (at 44100 Hz).

audio.tonefn
fn tone(note: Text, ms: Int, wave: Text, volume: Int) -> Result[Sound, Text]

A single synthesized note, e.g. tone("c4", 500, "sine", 80).

audio.appendfn
fn append(a: Sound, b: Sound) -> Sound

b played after a.

audio.mixfn
fn mix(a: Sound, b: Sound) -> Sound

a and b played together (summed, clamped); length is the longer one.

audio.gainfn
fn gain(s: Sound, percent: Int) -> Sound

The sound scaled to `percent` loudness (0–200), clamped.

audio.repeatfn
fn repeat(s: Sound, times: Int) -> Sound

The sound repeated `times` times.

audio.adsrfn
fn adsr(s: Sound, attack_ms: Int, decay_ms: Int, sustain: Int, release_ms: Int) -> Sound

The classic ADSR envelope applied over the sound's full length: linear attack and decay to `sustain` percent, then a linear release over the final `release_ms`.

audio.to_wav_bytesfn
fn to_wav_bytes(sound: Sound) -> Bytes

The single export bridge for playback: RIFF/WAVE PCM bytes.

Stereorecord
rate: Int
left: List[Int]
right: List[Int]

A stereo sound: two channels at the same rate. A v4 score places voices with `pan`; `render` stays the mono mixdown.

audio.render_stereofn
fn render_stereo(source: Text) -> Result[Stereo, Text]

Renders .pta source text in stereo: `pan` (version 4) attenuates the far channel per voice, so a centered score's channels both equal the mono render exactly. Accepts every version 1–4.

audio.to_wav_bytes_stereofn
fn to_wav_bytes_stereo(s: Stereo) -> Bytes

The stereo export bridge: RIFF/WAVE PCM, 16-bit, two interleaved channels — `to_wav_bytes`' twin. A shorter channel is padded with silence so the encode is total.

import base642

base64.encodefn
fn encode(bytes: Bytes) -> Text

Encodes bytes as Base64 with `=` padding.

base64.decodefn
fn decode(text: Text) -> Result[Bytes, Text]

Decodes standard Base64 (with `=` padding). A character outside the alphabet, a length that is not a multiple of four, or `=` padding anywhere but as a suffix of the final group is an error. Non-canonical trailing bits (the unused low bits of the last significant character) are accepted rather than rejected — RFC 4648 §3.5 leaves this to the decoder, and `encode` always emits the canonical form, so round-trips are unaffected.

import crypto5

crypto.sha256fn
fn sha256(msg: Bytes) -> Bytes

SHA-256 of the given bytes, as a 32-byte digest.

crypto.sha256_hexfn
fn sha256_hex(msg: Bytes) -> Text

SHA-256 as a lowercase hex string.

crypto.hmac_sha256fn
fn hmac_sha256(key: Bytes, msg: Bytes) -> Bytes

HMAC-SHA-256 (RFC 2104) of `msg` under `key`, as a 32-byte tag.

crypto.hmac_sha256_hexfn
fn hmac_sha256_hex(key: Bytes, msg: Bytes) -> Text

HMAC-SHA-256 as a lowercase hex string.

crypto.crc32fn
fn crc32(msg: Bytes) -> Int

CRC-32 (IEEE 802.3, the zip/png checksum), computed bit by bit.

import csv2

csv.parsefn
fn parse(text: Text) -> Result[List[List[Text]], Text]

Parses CSV text into rows of fields. An unterminated quoted field, or content after a field's closing quote (`"ab"c`), is an error.

csv.serializefn
fn serialize(rows: List[List[Text]]) -> Text

Serializes rows of fields into CSV text (LF line endings, trailing newline per row). A CSV line cannot distinguish an empty row `[]` from a row holding one empty field `[""]` — both write a bare newline and `parse` reads them back as a single empty field.

import hex2

hex.encodefn
fn encode(bytes: Bytes) -> Text

Lowercase hex, two digits per byte (the builtin `Bytes.to_hex`).

hex.decodefn
fn decode(text: Text) -> Result[Bytes, Text]

Decodes a hex string (upper- or lowercase) to bytes. An odd length or a non-hex character is an error.

import http10

Methodenum
Method.Get
Method.Post
Method.Put
Method.Delete
Method.Patch
Method.Head
Method.Options

An HTTP request method.

Statusrecord
code: Int
Status.ok(self) -> BoolWhether the request succeeded (2xx).
Status.client_error(self) -> BoolWhether the caller made a mistake (4xx).
Status.server_error(self) -> BoolWhether the server failed (5xx).

An HTTP status code (200, 404, 500, …).

Requestrecord
method: Method
url: Text
headers: Map[Text, Text]
body: Option[Bytes]
Request.with_header(self, name: Text, value: Text) -> RequestThe same request carrying one more header.

An HTTP request: a method, a URL, headers, and an optional body.

Responserecord
status: Status
headers: Map[Text, Text]
body: Bytes
Response.ok(self) -> BoolWhether the response succeeded (2xx).
Response.text(self) -> Option[Text] — The body decoded as UTF-8 text, if it is valid.
Response.header(self, name: Text) -> Option[Text] — The value of a header, if the response carries it.

An HTTP response: a status, headers, and a body.

http.getfn
fn get(url: Text) -> Request

A GET request for a URL, no headers or body — the common case.

http.postfn
fn post(url: Text, body: Bytes) -> Request

A POST request carrying a body.

http.requestfn
fn request(method: Method, url: Text, headers: Map[Text, Text], body: Option[Bytes]) -> Request

A request with every field given explicitly.

http.is_successfn
fn is_success(status: Status) -> Bool

Whether a status is a success (200–299).

http.is_client_errorfn
fn is_client_error(status: Status) -> Bool

Whether a status is a client error (400–499).

http.is_server_errorfn
fn is_server_error(status: Status) -> Bool

Whether a status is a server error (500–599).

import images30

Imagerecord
width: Int
height: Int
pixels: List[Int]

A rendered image: dimensions plus a flat RGB pixel list (3 ints per pixel, row-major, values 0–255).

images.canvasfn
fn canvas(width: Int, height: Int, r: Int, g: Int, b: Int) -> Image

A solid-color canvas of width x height pixels (each 1-4096), filled with the RGB color (each channel 0-255).

images.set_pixelfn
fn set_pixel(img: Image, x: Int, y: Int, r: Int, g: Int, b: Int) -> Image

The image with one pixel set (ignores out-of-canvas coordinates).

images.get_pixelfn
fn get_pixel(img: Image, x: Int, y: Int) -> Option[Tuple[Int, Int, Int]]

The (r, g, b) triple at (x, y), or None outside the canvas. A tuple since Sprint 210 `[LLM-first decision]`: two independent benchmark models both guessed `case Some((r, g, b))` — the destructuring form IS the prior; a List needed index reads.

images.draw_rectfn
fn draw_rect(img: Image, x: Int, y: Int, w: Int, h: Int, r: Int, g: Int, b: Int) -> Image

The image with a filled rectangle drawn on it (clipped to the canvas).

images.draw_linefn
fn draw_line(img: Image, x1: Int, y1: Int, x2: Int, y2: Int, r: Int, g: Int, b: Int) -> Image

The image with a straight line drawn on it (Bresenham, clipped).

images.draw_circlefn
fn draw_circle(img: Image, cx: Int, cy: Int, radius: Int, r: Int, g: Int, b: Int) -> Image

The image with a filled circle drawn on it (clipped).

images.draw_ellipsefn
fn draw_ellipse(img: Image, cx: Int, cy: Int, rx: Int, ry: Int, r: Int, g: Int, b: Int) -> Image

The image with a filled ellipse drawn on it (clipped) — since v5.

images.draw_ellipse_outlinefn
fn draw_ellipse_outline(img: Image, cx: Int, cy: Int, rx: Int, ry: Int, r: Int, g: Int, b: Int) -> Image

The image with a one-pixel ellipse ring drawn on it — since v5.

images.draw_circle_outlinefn
fn draw_circle_outline(img: Image, cx: Int, cy: Int, radius: Int, r: Int, g: Int, b: Int) -> Image

The image with a one-pixel circle ring drawn on it — since v5.

images.draw_rect_outlinefn
fn draw_rect_outline(img: Image, x: Int, y: Int, w: Int, h: Int, r: Int, g: Int, b: Int) -> Image

The image with a one-pixel rectangle outline drawn on it — since v5.

images.draw_thick_linefn
fn draw_thick_line(img: Image, x1: Int, y1: Int, x2: Int, y2: Int, width: Int, r: Int, g: Int, b: Int) -> Image

The image with a line of the given stroke width (a square stamp per Bresenham step, clipped) — since v5. Width 1 is draw_line.

images.draw_polylinefn
fn draw_polyline(img: Image, points: List[Int], r: Int, g: Int, b: Int) -> Image

The image with connected segments through the points (flat x y pairs) — since v5: a brush stroke is one op, not one line per segment.

images.to_ppm_bytesfn
fn to_ppm_bytes(img: Image) -> Bytes

The single export bridge for viewing: binary PPM (P6) bytes.

images.from_ppm_bytesfn
fn from_ppm_bytes(raw: Bytes) -> Result[Image, Text]

The inverse bridge (since Sprint 27): parses the P6 bytes to_ppm_bytes writes — and any binary PPM with maxval 255 — back into an Image, so existing pictures can enter the toolkit.

images.draw_gradientfn
fn draw_gradient(img: Image, x: Int, y: Int, w: Int, h: Int, r1: Int, g1: Int, b1: Int, r2: Int, g2: Int, b2: Int, direction: Text) -> Image

A linear (`"vertical"`/`"horizontal"`) or `"radial"` gradient fill over the clipped region — any other direction behaves as vertical (v2 toolkit, Sprint 35).

images.draw_polygonfn
fn draw_polygon(img: Image, points: List[Int], r: Int, g: Int, b: Int) -> Image

A filled polygon from flat x/y pairs (even-odd scanline fill, clipped). Fewer than three points paints nothing (v2 toolkit).

images.flood_fillfn
fn flood_fill(img: Image, x: Int, y: Int, r: Int, g: Int, b: Int) -> Image

Four-connected flood fill from (x, y) — the v3 toolkit twin.

images.draw_opsfn
fn draw_ops(img: Image, ops: Text) -> Result[Image, Text]

Applies a draw-section's operations (the full v4 op set, hex colors) onto an existing image — the primitive that makes layers and imported pictures composable (Sprint 38): each op line is exactly a .pti draw: line without its indentation.

images.draw_textfn
fn draw_text(img: Image, x: Int, y: Int, size: Int, r: Int, g: Int, b: Int, content: Text) -> Image

Draws text in the built-in 5×7 pixel font at (x, y), scaled by whole pixels (v4 toolkit, Sprint 40). Unknown characters draw nothing; letters are case-insensitive; spaces advance the pen.

images.cropfn
fn crop(img: Image, x: Int, y: Int, w: Int, h: Int) -> Image

The w×h region of the image starting at (x, y); out-of-canvas parts read as black.

images.flip_xfn
fn flip_x(img: Image) -> Image

The image mirrored left–right.

images.flip_yfn
fn flip_y(img: Image) -> Image

The image mirrored top–bottom.

images.scalefn
fn scale(img: Image, factor: Int) -> Image

The image scaled up by a whole factor (nearest neighbor).

images.blitfn
fn blit(dst: Image, src: Image, x: Int, y: Int) -> Image

The destination with `src` painted onto it at (x, y), clipped.

images.map_pixelsfn
fn map_pixels(img: Image, f: fn(Int, Int, Int) -> List[Int]) -> Image

A new image with `f` applied to every pixel's r/g/b triple; results are clamped to 0–255.

images.invertfn
fn invert(img: Image) -> Image

Every channel inverted.

images.grayscalefn
fn grayscale(img: Image) -> Image

Luma grayscale (Rec. 601 weights).

images.brightenfn
fn brighten(img: Image, amount: Int) -> Image

Every channel shifted by `amount` (negative darkens), clamped.

images.renderfn
fn render(source: Text) -> Result[Image, Text]

Renders .pti source text into an Image (formats/pti-image.md).

import ints7

ints.minfn
fn min(a: Int, b: Int) -> Int

The smaller of two integers.

ints.maxfn
fn max(a: Int, b: Int) -> Int

The larger of two integers.

ints.clampfn
fn clamp(x: Int, lo: Int, hi: Int) -> Int

Clamps x into the inclusive range [lo, hi].

ints.signfn
fn sign(x: Int) -> Int

-1 for negative numbers, 0 for zero, 1 for positive numbers.

ints.is_evenfn
fn is_even(n: Int) -> Bool

Whether n is divisible by two — zero and negatives included (is_even(0) and is_even(-2) are true).

ints.powfn
fn pow(base: Int, exp: Int) -> Int

base raised to a non-negative exponent (asserts exp >= 0).

ints.gcdfn
fn gcd(a: Int, b: Int) -> Int

The greatest common divisor of two integers (always non-negative).

import json3

Jsonenum
Json.Null
Json.Bool(value: Bool)
Json.Int(value: Int)
Json.Float(value: Float)
Json.Str(value: Text)
Json.Arr(items: List[Json])
Json.Obj(entries: Map[Text, Json])

A parsed JSON value. Match on it to read a document; absence of a key is `Map.get -> None`, never null-the-language-feature.

json.parsefn
fn parse(text: Text) -> Result[Json, Text]

Parses a JSON document into a Json value; trailing content after the value (other than whitespace) is an error.

json.to_textfn
fn to_text(json: Json) -> Text

Serializes a Json value to canonical JSON text — compact (no spaces), objects in insertion order, output always literal UTF-8.

import lists24

lists.sumfn
fn sum(xs: List[Int]) -> Int

The sum of all elements (0 for the empty list).

lists.productfn
fn product(xs: List[Int]) -> Int

The product of all elements (1 for the empty list).

lists.rangefn
fn range(from: Int, to: Int) -> List[Int]

The integers from `from` (inclusive) to `to` (exclusive).

lists.largestfn
fn largest(xs: List[Int]) -> Option[Int]

The largest element, or None for the empty list.

lists.smallestfn
fn smallest(xs: List[Int]) -> Option[Int]

The smallest element, or None for the empty list.

lists.count_wherefn
fn count_where(xs: List[Int], pred: fn(Int) -> Bool) -> Int

How many elements satisfy the predicate.

lists.index_offn
fn index_of[T](xs: List[T], x: T) -> Int

The index of the first element equal to `x`, or -1 (since Sprint 32 — the first generic functions in the stdlib).

lists.reversedfn
fn reversed[T](xs: List[T]) -> List[T]

The list in reverse order.

lists.takefn
fn take[T](xs: List[T], n: Int) -> List[T]

The first `n` elements (fewer when the list is shorter).

lists.dropfn
fn drop[T](xs: List[T], n: Int) -> List[T]

Everything after the first `n` elements.

lists.zipfn
fn zip[A, B](xs: List[A], ys: List[B]) -> List[Tuple[A, B]]

Pairs elements up to the shorter length (since Sprint 33 — the first generic function returning tuples of two parameters).

lists.enumeratefn
fn enumerate[T](xs: List[T]) -> List[Tuple[Int, T]]

Pairs each element with its zero-based index (`(0, x0), (1, x1), …`).

lists.zip_withfn
fn zip_with[A, B, C](xs: List[A], ys: List[B], f: fn(A, B) -> C) -> List[C]

Combines two lists element-wise with `f`, to the shorter length.

lists.unzipfn
fn unzip[A, B](pairs: List[Tuple[A, B]]) -> Tuple[List[A], List[B]]

Splits a list of pairs into a pair of lists — the inverse of `zip`.

lists.anyfn
fn any[T](xs: List[T], pred: fn(T) -> Bool) -> Bool

True if any element satisfies the predicate (false for the empty list).

lists.allfn
fn all[T](xs: List[T], pred: fn(T) -> Bool) -> Bool

True if every element satisfies the predicate (true for the empty list).

lists.findfn
fn find[T](xs: List[T], pred: fn(T) -> Bool) -> Option[T]

The first element satisfying the predicate, or None.

lists.uniquefn
fn unique[T](xs: List[T]) -> List[T]

The distinct elements, in first-seen order. O(n²) — a linear `contains` scan per element, since element types need only equality, not hashing or ordering.

lists.flattenfn
fn flatten[T](xss: List[List[T]]) -> List[T]

One flat list from a list of lists, preserving order.

lists.chunkfn
fn chunk[T](xs: List[T], size: Int) -> List[List[T]]

The list split into consecutive chunks of at most `size` (which must be positive; a non-positive size yields the whole list as one chunk).

lists.min_byfn
fn min_by[T](xs: List[T], key: fn(T) -> Int) -> Option[T]

The element with the smallest key, or None for the empty list.

lists.max_byfn
fn max_by[T](xs: List[T], key: fn(T) -> Int) -> Option[T]

The element with the largest key, or None for the empty list.

lists.sort_byfn
fn sort_by[T](xs: List[T], key: fn(T) -> Int) -> List[T]

The list ordered by an integer key (stable insertion sort — the generic companion to the builtin `sorted`, which handles Int/Float/ Text directly). O(n²): for a large list ordered by an Int/Float/Text key, prefer the builtin `sorted`.

lists.group_byfn
fn group_by[T](xs: List[T], key: fn(T) -> Int) -> Map[Int, List[T]]

Groups elements by an integer key, preserving first-seen key order and per-group element order.

import maps6

maps.get_orfn
fn get_or[K, V](m: Map[K, V], key: K, default: V) -> V

The value for `key`, or `default` when the key is absent.

maps.mergefn
fn merge[K, V](a: Map[K, V], b: Map[K, V]) -> Map[K, V]

`a` and `b` merged into one map; on a shared key, `b` wins.

maps.map_valuesfn
fn map_values[K, V, W](m: Map[K, V], f: fn(V) -> W) -> Map[K, W]

The map with `f` applied to every value; keys are unchanged.

maps.from_listsfn
fn from_lists[K, V](keys: List[K], values: List[V]) -> Map[K, V]

A map from parallel key and value lists, paired to the shorter length; a later duplicate key overwrites an earlier one.

maps.invertfn
fn invert[K, V](m: Map[K, V]) -> Map[V, K]

The map with keys and values swapped. When several keys share a value, the last one (in insertion order) wins.

maps.filterfn
fn filter[K, V](m: Map[K, V], pred: fn(K, V) -> Bool) -> Map[K, V]

The entries whose `(key, value)` satisfy the predicate.

import maths14

maths.pifn
fn pi() -> Float

The ratio of a circle's circumference to its diameter.

maths.taufn
fn tau() -> Float

Two pi — a full turn in radians.

maths.efn
fn e() -> Float

Euler's number, the base of the natural logarithm.

maths.minfn
fn min(a: Float, b: Float) -> Float

The smaller of two floats.

maths.maxfn
fn max(a: Float, b: Float) -> Float

The larger of two floats.

maths.clampfn
fn clamp(x: Float, lo: Float, hi: Float) -> Float

Clamps x into the inclusive range [lo, hi].

maths.signfn
fn sign(x: Float) -> Float

-1.0 for negatives, 0.0 for zero, 1.0 for positives.

maths.powfn
fn pow(base: Float, exp: Int) -> Float

base raised to an integer exponent (negative exponents invert).

maths.hypotfn
fn hypot(x: Float, y: Float) -> Float

The length of the hypotenuse — sqrt(x*x + y*y).

maths.tanfn
fn tan(x: Float) -> Float

The tangent of an angle in radians.

maths.to_degreesfn
fn to_degrees(radians: Float) -> Float

Converts radians to degrees.

maths.to_radiansfn
fn to_radians(degrees: Float) -> Float

Converts degrees to radians.

maths.lerpfn
fn lerp(a: Float, b: Float, t: Float) -> Float

Linear interpolation from a to b by t (t = 0 gives a, t = 1 gives b).

maths.round_tofn
fn round_to(x: Float, places: Int) -> Float

Rounds x to a number of decimal places (asserts places >= 0).

import mesh13

Meshrecord
vertices: List[Float]
faces: List[Int]
colors: List[Int]

A triangle mesh: flat vertex coordinates (3 floats per vertex), flat face indices (3 zero-based vertex indices per triangle), and flat RGB colors (3 ints 0–255 per triangle, version 2).

mesh.add_boxfn
fn add_box(m: Mesh, w: Float, h: Float, d: Float, x: Float, y: Float, z: Float) -> Mesh

A mesh with a cuboid appended: w×h×d, centered on x/z, base at y.

mesh.add_planefn
fn add_plane(m: Mesh, w: Float, d: Float, x: Float, y: Float, z: Float) -> Mesh

A mesh with a flat ground rectangle appended (w×d, centered).

mesh.add_spherefn
fn add_sphere(m: Mesh, r: Float, segments: Int, x: Float, y: Float, z: Float) -> Mesh

A mesh with a UV sphere appended (radius r, `segments` around the equator, segments / 2 rings).

mesh.add_cylinderfn
fn add_cylinder(m: Mesh, r: Float, h: Float, segments: Int, x: Float, y: Float, z: Float) -> Mesh

A cylinder: two rings of `segments` points, wall quads, capped — v3.

mesh.add_conefn
fn add_cone(m: Mesh, r: Float, h: Float, segments: Int, x: Float, y: Float, z: Float) -> Mesh

A cone: a base ring, an apex, wall triangles and a base fan — v3.

mesh.add_torusfn
fn add_torus(m: Mesh, big_r: Float, small_r: Float, segments: Int, x: Float, y: Float, z: Float) -> Mesh

A torus: a segments x segments grid of quads around the ring — v3.

mesh.renderfn
fn render(source: Text) -> Result[Mesh, Text]

Tessellates .ptm source text into a Mesh (formats/ptm-model.md).

mesh.to_obj_bytesfn
fn to_obj_bytes(m: Mesh) -> Bytes

The single export bridge for viewing: Wavefront OBJ text as bytes.

mesh.render_viewfn
fn render_view(m: Mesh, width: Int, height: Int, yaw: Float, pitch: Float) -> images.Image

A rendered orbit view of the mesh (Sprint 45): the camera is auto-framed on the model's bounding sphere (2.2 radii away), yaw orbits around y and pitch tilts the camera up (both in degrees), occlusion is decided per pixel by a 1/z depth buffer (Sprint 234) with two-sided shading against a fixed world-space key light.

mesh.render_view_fromfn
fn render_view_from(m: Mesh, width: Int, height: Int, yaw: Float, pitch: Float, zoom: Float) -> images.Image

The orbit view at a chosen camera distance (Sprint 178): `zoom` is a factor on the automatic framing distance — `1.0` frames the whole model exactly like `render_view`, `0.5` moves twice as close, `2.0` twice as far. Values are clamped to `0.2`–`8.0`, so a wild factor degrades gracefully instead of clipping through the model.

mesh.render_view_finefn
fn render_view_fine(m: Mesh, width: Int, height: Int, yaw: Float, pitch: Float, zoom: Float, bg_r: Int, bg_g: Int, bg_b: Int) -> images.Image

The fine orbit view (Sprint 179): the same rasterizer rendered at twice the size and box-averaged down (2×2 supersampling — crisp edges from the identical geometry), a soft fill light so undersides read instead of falling to black, and a chosen background (RGB 0–255, clamped). Costs four times the pixels of [`render_view_from`]; the fast path stays exactly as it was.

mesh.render_view_showcasefn
fn render_view_showcase(m: Mesh, width: Int, height: Int, yaw: Float, pitch: Float, zoom: Float) -> images.Image

The showcase view (Sprint 218, M35): the fine render under a sky — a vertical gradient background and soft ground shadows cast along the key light onto the model's base plane, 2×2 supersampled like [`render_view_fine`]. The scene look the workshop opens with; existing entries are untouched (this is additive).

import patterns3

patterns.matches_globfn
fn matches_glob(pattern: Text, text: Text) -> Bool

Whether `text` matches a shell glob `pattern` in full. `*` matches any run of characters (including none), `?` exactly one, `[a-z]` / `[!a-z]` a character class; everything else is literal.

patterns.matchesfn
fn matches(pattern: Text, text: Text) -> Result[Bool, Text]

Whether `text` matches the regex `pattern` in full (anchored at both ends). Returns a teaching error for a malformed pattern rather than a silent mismatch. Supports literals, `.`, `[classes]`, the shorthands `\d \w \s` (and `\D \W \S`), alternation `a|b`, groups `(...)`, and the quantifiers `* + ? {n} {n,} {n,m}`.

patterns.capturesfn
fn captures(pattern: Text, text: Text) -> Result[Option[List[Text]], Text]

The whole match plus each group's captured substring (group order), when `pattern` matches `text` in full (anchored); `Ok(None)` when it does not; a teaching error for a malformed pattern. A group that did not participate captures `""`; a repeated group captures its last iteration. Consistent with `matches` on whether the text matches, and polynomial (no catastrophic backtracking).

import pkg6

Deprecord
name: Text
min_version: Text

One dependency: a package name and the minimum version that works.

Packagerecord
name: Text
pkg_version: Text
summary: Text
deps: List[Dep]
modules: List[Text]

A parsed package manifest.

pkg.renderfn
fn render(source: Text) -> Result[Package, Text]

Parses polytone.pkg source text (formats/pkg-manifest.md).

PackageRefrecord
name: Text
pkg_version: Text
summary: Text

One package listed by a registry index.

Registryrecord
title: Text
packages: List[PackageRef]

A parsed registry index (formats/registry-index.md).

pkg.render_indexfn
fn render_index(source: Text) -> Result[Registry, Text]

Parses index.ptr source text (formats/registry-index.md).

import sets7

sets.unionfn
fn union[T](a: Set[T], b: Set[T]) -> Set[T]

Every element of `a` and `b` (union). `b`'s elements are added to a copy of `a`'s.

sets.intersectionfn
fn intersection[T](a: Set[T], b: Set[T]) -> Set[T]

The elements in both `a` and `b` (intersection).

sets.differencefn
fn difference[T](a: Set[T], b: Set[T]) -> Set[T]

The elements of `a` that are not in `b` (difference, `a - b`).

sets.symmetric_differencefn
fn symmetric_difference[T](a: Set[T], b: Set[T]) -> Set[T]

The elements in exactly one of `a` or `b` (symmetric difference).

sets.is_subsetfn
fn is_subset[T](a: Set[T], b: Set[T]) -> Bool

True if every element of `a` is in `b`.

sets.is_supersetfn
fn is_superset[T](a: Set[T], b: Set[T]) -> Bool

True if every element of `b` is in `a`.

sets.is_disjointfn
fn is_disjoint[T](a: Set[T], b: Set[T]) -> Bool

True if `a` and `b` share no elements.

import tasks1

tasks.allfn
fn all[T](ts: List[Task[T]]) -> List[T]

Drives every task in list order and collects the results.

import texts4

texts.repeatfn
fn repeat(s: Text, times: Int) -> Text

s repeated `times` times ("" for zero or negative counts).

texts.pad_leftfn
fn pad_left(s: Text, width: Int, fill: Text) -> Text

Pads s on the left with `fill` (one character) until it is `width` long. An empty `fill` cannot add width, so s is returned unchanged.

texts.pad_rightfn
fn pad_right(s: Text, width: Int, fill: Text) -> Text

Pads s on the right with `fill` (one character) until it is `width` long. An empty `fill` cannot add width, so s is returned unchanged.

texts.is_blankfn
fn is_blank(s: Text) -> Bool

Whether s is empty or whitespace-only.

import time18

Instantrecord
epoch_second: Int
Instant.civil(self) -> CivilThis instant as broken-down UTC calendar fields.
Instant.iso(self) -> TextThis instant in RFC 3339 form, e.g. "2026-08-06T12:00:00Z".
Instant.plus(self, d: Duration) -> InstantThis instant moved forward by `d`.
Instant.minus(self, d: Duration) -> InstantThis instant moved back by `d`.
Instant.until(self, other: Instant) -> DurationThe span from this instant to `other` (negative when `other` is earlier).
Instant.is_before(self, other: Instant) -> BoolWhether this instant is strictly before `other`.
Instant.is_after(self, other: Instant) -> BoolWhether this instant is strictly after `other`.

A point on the UTC timeline: seconds since the Unix epoch (1970-01-01T00:00:00Z). Negative values are before the epoch.

Durationrecord
seconds: Int
Duration.in_minutes(self) -> IntThis span in whole minutes, truncated toward zero.
Duration.in_hours(self) -> IntThis span in whole hours, truncated toward zero.
Duration.in_days(self) -> IntThis span in whole days, truncated toward zero.
Duration.abs(self) -> DurationThe same span without a sign.

A signed span of time, in whole seconds.

Civilrecord
year: Int
month: Int
day: Int
hour: Int
minute: Int
second: Int
weekday: Int

Broken-down UTC calendar fields. `weekday` is 0=Sunday .. 6=Saturday.

time.is_leapfn
fn is_leap(year: Int) -> Bool

Whether a year is a leap year in the proleptic Gregorian calendar.

time.days_in_monthfn
fn days_in_month(year: Int, month: Int) -> Int

The number of days in a month (1-12); asserts the month is in range.

time.of_civilfn
fn of_civil(year: Int, month: Int, day: Int, hour: Int, minute: Int, second: Int) -> Result[Instant, Text]

Builds an Instant from UTC calendar fields, validating every field; returns a teaching error (never a silently wrong date) on any range violation, February 30th included.

time.to_civilfn
fn to_civil(instant: Instant) -> Civil

Breaks an Instant down into UTC calendar fields.

time.addfn
fn add(instant: Instant, d: Duration) -> Instant

The instant `d` after the given one.

time.subfn
fn sub(instant: Instant, d: Duration) -> Instant

The instant `d` before the given one.

time.betweenfn
fn between(a: Instant, b: Instant) -> Duration

The span from `a` to `b` (positive when b is later than a).

time.beforefn
fn before(a: Instant, b: Instant) -> Bool

Whether `a` is strictly before `b`.

time.afterfn
fn after(a: Instant, b: Instant) -> Bool

Whether `a` is strictly after `b`.

time.secondsfn
fn seconds(n: Int) -> Duration

A duration of n seconds.

time.minutesfn
fn minutes(n: Int) -> Duration

A duration of n minutes.

time.hoursfn
fn hours(n: Int) -> Duration

A duration of n hours.

time.daysfn
fn days(n: Int) -> Duration

A duration of n days.

time.weeksfn
fn weeks(n: Int) -> Duration

A duration of n weeks.

time.to_isofn
fn to_iso(instant: Instant) -> Text

Formats an Instant as ISO 8601 UTC — "YYYY-MM-DDTHH:MM:SSZ".

import toml4

Valueenum
Value.Str(s: Text)
Value.Int(n: Int)
Value.Bool(b: Bool)
Value.Arr(items: List[Value])

A TOML scalar or array value.

Tablerecord
name: Text
pairs: List[Tuple[Text, Value]]
Table.get(self, key: Text) -> Option[Value] — The value stored under `key`, if the table has one.
Table.has(self, key: Text) -> BoolWhether the table carries `key`.
Table.text(self, key: Text) -> Option[Text] — The Text under `key`, if it is present and is a string.
Table.int(self, key: Text) -> Option[Int] — The Int under `key`, if it is present and is a number.
Table.keys(self) -> List[Text] — The keys in declaration order.

One table: its header name ("" for the root) and its ordered pairs.

toml.parsefn
fn parse(text: Text) -> Result[List[Table], Text]

Parses TOML text into an ordered list of tables. The root table (keys before any `[header]`) comes first with name "". A malformed line is a typed error.

toml.serializefn
fn serialize(tables: List[Table]) -> Text

Serializes tables back to TOML text (the inverse of parse).

import url2

url.encodefn
fn encode(text: Text) -> Text

Percent-encodes text: unreserved characters pass through, every other UTF-8 byte becomes %XX.

url.decodefn
fn decode(text: Text) -> Result[Text, Text]

Decodes a percent-encoded string. A truncated or non-hex escape, or bytes that are not valid UTF-8, is an error.

import uuid1

uuid.v4fn
fn v4(gen: Rng) -> Text

A fresh random UUID (version 4). Draws sixteen bytes from `gen`, sets the version nibble to 4 and the variant bits to 10 (RFC 4122 §4.4), and renders `xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`.

import video3

Videorecord
width: Int
height: Int
fps: Int
frames: List[Int]
audio: Text

Rendered video: dimensions, frame rate, flat RGB frame data (width × height × 3 ints per frame, frames in order) — and since v2 the soundtrack (`""` = none): a relative `.pta` address — or, since v3's embedded `audio:` block, the full `.pta` source itself (embedded source contains newlines; a reference never does). Hosts render it through the audio codec; the video codec stays pure.

video.renderfn
fn render(source: Text) -> Result[Video, Text]

Renders .ptv source text into a Video (formats/ptv-video.md).

video.to_y4m_bytesfn
fn to_y4m_bytes(v: Video) -> Bytes

The single export bridge for playback: an uncompressed YUV4MPEG2 (C444) stream — `ffplay out.y4m` / `mpv out.y4m` play it directly.

import web5

Blockenum
Block.Heading(level: Int, text: Text)
Block.Paragraph(text: Text)
Block.Code(text: Text)
Block.Bullets(items: List[Text])
Block.Link(url: Text, label: Text)
Block.Image(source: Text, alt: Text)
Block.Film(source: Text, alt: Text)
Block.Sound(source: Text, alt: Text)
Block.Input(name: Text, label: Text)
Block.Button(target: Text, label: Text)
Block.Quote(text: Text)
Block.Note(text: Text)
Block.Table(head: List[Text], rows: List[List[Text]])
Block.Nav(links: List[Tuple[Text, Text]])
Block.Rule

One typed document block — markup never exists as strings. Image/Film/Sound reference native documents by relative address (since v2, Sprint 34).

Documentrecord
title: Text
blocks: List[Block]

A parsed document: title plus blocks in order.

web.renderfn
fn render(source: Text) -> Result[Document, Text]

Parses .ptw source text into a Document (formats/ptw-web.md).

web.form_valuefn
fn form_value(submitted: List[Text], name: Text) -> Option[Text]

Reads a form field from program arguments (v3, Sprint 41): the viewer submits each input as one `name=value` argument with spaces encoded as '+'. Missing fields are None; empty submissions are Some("").

web.to_html_bytesfn
fn to_html_bytes(doc: Document, assets: Map[Text, images.Image]) -> Bytes

The single export bridge: a standalone HTML page as bytes. `assets` maps image-block sources to rendered images — supplied ones embed as BMP data URIs, so the page stays self-contained; missing ones (and film/sound blocks) render as addressed links (v2, Sprint 34).