Types

Overview

rill is dynamically typed and type-safe. Types are checked at runtime, but type errors are always caught. There are no implicit conversions or coercions.

TypeSyntaxExample
String"text""hello"
Number123, 0.542, 0.9
Booltrue, falsetrue
List[a, b] or list[a, b]list["file.ts", 42]
Dict[k: v] or dict[k: v]dict[output: "text", code: 0]
Orderedordered[k: v]ordered[a: 1, b: "hello"]
Tupletuple[...] (positional)tuple[1, 2]
Mapmap[k: v] (scalar keys)map[404: "missing"]
Datetimedatetime(...) or now()datetime("2024-01-15T10:30:00Z")
Durationduration(...)duration(...dict[days: 1, hours: 2])
Vectorhost-providedvector(voyage-3, 1024d)
Functionfn() { }fn(x) { $x * 2 }
Typetype name or constructornumber, list(number), dict(a: number)

Key principles:

  • Type-safe: No implicit coercion; "5" + 1 errors, not "51" or 6
  • Type-locked variables: A variable that holds a string always holds a string; an annotation sets a declared type that travels with the value
  • Value-based: All values are immutable, all comparisons by value
  • No null/undefined: Empty values are valid ("", [], [:]), but “no value” cannot exist
  • No truthiness: Conditions require actual booleans, not “truthy” values

fn is the type name of every function, in every type position. Writing closure in a type position halts RILL-P012 and names fn. See Functions and Code Blocks for function literals and fn types. A block written as a dict, ordered, list, or tuple entry is held uncalled and reports the type fn(); see Code Blocks.

Strings

Double-quoted text with variable interpolation using {$var}:

"hello world"
"Process {$filename} for review"
"Result: {$response}"

Escape sequences: \n, \t, \\, \", {{ (literal {), }} (literal })

Interpolation

Any valid expression works inside {...}:

"alice" => $name
3 => $a
5 => $b
true => $ok
"Hello, {$name}!"                    # Variable
"sum: {$a + $b}"                     # Arithmetic
"valid: {$a > 0}"                    # Comparison
"status: {$ok ? "yes" ! "no"}"       # Conditional
"upper: {$name -> .upper}"           # Method chain

For how interpolation scopes variables, see Scope Rules; for how it treats invalid values, see Access vs Non-Access; for which values convert to a string, see the conversion matrix in Operators.

Multiline Strings

Multiline strings use triple-quote syntax:

"World" => $name
"""
Hello, {$name}!
Line two
"""

Triple-quote strings support interpolation like regular strings.

See Strings for string methods.

Numbers

Used for arithmetic, exit codes, and loop limits:

42
0
3.14159
-7

Arithmetic operators: +, -, *, /, % (modulo)

Type constraint: All arithmetic operands must be numbers. No implicit conversion:

5 + 3                      # 8
# Error: Arithmetic requires number, got string
"5" + 1

Booleans

Literal true and false. Conditional expressions (?), loop conditions (@), and filter predicates require boolean values. Non-boolean values cause runtime errors.

true ? "yes" ! "no"        # "yes"
false ? "yes" ! "no"       # "no"

No truthiness: rill has no automatic boolean coercion. Empty strings, zero, and empty lists are not “falsy”; you must explicitly check:

"" -> .empty ? "empty" ! "has content"     # Use .empty method
0 -> ($ == 0) ? "zero" ! "nonzero"         # Use comparison

Type-Safe Negation

The negation operator (!) requires a boolean operand. There is no truthiness coercion:

!true                      # false
!false                     # true
"hello" -> .empty -> (!$)  # true (negates boolean from .empty)
!"hello"                   # ERROR: Negation requires boolean, got string
!0                         # ERROR: Negation requires boolean, got number

Use explicit boolean checks when needed:

"" -> .empty -> (!$) ? "has content" ! "empty"         # Negate boolean result
[1,2,3] -> .empty -> (!$) ? "has items" ! "none"   # Check non-empty

Lists

Ordered sequences of values. The bare [...] form and the keyword list[...] form are equivalent; list[...] is canonical (used in output and the LLM reference).

When list elements differ in type, rill infers a union element type. See Element Type Inference.

