API reference
Every pub item of the standard library — 187 entries across 24 modules, generated from the code that ships (ptc doc at build time). This page cannot drift.
import audio13
Soundrecordrate: Int samples: List[Int]
Rendered sound: sample rate plus 16-bit signed samples (mono).
audio.renderfnfn 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.silencefnfn silence(ms: Int) -> Sound
Silence of the given length in milliseconds (at 44100 Hz).
audio.tonefnfn tone(note: Text, ms: Int, wave: Text, volume: Int) -> Result[Sound, Text]
A single synthesized note, e.g. tone("c4", 500, "sine", 80).
audio.appendfnfn append(a: Sound, b: Sound) -> Sound
b played after a.
audio.mixfnfn mix(a: Sound, b: Sound) -> Sound
a and b played together (summed, clamped); length is the longer one.
audio.gainfnfn gain(s: Sound, percent: Int) -> Sound
The sound scaled to `percent` loudness (0–200), clamped.
audio.repeatfnfn repeat(s: Sound, times: Int) -> Sound
The sound repeated `times` times.
audio.adsrfnfn 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_bytesfnfn to_wav_bytes(sound: Sound) -> Bytes
The single export bridge for playback: RIFF/WAVE PCM bytes.
Stereorecordrate: 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_stereofnfn 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_stereofnfn 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.encodefnfn encode(bytes: Bytes) -> Text
Encodes bytes as Base64 with `=` padding.
base64.decodefnfn 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.sha256fnfn sha256(msg: Bytes) -> Bytes
SHA-256 of the given bytes, as a 32-byte digest.
crypto.sha256_hexfnfn sha256_hex(msg: Bytes) -> Text
SHA-256 as a lowercase hex string.
crypto.hmac_sha256fnfn hmac_sha256(key: Bytes, msg: Bytes) -> Bytes
HMAC-SHA-256 (RFC 2104) of `msg` under `key`, as a 32-byte tag.
crypto.hmac_sha256_hexfnfn hmac_sha256_hex(key: Bytes, msg: Bytes) -> Text
HMAC-SHA-256 as a lowercase hex string.
crypto.crc32fnfn crc32(msg: Bytes) -> Int
CRC-32 (IEEE 802.3, the zip/png checksum), computed bit by bit.
import csv2
csv.parsefnfn 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.serializefnfn 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.encodefnfn encode(bytes: Bytes) -> Text
Lowercase hex, two digits per byte (the builtin `Bytes.to_hex`).
hex.decodefnfn 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
MethodenumMethod.Get Method.Post Method.Put Method.Delete Method.Patch Method.Head Method.Options
An HTTP request method.
Statusrecordcode: Int Status.ok(self) -> Bool — Whether the request succeeded (2xx). Status.client_error(self) -> Bool — Whether the caller made a mistake (4xx). Status.server_error(self) -> Bool — Whether the server failed (5xx).
An HTTP status code (200, 404, 500, …).
Requestrecordmethod: Method url: Text headers: Map[Text, Text] body: Option[Bytes] Request.with_header(self, name: Text, value: Text) -> Request — The same request carrying one more header.
An HTTP request: a method, a URL, headers, and an optional body.
Responserecordstatus: Status headers: Map[Text, Text] body: Bytes Response.ok(self) -> Bool — Whether 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.getfnfn get(url: Text) -> Request
A GET request for a URL, no headers or body — the common case.
http.postfnfn post(url: Text, body: Bytes) -> Request
A POST request carrying a body.
http.requestfnfn request(method: Method, url: Text, headers: Map[Text, Text], body: Option[Bytes]) -> Request
A request with every field given explicitly.
http.is_successfnfn is_success(status: Status) -> Bool
Whether a status is a success (200–299).
http.is_client_errorfnfn is_client_error(status: Status) -> Bool
Whether a status is a client error (400–499).
http.is_server_errorfnfn is_server_error(status: Status) -> Bool
Whether a status is a server error (500–599).
import images32
Imagerecordwidth: 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.canvasfnfn 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_pixelfnfn 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_pixelfnfn 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_rectfnfn 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_linefnfn 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_circlefnfn 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_ellipsefnfn 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_outlinefnfn 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_outlinefnfn 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_outlinefnfn 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_linefnfn 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_polylinefnfn 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_bytesfnfn to_ppm_bytes(img: Image) -> Bytes
The single export bridge for viewing: binary PPM (P6) bytes.
images.from_ppm_bytesfnfn 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_gradientfnfn 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_polygonfnfn 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_fillfnfn 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_opsfnfn 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_textfnfn 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.draw_labelfnfn draw_label(img: Image, x: Int, y: Int, size: Int, r: Int, g: Int, b: Int, content: Text) -> Image
Draws `content` in the 5×9 system font at (x, y), scaled by whole pixels (v6, Sprint 275): every printable ASCII character has its own glyph — lowercase included —, any other character draws the replacement box, and the pen advances 6 × `size` per character (a line is 10 × `size` tall). This is the font POLY-OS reads with.
images.label_widthfnfn label_width(content: Text, size: Int) -> Int
The pixel width `draw_label` needs for `content` at `size`: six pixels per character (a layout helper, so text fits its box).
images.cropfnfn 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_xfnfn flip_x(img: Image) -> Image
The image mirrored left–right.
images.flip_yfnfn flip_y(img: Image) -> Image
The image mirrored top–bottom.
images.scalefnfn scale(img: Image, factor: Int) -> Image
The image scaled up by a whole factor (nearest neighbor).
images.blitfnfn blit(dst: Image, src: Image, x: Int, y: Int) -> Image
The destination with `src` painted onto it at (x, y), clipped.
images.map_pixelsfnfn 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.invertfnfn invert(img: Image) -> Image
Every channel inverted.
images.grayscalefnfn grayscale(img: Image) -> Image
Luma grayscale (Rec. 601 weights).
images.brightenfnfn brighten(img: Image, amount: Int) -> Image
Every channel shifted by `amount` (negative darkens), clamped.
images.renderfnfn render(source: Text) -> Result[Image, Text]
Renders .pti source text into an Image (formats/pti-image.md).
import ints7
ints.minfnfn min(a: Int, b: Int) -> Int
The smaller of two integers.
ints.maxfnfn max(a: Int, b: Int) -> Int
The larger of two integers.
ints.clampfnfn clamp(x: Int, lo: Int, hi: Int) -> Int
Clamps x into the inclusive range [lo, hi].
ints.signfnfn sign(x: Int) -> Int
-1 for negative numbers, 0 for zero, 1 for positive numbers.
ints.is_evenfnfn 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.powfnfn pow(base: Int, exp: Int) -> Int
base raised to a non-negative exponent (asserts exp >= 0).
ints.gcdfnfn gcd(a: Int, b: Int) -> Int
The greatest common divisor of two integers (always non-negative).
import json3
JsonenumJson.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.parsefnfn 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_textfnfn 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.sumfnfn sum(xs: List[Int]) -> Int
The sum of all elements (0 for the empty list).
lists.productfnfn product(xs: List[Int]) -> Int
The product of all elements (1 for the empty list).
lists.rangefnfn range(from: Int, to: Int) -> List[Int]
The integers from `from` (inclusive) to `to` (exclusive).
lists.largestfnfn largest(xs: List[Int]) -> Option[Int]
The largest element, or None for the empty list.
lists.smallestfnfn smallest(xs: List[Int]) -> Option[Int]
The smallest element, or None for the empty list.
lists.count_wherefnfn count_where(xs: List[Int], pred: fn(Int) -> Bool) -> Int
How many elements satisfy the predicate.
lists.index_offnfn 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.reversedfnfn reversed[T](xs: List[T]) -> List[T]
The list in reverse order.
lists.takefnfn take[T](xs: List[T], n: Int) -> List[T]
The first `n` elements (fewer when the list is shorter).
lists.dropfnfn drop[T](xs: List[T], n: Int) -> List[T]
Everything after the first `n` elements.
lists.zipfnfn 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.enumeratefnfn enumerate[T](xs: List[T]) -> List[Tuple[Int, T]]
Pairs each element with its zero-based index (`(0, x0), (1, x1), …`).
lists.zip_withfnfn 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.unzipfnfn 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.anyfnfn any[T](xs: List[T], pred: fn(T) -> Bool) -> Bool
True if any element satisfies the predicate (false for the empty list).
lists.allfnfn all[T](xs: List[T], pred: fn(T) -> Bool) -> Bool
True if every element satisfies the predicate (true for the empty list).
lists.findfnfn find[T](xs: List[T], pred: fn(T) -> Bool) -> Option[T]
The first element satisfying the predicate, or None.
lists.uniquefnfn 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.flattenfnfn flatten[T](xss: List[List[T]]) -> List[T]
One flat list from a list of lists, preserving order.
lists.chunkfnfn 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_byfnfn 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_byfnfn 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_byfnfn 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_byfnfn 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_orfnfn 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.mergefnfn 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_valuesfnfn 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_listsfnfn 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.invertfnfn 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.filterfnfn 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.pifnfn pi() -> Float
The ratio of a circle's circumference to its diameter.
maths.taufnfn tau() -> Float
Two pi — a full turn in radians.
maths.efnfn e() -> Float
Euler's number, the base of the natural logarithm.
maths.minfnfn min(a: Float, b: Float) -> Float
The smaller of two floats.
maths.maxfnfn max(a: Float, b: Float) -> Float
The larger of two floats.
maths.clampfnfn clamp(x: Float, lo: Float, hi: Float) -> Float
Clamps x into the inclusive range [lo, hi].
maths.signfnfn sign(x: Float) -> Float
-1.0 for negatives, 0.0 for zero, 1.0 for positives.
maths.powfnfn pow(base: Float, exp: Int) -> Float
base raised to an integer exponent (negative exponents invert).
maths.hypotfnfn hypot(x: Float, y: Float) -> Float
The length of the hypotenuse — sqrt(x*x + y*y).
maths.tanfnfn tan(x: Float) -> Float
The tangent of an angle in radians.
maths.to_degreesfnfn to_degrees(radians: Float) -> Float
Converts radians to degrees.
maths.to_radiansfnfn to_radians(degrees: Float) -> Float
Converts degrees to radians.
maths.lerpfnfn 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_tofnfn round_to(x: Float, places: Int) -> Float
Rounds x to a number of decimal places (asserts places >= 0).
import mesh13
Meshrecordvertices: List[Float] faces: List[Int] colors: List[Int] cullable: List[Bool]
A triangle mesh: flat vertex coordinates (3 floats per vertex), flat face indices (3 zero-based vertex indices per triangle), flat RGB colors (3 ints 0–255 per triangle, version 2), and one flag per triangle saying whether the view may skip it when it faces away (version 4 `cullable` — closed shapes only, wound outward so the screen winding decides; a shorter or empty list means never).
mesh.add_boxfnfn 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_planefnfn 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_spherefnfn 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_cylinderfnfn 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_conefnfn 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_torusfnfn 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.renderfnfn render(source: Text) -> Result[Mesh, Text]
Tessellates .ptm source text into a Mesh (formats/ptm-model.md).
mesh.to_obj_bytesfnfn to_obj_bytes(m: Mesh) -> Bytes
The single export bridge for viewing: Wavefront OBJ text as bytes.
mesh.render_viewfnfn 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_fromfnfn 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_finefnfn 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_showcasefnfn 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_globfnfn 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.matchesfnfn 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.capturesfnfn 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
Deprecordname: Text min_version: Text
One dependency: a package name and the minimum version that works.
Packagerecordname: Text pkg_version: Text summary: Text deps: List[Dep] modules: List[Text]
A parsed package manifest.
pkg.renderfnfn render(source: Text) -> Result[Package, Text]
Parses polytone.pkg source text (formats/pkg-manifest.md).
PackageRefrecordname: Text pkg_version: Text summary: Text
One package listed by a registry index.
Registryrecordtitle: Text packages: List[PackageRef]
A parsed registry index (formats/registry-index.md).
pkg.render_indexfnfn render_index(source: Text) -> Result[Registry, Text]
Parses index.ptr source text (formats/registry-index.md).
import sets7
sets.unionfnfn 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.intersectionfnfn intersection[T](a: Set[T], b: Set[T]) -> Set[T]
The elements in both `a` and `b` (intersection).
sets.differencefnfn difference[T](a: Set[T], b: Set[T]) -> Set[T]
The elements of `a` that are not in `b` (difference, `a - b`).
sets.symmetric_differencefnfn symmetric_difference[T](a: Set[T], b: Set[T]) -> Set[T]
The elements in exactly one of `a` or `b` (symmetric difference).
sets.is_subsetfnfn is_subset[T](a: Set[T], b: Set[T]) -> Bool
True if every element of `a` is in `b`.
sets.is_supersetfnfn is_superset[T](a: Set[T], b: Set[T]) -> Bool
True if every element of `b` is in `a`.
sets.is_disjointfnfn is_disjoint[T](a: Set[T], b: Set[T]) -> Bool
True if `a` and `b` share no elements.
import tasks1
tasks.allfnfn all[T](ts: List[Task[T]]) -> List[T]
Drives every task in list order and collects the results.
import texts4
texts.repeatfnfn repeat(s: Text, times: Int) -> Text
s repeated `times` times ("" for zero or negative counts).
texts.pad_leftfnfn 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_rightfnfn 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_blankfnfn is_blank(s: Text) -> Bool
Whether s is empty or whitespace-only.
import time18
Instantrecordepoch_second: Int Instant.civil(self) -> Civil — This instant as broken-down UTC calendar fields. Instant.iso(self) -> Text — This instant in RFC 3339 form, e.g. "2026-08-06T12:00:00Z". Instant.plus(self, d: Duration) -> Instant — This instant moved forward by `d`. Instant.minus(self, d: Duration) -> Instant — This instant moved back by `d`. Instant.until(self, other: Instant) -> Duration — The span from this instant to `other` (negative when `other` is earlier). Instant.is_before(self, other: Instant) -> Bool — Whether this instant is strictly before `other`. Instant.is_after(self, other: Instant) -> Bool — Whether 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.
Durationrecordseconds: Int Duration.in_minutes(self) -> Int — This span in whole minutes, truncated toward zero. Duration.in_hours(self) -> Int — This span in whole hours, truncated toward zero. Duration.in_days(self) -> Int — This span in whole days, truncated toward zero. Duration.abs(self) -> Duration — The same span without a sign.
A signed span of time, in whole seconds.
Civilrecordyear: 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_leapfnfn is_leap(year: Int) -> Bool
Whether a year is a leap year in the proleptic Gregorian calendar.
time.days_in_monthfnfn 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_civilfnfn 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_civilfnfn to_civil(instant: Instant) -> Civil
Breaks an Instant down into UTC calendar fields.
time.addfnfn add(instant: Instant, d: Duration) -> Instant
The instant `d` after the given one.
time.subfnfn sub(instant: Instant, d: Duration) -> Instant
The instant `d` before the given one.
time.betweenfnfn between(a: Instant, b: Instant) -> Duration
The span from `a` to `b` (positive when b is later than a).
time.beforefnfn before(a: Instant, b: Instant) -> Bool
Whether `a` is strictly before `b`.
time.afterfnfn after(a: Instant, b: Instant) -> Bool
Whether `a` is strictly after `b`.
time.secondsfnfn seconds(n: Int) -> Duration
A duration of n seconds.
time.minutesfnfn minutes(n: Int) -> Duration
A duration of n minutes.
time.hoursfnfn hours(n: Int) -> Duration
A duration of n hours.
time.daysfnfn days(n: Int) -> Duration
A duration of n days.
time.weeksfnfn weeks(n: Int) -> Duration
A duration of n weeks.
time.to_isofnfn to_iso(instant: Instant) -> Text
Formats an Instant as ISO 8601 UTC — "YYYY-MM-DDTHH:MM:SSZ".
import toml4
ValueenumValue.Str(s: Text) Value.Int(n: Int) Value.Bool(b: Bool) Value.Arr(items: List[Value])
A TOML scalar or array value.
Tablerecordname: 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) -> Bool — Whether 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.parsefnfn 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.serializefnfn serialize(tables: List[Table]) -> Text
Serializes tables back to TOML text (the inverse of parse).
import url2
url.encodefnfn encode(text: Text) -> Text
Percent-encodes text: unreserved characters pass through, every other UTF-8 byte becomes %XX.
url.decodefnfn 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.v4fnfn 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
Videorecordwidth: 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.renderfnfn render(source: Text) -> Result[Video, Text]
Renders .ptv source text into a Video (formats/ptv-video.md).
video.to_y4m_bytesfnfn 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
BlockenumBlock.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.Model(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).
Documentrecordtitle: Text blocks: List[Block]
A parsed document: title plus blocks in order.
web.renderfnfn render(source: Text) -> Result[Document, Text]
Parses .ptw source text into a Document (formats/ptw-web.md).
web.form_valuefnfn 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_bytesfnfn 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).