[1, 2, 3]         # bare form
list[1, 2, 3]     # keyword form (canonical)
[1, 2, 3] => $nums
$nums[0]                   # 1
$nums[-1]                  # 3 (last element)
$nums -> .len              # 3

List Spread

Inline elements from a list or tuple using ... spread syntax:

[1, 2] => $a
[...$a, 3]             # list[1, 2, 3]
[...$a, ...$a]         # list[1, 2, 1, 2] (concatenation)
[...[], 1]         # list[1] (empty spread contributes nothing)

Spread expressions evaluate before inlining:

[1, 2, 3] => $nums
[...($nums -> fan({ $ * 2 }))]  # list[2, 4, 6]

Spreading any other value halts with RILL-R002:

"hello" => $str
[...$str]              # Error: RILL-R002

Access methods:

  • [0], [1]: Index access (0-based)
  • [-1], [-2]: Negative index (from end)
  • .head: First element (errors on empty)
  • .tail: Last element (errors on empty)
  • .at(n): Element at index (negative counts from end)

Out-of-range access halts with RILL-R009; a non-integer index halts with #INVALID_INPUT. Both are catchable.

list[] -> .at(0)  # Error: RILL-R009
list["a"] -> .at(5)  # Error: RILL-R009
list["a"] -> .at(0.5)  # Error: #INVALID_INPUT

Use ?? for safe access with default:

["a"] => $letters
$letters[5] ?? "default"  # "default"
list["a", "b", "c"] -> .at(-1)
# Result: "c"
list["a"] -> .at(5) ?? "default"
# Result: "default"
guard { list["a"] -> .at(5) } => $r
$r.!code -> string
# Result: "RILL_R009"

See Collections for iteration operators.

Dicts

Key-value mappings with string keys written as identifier, number, boolean, variable, or computed keys. The bare [k: v] form and the keyword dict[...] form are equivalent; dict[...] is canonical.

[name: "alice", age: 30]         # bare form
dict[name: "alice", age: 30]     # keyword form (canonical)
[:]                               # empty dict (bare)
dict[]                            # empty dict (canonical)

A bare bracket takes every dict[...] entry, spreads included. A bracket of only spreads is a list, so write a spread-only dict as dict[...$d]. [] is the empty list and [:] the empty dict. Mixing positional and keyed entries halts RILL-P001.

dict[a: 1] => $d
[...$d, b: 2]
# Result: dict[a: 1, b: 2]
dict[a: 1] => $d
dict[...$d]
# Result: dict[a: 1]
list[[] == list[], [:] == dict[]]
# Result: list[true, true]
# Error: RILL-P001
[1, a: 2]
# Identifier keys
[name: "alice", age: 30] => $person
$person.name               # "alice"
$person.age                # 30
# Number and boolean keys are string keys spelled differently
[1: "one", 2: "two", -1: "minus one"] => $numbers
[true: "yes", false: "no"] => $yesno
list[$numbers["1"], $numbers["-1"], $yesno["true"]]
# Result: list["one", "minus one", "yes"]
# Variable and computed keys must evaluate to strings
"status" => $key
"user" => $prefix
list[dict[$key: "active"], dict[($prefix -> "{$}_name"): "alice"]]
# Result: list[dict[status: "active"], dict[user_name: "alice"]]
# Multi-key syntax (same value for multiple keys)
[a: 0, ["b", "c"]: 1]
# Result: dict[a: 0, b: 1, c: 1]
# Quote number-like keys in a multi-key list
dict[["0.50", "2"]: "a"] -> .keys
# Result: list["0.50", "2"]
# Multi-key dispatch
[["GET", "HEAD"]: "safe", list["POST", "PUT"]: "unsafe"] => $methods
"GET" -> $methods
# Result: "safe"

Multi-key errors:

[[]: 1]            # Error: RILL-R002 Multi-key dict entry requires non-empty list
[[list[1, 2], "a"]: 1]  # Error: RILL-R002 Multi-key dict entry keys must be string, got list; quote the key
[[0.50, 2]: "a"]        # Error: RILL-R002 Multi-key dict entry keys must be string, got number; quote the key

Every element of a multi-key list must be a string. [0.50, 2] is a list of numbers, and 0.50 evaluates to 0.5, so its spelling is lost. A dict literal, an ordered literal, and a dispatch table all apply this rule, and a dispatch table checks every key list in every entry before it matches. Write ["0.50", "2"]. A single key such as 1: x or true: x still stores its spelling.

Note: Dot notation for a number spelling (.1) is not valid syntax; see Operators for access forms. Reach a number-spelled key with ["1"], and a boolean-spelled key with ["true"] or .true.

Missing key access throws an error. Use ?? for safe access:

[:] => $d
$d.missing ?? ""
# Result: ""

?? recovers only the last step of a chain, so $d.x.y ?? 0 with .x missing halts RILL-R009.

Dict Keys Are Strings

Every dict key is a string; for keys of another scalar kind, see Maps. A single number or boolean key in a literal names the string of its spelling, so [1: "one"] and ["1": "one"] are the same dict. Writing the same key twice halts at parse time with RILL-P027, including [1: "a", "1": "b"].

[1: "one", true: "yes"] -> .keys
# Result: list["1", "true"]

A dict type names its fields with the same key forms. An identifier, quoted, number, or boolean key works, and a signature quotes a key not spelled as an identifier or reserved word, and true/false. A repeated key halts RILL-P027.

dict("a b": number) == dict["a b": 1].^type
# Result: true
dict(1: string) == dict("1": string)
# Result: true
# Error: RILL-P027
dict(a: number, "a": string)
dict[a: 1, a: 2]    # Error: RILL-P027 Duplicate key 'a' in dict
dict[1: "a", "1": "b"]    # Error: RILL-P027 Duplicate key '1' in dict
dict[a: 1] => $d
guard { $d[1] } => $r
$r.!message
# Result: "Dict key must be string, got number"

A selector that reads a plain dict or a stream must be a string. A number or bool selector halts catchable #TYPE_MISMATCH in every form:

FormExample
Bracket access$d[1]
Variable key.$k
Existence probes.?$k, .?[expr]
Pipe selection1 -> $d
Dispatchdispatch tables, hierarchical dispatch

Every key form selects as [expr] does: .$k, .?$k, and .?[expr] halt with the error the bracket read raises when the receiver rejects the key.

ReceiverWrong keyHalts
dict, streamnumber or bool#TYPE_MISMATCH
mapnot the key type#TYPE_MISMATCH
list, tuple, orderedwrong-typed keyRILL-R002
string, number, atom, fn, iterator, vector, type valueany keyRILL-R002, message Cannot index <type>

?? does not recover these halts, because the selector is wrong rather than absent. Only an absent key or an out-of-range index is a miss.

dict[a: 1] => $d
$d[1] ?? 0
# Error: #TYPE_MISMATCH

.$k reports a missing key as [$k] does (Undefined dict key: k). Spelled field names ($v.name, $v.?name, $t.inner) are not selectors and are unchanged. Elements of a multi-key list must be strings; a non-string element halts RILL-R002.

Convert a number or bool selector with -> string:

[1: "one", 2: "two"] => $d
2 -> string -> $d
# Result: "two"

Dict Methods

MethodDescription
.keysAll keys as list
.valuesAll values as list
.entriesList of tuple(string, V) pairs

.keys, .values, and .entries all return dict’s canonical order (see Ordered, below).

On a non-dict receiver (tuple, stream, string, number, and so on) they halt RILL-R003, and ?? does not recover the halt. ordered and map values are accepted.

[name: "test", count: 42] -> .keys      # ["count", "name"]
[name: "test", count: 42] -> .values    # [42, "test"]
[a: 1, b: 2] -> .entries                # list[tuple["a", 1], tuple["b", 2]]

Reserved methods (keys, values, entries) cannot be used as dict keys.

Uniform Value Type Removed

dict(number) is RILL-P012: a dict type names its fields. Keyed data of one value type is map(string, number); see Maps.

dict[a: 1, b: 2] -> map(string, number) -> .values
# Result: list[1, 2]

Field Annotations

Dict type constructors support ^() inline field annotations. Annotations attach metadata to individual fields and appear on the type structure when you call .^type. See Closure Annotations for the full ^() syntax and TypeScript access patterns.

dict(^("A person's name") name: string, ^("Age in years") age: number)

Ordered

ordered is a first-class container produced by the ordered[...] literal syntax. It preserves key insertion order. When sort is applied to a dict, it returns ordered[[key, value]] — an ordered collection of key-value entry tuples. Variable and computed keys follow the same rules as dict keys: the value must be a string, and any other type halts with RILL-R002. A list[...] key expands to one entry per key, as in dict, and every element must be a string. Keys that repeat collapse to one entry whose last value wins.

ordered[a: 1, b: "hello"] => $o
$o.^type.name
# Result: "ordered"

Use ordered for named argument unpacking:

fn(a, b) { "{$a}-{$b}" } => $fmt
ordered[a: 1, b: "hello"] -> $fmt(...)
# Result: "1-hello"

Element and Entry Access

Access an ordered value by key with ["key"] or .key, exactly like a dict, or by position with an integer index. .keys, .values, .entries, .len, and the .?key existence check read the entries in insertion order.

ordered[a: 1, b: 2] => $o
$o["a"]
# Result: 1
ordered[a: 1, b: 2] => $o
$o.a
# Result: 1
ordered[a: 1, b: 2][0]
# Result: 1
ordered[a: 1, b: 2] -> .keys
# Result: list["a", "b"]
ordered[a: 1, b: 2] -> .values
# Result: list[1, 2]
ordered[a: 1, b: 2] => $o
$o.?a
# Result: true

Key order in ordered is the insertion order. dict has no insertion order to preserve; it iterates in a canonical order instead: keys sorted by UTF-16 code unit.

ordered converts to a plain object via toNative(). The NativeResult.value field holds { key: value, ... }.

Uniform Value Type Removed

ordered(number) is RILL-P012: an ordered type names its fields. Keyed data of one value type is map(string, number); see Maps.

Field Annotations

ordered type constructors support ^() inline field annotations. Annotations attach at each index in the type structure. See Closure Annotations for syntax and TypeScript access patterns.

ordered(^("X coordinate") x: number, ^("Y coordinate") y: number)

Tuples

Tuples are positional containers created with tuple[...] syntax.

Element Access

Index a tuple by position with [i] (negative indexes count from the end for both [i] and .at(i)), or with .at(i). Indexing applies directly to a tuple[...] literal as well as to a captured tuple.

.len returns the number of positions.

tuple[1, "a"].len
# Result: 2
tuple[1, "a"] => $t
$t[1]
# Result: "a"
tuple[1, "a"] -> .at(-1)
# Result: "a"
tuple[1, "a"] -> .at(1)
# Result: "a"
tuple[1, "a"][1]
# Result: "a"

Dot-number access ($t.1) is not supported and is a parse error; use $t[1].

# Error: dot-number is not a valid access form
tuple[1, "a"] => $t
$t.1

Lexicographic Comparison

Tuples support all six comparison operators (<, >, <=, >=, ==, !=). Comparison is element-wise from left to right. The first differing position determines the result.

tuple[1, 2] < tuple[1, 3]
# Result: true
tuple[2, 1] > tuple[1, 9]
# Result: true
tuple[1, 2] <= tuple[1, 2]
# Result: true
tuple[1, 2] >= tuple[1, 2]
# Result: true

Each element compares using the protocol of its own type. An empty tuple[] compares equal to another empty tuple[].

Error cases: Tuples of different lengths or tuples whose corresponding elements have different types halt with #TYPE_MISMATCH.

Dict comparison exclusion: Dicts have no comparison protocol. [a: 1] < [b: 2] halts with RILL-R002. Use tuples for multi-key ordering instead.

For multi-key sort using tuple projections, see Collections.

Using Ordered for Named Unpacking

For named unpacking, use ordered[...]:

fn(a, b, c) { "{$a}-{$b}-{$c}" } => $fmt
dict[c: 3, a: 1, b: 2] -> $fmt(...)   # "1-2-3" (named, via dict; key order irrelevant)

Strict Validation

When invoking with ordered containers, missing required parameters error, and extra keys error:

fn(x, y) { $x + $y } => $fn
ordered[x: 1, y: 2] -> $fn(...)        # 3

Parameter Defaults with Ordered

fn(x, y = 10, z = 20) { $x + $y + $z } => $fn
ordered[x: 5] -> $fn(...)              # 35 (5 + 10 + 20)

A default does not infer the parameter type: y = 10 gives y the type any. Write y: number = 10 to constrain it.

Trailing Defaults with Tuples

Tuple type constructors accept default values on trailing positional fields. When you assert or check against a tuple type, values shorter than the full field count match if every omitted trailing field has a default.

Write the type constructor inline in : or :? position, or bind it to a variable first:

tuple(string, number = 0) => $t
tuple["x"] -> :?$t
# Result: true

The value tuple["x"] has 1 element. The type has 2 fields, but the second field defaults to 0. The check passes because the omitted trailing field has a default.

tuple(string, number = 0) => $t
tuple["x"] -> :$t
# Result: tuple["x"]

The : assertion also accepts the shorter value. No field synthesis occurs; the returned value is unchanged. Use -> type to fill missing fields with their defaults.

Defaults must appear at trailing positions only. A required field after a defaulted field is a type constructor error. A tuple type’s .defaults returns the defaults as a map; see Type System.

ordered follows the same trailing rule. A dict value may omit any defaulted field, not only trailing ones. See Type System for how defaults interact with assertions and conversion.

Nested Default Synthesis

When a collection-typed field has no value and no explicit default, -> type synthesizes it if all its children have defaults. The runtime seeds an empty collection and fills each child from the nested type.

dict[a: 1] -> dict(a: number, b: dict(c: number = 5))
# Result: dict[a: 1, b: dict[c: 5]]

When a field has an explicit collection default, -> type hydrates that default through the nested type. Child defaults fill any fields the explicit default omits.

If any required child field lacks a default, the conversion raises RILL-R044.

Parallel Spread with Tuples

Use tuples with explicit spread ... to pass positional args in fan:

fn(x, y) { $x * $y } => $mul
[tuple[1, 2], tuple[3, 4]] -> fan({ $mul(...) })    # list[2, 12]

One Position per Argument

tuple(T) names exactly one position. Each argument adds one position, so tuple(number, number) names two.

tuple[1, 2, 3] -> tuple(number, number)
# Result: tuple[1, 2]

Conversion keeps the named positions and drops the rest. For a sequence of any length with one element type, use list(T). See Type Form for the tuple(T) rule.

Field Annotations

Tuple type constructors support ^() inline annotations on positional elements. Annotations attach at each index in the type structure. See Closure Annotations for syntax and TypeScript access patterns.

tuple(^("X coordinate") number, ^("Y coordinate") number)

Vectors

Vectors represent dense numeric embeddings from language models or other ML systems. Host applications provide vectors through embedding APIs.

Display format: vector(model, Nd) where model is the source model name and N is the dimension count.

use<ext:app> => $app

$app.embed("hello world") => $vec
$vec -> .model
# Result: "mock-embed"

Properties

PropertyTypeDescription
.dimensionsnumberNumber of dimensions in the vector
.modelstringSource model name
use<ext:app> => $app

$app.embed("hello world") => $vec
$vec -> .dimensions
# Result: 3

$vec -> .model
# Result: "mock-embed"

Methods

MethodReturnsDescription
.similarity(other)numberCosine similarity, range [-1, 1]
.dot(other)numberDot product
.distance(other)numberEuclidean distance, >= 0
.norm()numberL2 magnitude
.normalize()vectorUnit vector (preserves model)
use<ext:app> => $app

$app.embed("hello") => $a
$app.embed("hi") => $b
$a -> .similarity($b)
# Result: 1.0

$a -> .dot($b)
# Result: 0.14

$a -> .distance($b)
# Result: 0.0

$a -> .norm
# Result: 0.37

$a -> .normalize -> .norm
# Result: 1.0

Comparison

Vectors support equality comparison (==, !=). Two vectors are equal when both model and all float elements match:

use<ext:app> => $app

$app.embed("test") => $v1
$app.embed("test") => $v2
$v1 == $v2
# Result: true

Vectors from different models are never equal, even with identical data:

use<ext:app> => $app

# Different models
$app.embed("test", "model-a") => $v1
$app.embed("test", "model-b") => $v2
$v1 == $v2
# Result: false

Behavioral Notes

  • Immutable: Vector data cannot be modified after creation
  • No .empty method: Vectors are always non-empty by construction; there is no empty vector to test for
  • No string coercion: Cannot be used in string interpolation or concatenation
  • No collection operations: Cannot use seq, fan, filter, fold, acc on vectors

Datetime

A datetime represents an instant in time stored as UTC milliseconds since the Unix epoch. It is an opaque scalar type; values are immutable and compared by their Unix timestamp.

Construction

Three forms construct a datetime value:

FormExampleNotes
ISO 8601 stringdatetime("2024-01-15T10:30:00Z")Accepts date-only and datetime with offset
Named componentsdatetime(...dict[year: 2024, month: 1, day: 15])UTC; hour, minute, second, ms default to 0
Unix millisecondsdatetime(...dict[unix: 1705312200000])UTC ms since epoch
datetime("2024-01-15T10:30:00Z") -> .iso()
# Result: "2024-01-15T10:30:00Z"

datetime(...dict[year: 2024, month: 1, day: 15]) -> .iso()
# Result: "2024-01-15T00:00:00Z"

datetime(...dict[unix: 0]) -> .iso()
# Result: "1970-01-01T00:00:00Z"

now()

now() returns the current UTC instant as a datetime.

now() -> .iso()

The test harness does not fix the clock, so # Result: is omitted. Pass nowMs in RuntimeContext to pin the instant in deterministic scripts.

Properties

UTC component properties decompose the stored timestamp:

PropertyTypeDescription
.yearnumberUTC year (e.g. 2024)
.monthnumberUTC month, 1–12
.daynumberUTC day, 1–31
.hournumberUTC hour, 0–23
.minutenumberUTC minute, 0–59
.secondnumberUTC second, 0–59
.msnumberUTC millisecond, 0–999
.unixnumberRaw UTC ms since epoch
.weekdaynumberISO weekday: 1 (Monday) – 7 (Sunday)
now() => $t
$t -> .year
$t -> .month
$t -> .weekday

String Output Methods

MethodReturnsDescription
.iso(offset?)stringFull ISO 8601 with timezone indicator (default UTC)
.date(offset?)stringYYYY-MM-DD portion
.time(offset?)stringHH:MM:SS portion

offset is hours east of UTC. Pass 2 for +02:00, -5 for -05:00, 5.5 for +05:30.

now() => $t
$t -> .iso(0)
$t -> .iso(2)
$t -> .date(0)
$t -> .time(0)

Local Properties

These properties apply the timezone offset from RuntimeContext automatically:

PropertyTypeDescription
.local_isostringISO 8601 at host timezone
.local_datestringYYYY-MM-DD at host timezone
.local_timestringHH:MM:SS at host timezone
.local_offsetnumberHost timezone offset in hours
now() => $t
$t -> .local_iso
$t -> .local_offset

Arithmetic

MethodArgumentReturnsDescription
.add(dur)durationdatetimeAdds duration to datetime; months applied first, then ms
.diff(other)datetimedurationAbsolute difference as a fixed-ms duration
now() => $t1
$t1 -> .diff($t1) => $gap
$gap -> .display
# Result: "0ms"
# Add one month (calendar duration)
now() -> .add(duration(...dict[months: 1])) -> .iso()
datetime("2024-03-01T00:00:00Z") -> .diff(datetime("2024-01-01T00:00:00Z")) -> .display
# Result: "60d"

Comparison

Datetimes support equality (==, !=) and ordering (<, >, <=, >=). Comparison uses the Unix timestamp directly.

now() == now()
# Result: true

now() <= now()
# Result: true

JSON

json() serializes a datetime as an ISO 8601 string with milliseconds. deserializeValue accepts an ISO 8601 string to reconstruct the datetime.

json(datetime("2024-01-15T10:30:00Z"))
# Result: "\"2024-01-15T10:30:00.000Z\""

String Interpolation

Interpolating a datetime produces its UTC ISO 8601 string (same as .iso()).

now() => $t
"Event at {$t}"

Zero Value

.zero returns datetime(unix: 0), the Unix epoch.

now() -> .zero -> .iso()
# Result: "1970-01-01T00:00:00Z"

now() -> .zero -> .unix
# Result: 0

Behavioral Notes

  • Immutable: Datetime values cannot be modified after creation
  • Scalar: A single UTC timestamp; no timezone or locale stored on the value
  • String coercion permitted: Datetimes can appear in string interpolation; they format as ISO UTC
  • No collection operations: Cannot use seq, fan, filter, fold, acc on datetimes

Extension Boundary

The core datetime type stores UTC timestamps and formats with numeric offsets only. IANA timezone names (e.g. "America/New_York") require the datetime-extension package, which is not part of core rill. rill uses POSIX time (Unix milliseconds); POSIX time does not model leap seconds.


Duration

A duration represents a span of time. It stores two fields independently: months for calendar units and ms for fixed units. These fields never mix in arithmetic.

Construction

Three forms construct duration values: named components, the printed form, and a piped string. The first three rows below are named components.

FormExampleNotes
Fixed unitsduration(...dict[days: 1, hours: 2])Collapses to ms; exact arithmetic
Calendar unitsduration(...dict[months: 3, years: 1])Collapses years to months; variable-length
Raw millisecondsduration(...dict[ms: 86400000])Direct ms count
Printed formduration("1d2h")Units in the order y, mo, d, h, m, s, ms, each at most once; only the ms count may be a decimal ("1s500.5ms"); each component is at most 2^53-1; malformed text halts with #INVALID_INPUT; a positional number halts with RILL-R001
String pipe"1d2h" -> durationParses as duration("1d2h") and halts the same way; duration -> string returns the printed form; a number or dict piped into duration halts with RILL-R036
duration(...dict[days: 1, hours: 2]) -> .display
# Result: "1d2h"

duration(...dict[months: 3]) -> .months
# Result: 3

duration(...dict[years: 1]) -> .months
# Result: 12

duration(...dict[ms: 5000]) -> .display
# Result: "5s"

Properties

Fixed-unit durations decompose their ms field using remainder arithmetic:

PropertyTypeDescription
.daysnumberfloor(ms / 86400000)
.hoursnumberRemainder hours after days
.minutesnumberRemainder minutes after hours
.secondsnumberRemainder seconds after minutes
.msnumberRemainder milliseconds after seconds
.monthsnumberCalendar months count
.total_msnumberRaw ms field; halts on calendar durations

Durations also carry .eq and .ne, which compare as == does: months and milliseconds must both match.

duration(...dict[hours: 25]) -> .days
# Result: 1

duration(...dict[hours: 25]) -> .hours
# Result: 1

duration(...dict[hours: 25]) -> .total_ms
# Result: 90000000

Requesting .total_ms on a calendar duration halts with a catchable #INVALID_INPUT:

# Error: total_ms is not defined for calendar durations
duration(...dict[months: 1]) -> .total_ms

Display

.display formats a duration as a compact string, omitting zero components. Zero duration displays as "0ms".

duration(...dict[days: 1, hours: 2, minutes: 30]) -> .display
# Result: "1d2h30m"

duration(...dict[years: 1, months: 3]) -> .display
# Result: "1y3mo"
now() => $t
$t -> .diff($t) -> .zero -> .display
# Result: "0ms"

Arithmetic

MethodArgumentReturnsDescription
.add(dur)durationdurationSums months and ms fields independently
.subtract(other)durationdurationSubtracts fields; halts with #INVALID_INPUT if the result would be negative
.multiply(n)numberdurationMultiplies both fields by n; halts with #INVALID_INPUT if n is negative, the result is not finite, or a month result is fractional

All three halt with #TYPE_MISMATCH when the argument has the wrong type. These halts are catchable.

duration(...dict[hours: 1]) -> .add(duration(...dict[hours: 1])) -> .display
# Result: "2h"

duration(...dict[hours: 2]) -> .subtract(duration(...dict[hours: 1])) -> .display
# Result: "1h"

duration(...dict[hours: 1]) -> .multiply(3) -> .display
# Result: "3h"

Comparison

Equality compares both months and ms fields. Two durations are equal only when both fields match.

duration(...dict[hours: 48]) == duration(...dict[days: 2])
# Result: true

duration(...dict[months: 1]) == duration(...dict[months: 1])
# Result: true

A duration’s interpolated text parses back to an equal duration:

duration("1d2h") => $d
duration("{$d}") == $d
# Result: true

Two durations order when one is greater than or equal to the other in both months and ms. When the two fields disagree in direction, ordering halts with RILL-R002, which guard recovers:

duration("1y") < duration("2y")
# Result: true
# Error: Cannot order durations with different calendar components
duration(...dict[months: 1]) < duration(...dict[hours: 24])

To compare an incomparable pair, add each duration to the same anchor datetime and compare the results:

now() => $anchor
duration(...dict[months: 1]) => $a
duration(...dict[hours: 24]) => $b
($anchor -> .add($a)) < ($anchor -> .add($b))
# Result: false

JSON

Fixed durations serialize as a number (raw ms). Calendar durations serialize as {"months": N, "ms": M}.

json(duration(...dict[hours: 1]))
# Result: "3600000"

json(duration(...dict[months: 1]))
# Result: "{\"months\":1,\"ms\":0}"

String Interpolation

Interpolating a duration produces its .display string.

"Gap: {duration(...dict[days: 3])}"
# Result: "Gap: 3d"
now() => $t
$t -> .diff($t) => $gap
"Gap: {$gap}"
# Result: "Gap: 0ms"

Zero Value

.zero returns duration("0ms").

now() => $t
$t -> .diff($t) -> .zero -> .display
# Result: "0ms"

Behavioral Notes

  • Immutable: Duration values cannot be modified after creation
  • Scalar: Stored as two independent fields; no normalization between fields
  • No negatives: Duration values are always non-negative; subtraction halts on negative results
  • String coercion permitted: Durations can appear in string interpolation; they format via .display

Extension Boundary

Core duration arithmetic is fixed-field only. Fractional months, business-day arithmetic, and calendar-aware duration normalization require the datetime-extension package.

Streams

A stream is a collection type that produces values over time. Unlike lists, streams emit chunks one at a time and carry a separate resolution value returned when the stream closes.

The type signature stream(T):R names both parts: T is the chunk type, and R is the resolution type.

stream(string):number   # chunks are strings, resolution is a number
stream(number)          # chunks are numbers, resolution is unconstrained
stream()                # unconstrained chunk and resolution types

Chunk Type

The chunk type T in stream(T):R constrains each emitted value. Inside a stream function, yield emits the current pipe value as a chunk.

fn(x):stream(string) {
  $x -> .upper -> yield
  $x -> .lower -> yield
}

yield appears as the terminator in a pipe chain. Use $x -> yield to emit a specific value, or bare yield to emit the current pipe value ($).

The yield keyword is only valid inside a function annotated with :stream(T):R. Using yield without that annotation is a parse error.

Resolution Type

The resolution type R in stream(T):R constrains the value the stream returns when it closes. Call the stream variable as a function ($s()) to get the resolution value.

make_stream() => $s
$s()   # returns the resolution value

The resolution is produced by the stream’s final expression or an explicit return statement in the stream function body. Host-provided streams supply the resolution from the underlying async producer.

A zero-chunk stream resolves immediately. Calling $s() returns the resolution value without consuming any chunks.

Single-Use Constraint

A stream can be iterated only once. Passing a stream to a collection operator (seq, fan, filter, fold, acc) consumes all its chunks. After that, the stream is done and produces no further chunks.

make_stream() => $s
$s -> seq({ $ })   # consumes the stream
$s -> fan({ $ })   # Error: stream already consumed

Calling $s() after consuming the stream still returns the resolution value. The resolution is cached after the stream closes. $s() also works on any .next() step, including stale steps that can no longer advance. Only .next() fails on stale steps.

Stream as Collection

All five collection operators work on streams. They consume chunks as the stream emits them and collect results when the stream closes.

make_stream() => $s
$s -> fan({ $ * 2 })           # transforms each chunk, returns list
$s -> filter({ $ > 0 })        # keeps matching chunks, returns list
$s -> fold(0, { $@ + $ })      # reduces all chunks to a single value

See Collections for full operator documentation including stream behavior.

For stream function syntax and the :stream(T):R annotation on functions, see Functions and Code Blocks.

Atom (:atom)

:atom is the 16th primitive type. It carries a name via #NAME literals and is compared by name. See Error Handling: Error Atoms for full syntax, conversions, the core error set, and extension error reporting.


See Also

DocumentDescription
MapsMap keys, selection, conversion, and sorting
Type SystemStructural types, type assertions, unions, type-locked variables
VariablesDeclaration, scope, $ binding
Functions and Code BlocksFunction semantics and patterns
CollectionsList iteration operators
StringsString methods reference
ReferenceQuick reference tables