DUST
Work in progress. This specification is incomplete and subject to change.
DUST (Data Universal S-expression Toolkit) is a small, high-performance, game‑engine‑inspired Lisp dialect designed for embedded information processing, data manipulation, and business logic.
DUST source files use the .dust extension. DUST extends RON with syntax for expressions and evaluation rules, while retaining a JSON representation of every source form.
This reference covers syntax, evaluation, schemas and contracts, special forms, and all standard functions. The Function Index lists every callable alphabetically. The Command line and REPL page covers the engine's command line, formatter, REPL, and evaluation costs.
(let [total (fn total [items discount] (reduce :+ 0.0 (map (fn [{quantity quantity unitPrice unitPrice}] (* (float (* quantity unitPrice)) (- 1.0 discount))) items)))] [(total [{quantity 3 unitPrice 20} {quantity 2 unitPrice 15}] 0.1) (total [{quantity 2 unitPrice 15}] 0.0) (total [] 0.5)])
(let [total (fn total [items discount] (reduce :+ 0.0 (map (fn [{quantity quantity unitPrice unitPrice}] (* (float (* quantity unitPrice)) (- 1.0 discount))) items)))] [(total [{quantity 3 unitPrice 20} {quantity 2 unitPrice 15}] 0.1) (total [{quantity 2 unitPrice 15}] 0.0) (total [] 0.5)])
81.0 30.0 0.0
01 Language
1.1. Syntax
The .dust format extends .ron. References, invocations, quotation shorthand, and mute shorthand belong exclusively to DUST. Their explicit tagged-element representations are ordinary data in RON and JSON.
Parsing DUST constructs forms without evaluating them. Reading source never executes user code or reader macros.
Parentheses delimit invocations, not literal lists or quotation forms.
[square brackets] are also used to delimit lists, used for literal
data structures and in specials and macros to delimit where new bindings
are introduced, such as argument lists and let bindings.
{curly braces} delimit maps containing key-value pairs and optional
tags.
Ordinary members pair a string key with a value.
Tags supply boolean-valued members using RON's shorthand.
Map keys must be strings.
Map values can be of any type.
1.1.1. Strings
DUST strings use double quotes or fences of two or more double quotes, with the same escapes as RON quoted strings. String literals produce strings, not quotation forms. Literal map keys are always strings and may be written bare.
In value position, a token matching a number, null, true, or false
denotes that value. Other unprefixed names denote local references.
Quote a name to write a string value.
A leading # introduces a tagged element, : a constant reference, and
/ a JSON Pointer. Leading `, ~, ,, and ,@ introduce quotation
forms. A leading \ mutes the next complete form.
["hello" ".-#1" "don't" true false null 42 -1.5 "true" "false" "null" "42" "-1.5" "nil" "#name" "^name" name "🙂" "" {true false}]
"hello" ".-#1" "don't" true false null 42 -1.5 "true" "false" "null" "42" "-1.5" "nil" "#name" "^name" name "🙂" "" <!true>
[hello .-#1 don't true false null 42 -1.5 "true" "false" "null" "42" "-1.5" nil "#name" ^name #local name 🙂 "" <!true>]
Whitespace separates list forms on every line. Putting [ alone on its
opening line has no effect on token boundaries. A string containing spaces
still requires quotes:
[ "Ada Lovelace" "Grace Hopper" ]
"Ada Lovelace" "Grace Hopper"
[ Ada Lovelace Grace Hopper]
Ordinary double-quoted strings use JSON escapes. Fenced strings allow double quotes inside without escaping them, but backslashes and control characters still use escapes. Unicode escapes decode to their characters:
["say \"hello\"" ""C:\\tmp\\notes.txt"" "\u03b5" "\u0000"]
""say "hello""" "C:\\tmp\\notes.txt" "ε" "\u0000"
[ say "hello" C:\tmp\notes.txt ε "\u0000"]
A fence of three or more quotes followed only by whitespace and a newline starts a multiline string. The newline after the opening fence and the newline before the closing fence are not part of the string. An extra blank line before the closing fence preserves a trailing newline. A single-line fence and a multiline fence can therefore contain the same string:
[ ""hello world"" """ hello world """ """ first line second line """ ]
"hello world" "hello world" """ first line second line """
[ hello world hello world """ first line second line """ ]
A quoted ., :, or / is a string. An unquoted : starts a
constant reference and / starts a pointer outside direct-callee position.
The old .name spelling is invalid. A caret has no special meaning.
["^name" "^x" name :name "^" name]
"^name" "^x" name :name "^" name
[^name ^x #local name #const name ^ #local name]
Binding forms interpret bare names as declarations. A direct callee is a
name encoded as a string in the first element of #invoke, without a
#local or #const wrapper. Surrounding quote characters in direct-callee
position belong to that name. A computed callee is an expression in the
first element, such as (:strings/case "upper" "hi").
Whitespace separates root forms, list elements, and invocation operands. Map keys follow RON's token rules and are always strings.
1.2. Source notation
1.2.1. Documents and form separation
A DUST file holds one or more forms. A file containing exactly one form is that form. Two or more forms, separated by whitespace including newlines, make an implied root list; its outer square brackets may be written or omitted. A root string value must be quoted. Unlike RON, whose default document is an implied outer object, DUST has no implied root map: a root map is written with braces.
Canonical DUST omits the root list's brackets when the list has two or more forms and its first non-comment form is not a literal list:
(+ 1 2)
(* 3 4)
Root forms are separated by whitespace, not lines, so a root string containing
spaces is quoted, as in "two words".
Explicit outer brackets around these forms are also accepted and produce the same list, but are not canonical.
Otherwise the brackets are kept, so a one-element list [x] stays distinct
from the form x, and [[1 2]] stays distinct from [1 2].
Once an earlier form establishes an implied root list, later literal lists
need only their own brackets.
A file is evaluated one top-level form at a time, from first to last, so a
form can use the top-level locals that earlier forms define. Its value is
the list of the forms' values: (+ 1 2) (* 3 4) evaluates to [3 12], and a
file with one form evaluates to that form's value. An empty file is an empty
list. Read for evaluation, as by the Stardust REPL, a written list is always
one form, so [1 2] followed by [3] is two forms, and each form can have a
depth of 256.
An #err value from one top-level form does not stop the later forms.
This is the language and evaluation API rule. The
CLI commands eval and run stop at the first form that returns #err.
In expression positions, unquoted (), [], and {} delimit forms and end reference names and direct-callee names.
These delimiters separate list forms and invocation operands without whitespace.
[["foo"(bar)] (foo(bar)) ["foo"["bar"]{}(bar)"baz"] [[foo(bar)][(bar):foo]]]
[["foo" (bar)] (foo (bar)) ["foo" ["bar"] {} (bar) "baz"] [[foo (bar)] [(bar) :foo]]]
[[foo #invoke [bar]] #invoke [foo #invoke [bar]] [foo [bar] {} #invoke [bar] baz] [[#local foo #invoke [bar]] [#invoke [bar] #const foo]]]
A map member value contains one form. foo(bar) contains two forms: the
reference foo and the invocation (bar). It may supply consecutive root
or list forms, but is invalid as one map member value. "foo(bar)" is one string.
Map keys use RON's token rules, including embedded brackets and parentheses, and require whitespace before their values.
Angle brackets delimit tag groups in map-member position.
A tag group can also stand alone as a tag-only map in value position.
For example, <staff mentor> is the canonical form of {staff true mentor true}.
In DUST, an empty tag group <> denotes the empty map and prints as {}.
See tag-only maps.
[{items[0] 1 foo(bar) 2 .name 3}]
[{.name 3 foo(bar) 2 items[0] 1}]
[{.name 3 foo(bar) 2 items[0] 1}]
Map keys are always strings. A key that starts with # is the same string with or without quotes,
at every member count and in every position, so {#zip null} and {"#zip" null} are the same map.
A tag is written without braces: #zip null.
[{#zip null} #zip null]
{#zip null} #zip null
[{#zip null} #zip null]
{#zip null} #zip null
A key that begins with ) is quoted, since a line that begins with ) closes a form:
{"(a" "b" ")" 1 ")x" 2 "x)" 3 "(" 4 k ["a <b" "c" "a<b"]}
{( 4 (a "b" ")" 1 ")x" 2 k [ "a <b" "c" "a<b"] x) 3}
( 4 (a b ) 1 )x 2 k [ "a <b" c a<b] x) 3
1.2.2. Comments
A DUST comment starts with ; and continues to the end of the line.
The ; starts a comment at the start of a line, after a space or tab, or
directly after an opening [, {, ( or < that starts a token.
In all other positions, ; is text, so a[;b is one token. A semicolon in a
quoted string is always text. RON and EDN use the same comment rules.
A $comment key is ordinary data in DUST and RON. JSON and TRON have no
comment syntax, so they keep all comments of a document in one root
$comment member: a JSON string of an object from the pointer of each
commented value to its text. The "" pointer is the root. This DUST:
; Spice math.
{rates {arrakis 10 caladan 15}
; reserve percent
reserve 10}
is this JSON:
{
"$comment": "{\"\":\"Spice math.\",\"/reserve\":\"reserve percent\"}",
"rates": {
"arrakis": 10,
"caladan": 15
},
"reserve": 10
}
A root that is not a map goes in {"$comment": "…", "$value": root}. See
stardust convert for the pointer steps.
Each value has a maximum of one comment text. These rules give each comment to a value:
- A comment after a value on the same line belongs to that value.
- A comment on its own line belongs to the next value.
- A comment directly after an opening bracket belongs to the next value.
- When closing brackets come before the comment on a line, the comment belongs to the outermost value that these brackets close.
In each of these examples, the comment c belongs to the value 1:
{x 1 ; c
y 2}
{y 2
; c
x 1}
[; c
1 2]
In this example, the comment belongs to the list [1 2] at /a, not to the
item 2:
{a [1 2] ; c
b 1}
When a value has more than one comment, the reader joins the texts in source
order, with a line feed between them. In this example, /a has the text
first, /b has second and third on two lines, and /c has fourth:
{a 1 ; first
; second
b 2 ; third
; fourth
c 3}
In a file with one form, a comment above the form belongs to that form. For
example, this file evaluates to 3, and its root form has the comment
Root documentation:
; Root documentation
(+ 1 2)
The reader refuses a comment that no value can own, with an
Invalid_Comment error at the offset of the first ; that has no value.
The reader also refuses a comment in some positions inside a value. In this
table, \n is a line feed:
| Refused comment | Example |
|---|---|
| Before a closing bracket | [1\n ; c\n] |
| In an empty container | {\n ; c\n} |
| After the last value of a file | 1\n; c |
| In a file that contains only comments | ; c |
| In a tag group | {<a ; c\n b>} |
A comment between a tag or quotation prefix and its payload is refused. Write the comment above the tagged value. A comment in the payload of a string template is refused.
A comment in the payload of a tag or quotation is permitted. In this example,
the comment the input belongs to the 1 in the quoted form:
{rule `(+ x
; the input
1)}
Canonical formatting writes each comment as ; lines directly above its
value. A text with line feeds gives one ; line for each line of the text.
A blank line goes above each comment block. There is no blank line at the
start of the file or directly after an opening bracket.
For example, canonical formatting changes this input:
{a 1 ; one
b 2}
to this form:
{
; one
a 1
b 2}
The example with four comments above formats as:
{
; first
a 1
; second
; third
b 2
; fourth
c 3}
1.2.3. Nesting depth
The parser and the evaluator have no nesting limit. A form or a value can nest as deep as the memory budget of the evaluation allows. For example, a list that is 256 levels deep evaluates to the same list:
[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[1]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]
[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ 1]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]
[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ 1]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]
A value that a program builds as it runs, such as a list that reduce wraps once for each item, can nest more than 100,000 levels deep in the default memory budget.
The code of a program has one bound that does not come from the budget.
The evaluator compiles a program to Lua, and LuaJIT runs it on a stack of 65,500 slots.
Deep code uses some of this stack for each level.
A program whose source nests control forms, such as if, about 30,000 levels deep, or a literal about 60,000 levels deep, can fill the stack.
The evaluation then gives #err <internal limit recursion>, the same error as a recursion that does not stop:
#err {<internal limit recursion>
message "program exceeds an internal limit: calls nest too deeply"}
Calls such as (+ 1 (+ 1 ...)) and (str (str ...)) nest past 100,000 levels.
Parser errors produce #err <invalid value>.
Formatting rejects a document when indentation would start after column 65,535.
1.2.4. Value size
A string, a byte string or a Bitset holds at most 4,294,967,295 bytes, and a
list, map or other container at most 4,294,967,295 items. This is a format
bound: a value cell stores its length in 32 bits. A longer text or a container
with more items is refused, never shortened; a decoder reports it as an
invalid value, and reading a longer stored list gives a limit error. Keep
larger payloads in the objects plugin, which stores a payload of any size
and reads it by byte range.
A value that crosses into or out of the runtime (an evaluation's bindings and
result, a host call's request and result, one page of query results) holds at
most 2,147,483,647 cells, 2,147,483,647 bytes of text and 2,147,483,647 facts
(repeated containers, functions and error positions). This is a runtime
bound: the runtime counts these in 32 bits, because 64-bit counts make every
value it writes slower. A value past it fails with #err <limit resource>
and a message that names the bound. One runtime string also holds less than
2 GiB.
1.2.5. References
Outside map-key and direct-callee positions, a bare name produces a #local
tagged element. : followed by a nonempty name produces a #const tagged
element. Names follow DUST's token and form-separation rules.
Numbers, booleans, and null keep their literal meanings; explicit tagged
notation can represent references to those spellings, such as #local "5".
The spellings .name, ., :, ..., ::x, and ."x" are syntax errors.
A . or : after the first character belongs to the name, as in a.b or a:b.
{var name const :name punctuation (fn? :+) qualified-var user/name qualified-const :math/pi colon a:b dot :a.b literal-names [#local "42" #local "-1" #local "1.5" #local "true" #local "false" #local "null"] caret-name ^+ nested [x {value :y}]}
{caret-name ^+ colon a:b const :name dot :a.b literal-names [#local "42" #local "-1" #local "1.5" #local "true" #local "false" #local "null"] nested [x {value :y}] punctuation (fn? :+) qualified-const :math/pi qualified-var user/name var name}
caret-name #local ^+ colon #local a:b const #const name dot #const a.b literal-names [#local "42" #local "-1" #local "1.5" #local "true" #local "false" #local "null"] nested [#local x {value #const y}] punctuation #invoke [fn? #const +] qualified-const #const math/pi qualified-var #local user/name var #local name
#err <name unbound>
(let [add :+] [(add 0 0) (add 1 2) (add -4 10)])
(let [add :+] [(add 0 0) (add 1 2) (add -4 10)])
#invoke [let [#local add #const +] [#invoke [add 0 0] #invoke [add 1 2] #invoke [add -4 10]]]
0 3 6
Parsing constructs the reference without looking up its name. Binding and parameter declarations use the same name forms as local references. A name in a binding or parameter position declares a local.
1.2.6. String Template Literals
A string template is a quoted or fenced string prefixed with ~, the
quasiquote prefix. Inside it, , followed by a form embeds that form, as
unquote does in a quasiquoted list. A string without ~ is always literal, so
",name" and "{{x}}" are plain text.
(let [name "Ada"] ~"Hello ,name") ; => "Hello Ada"
(let [subtotal 10 tax 2] ~"Total: ,(+ subtotal tax)") ; => "Total: 12"
~"Pi is ,:math/pi" ; => "Pi is 3.141592653589793"
(let [name "Ada"]
~"""
Hello ,name
Sum ,(+ 1 2)
""") ; => "Hello Ada\nSum 3"
An embedded form in parentheses, brackets, braces, or quotes ends at its closing delimiter. Any other form, such as a reference, reads a full name and ends at whitespace, a comma, a quote, or a bracket. A comma that ends it is consumed, so a reference can be followed directly by text:
(let [name "Ada"] ~"Hi ,name there") ; => "Hi Ada there"
(let [name "Ada"] ~"Hi ,name,!") ; => "Hi Ada!"
(let [foo! "bang"] ~"Hi ,foo!") ; => "Hi bang"
(let [name "Ada"] ~"Hi ,name,, there") ; => "Hi Ada, there"
A comma followed by whitespace or the closing quote is text, and ,, writes a
literal comma anywhere:
~"a, b" ; => "a, b"
~"x,,y" ; => "x,y"
Embedded forms may contain quotes, as in ~"a ,(str "x") b". A quoted string
cannot be embedded directly in a one-line template, because ," before the
closing quote is literal text and a quote otherwise ends the template; write
,(str "x") or use a fenced ~""" template. Only a string written directly
after ~ is a template; a string nested inside a quasiquoted list stays
literal, so ~[a ,x "b ,x"] keeps "b ,x".
The resulting template value keeps the literal pieces and evaluated values
separate, so template functions can inspect them or
escape each value. A printed or exported template value is its rendered string,
the same text str produces. Printing loses the parts: reading the printed
result back gives an ordinary string, not a template. A quoted template is a
form rather than an evaluated value, so it prints as a template literal.
In RON, the #template tagged representation contains a list of literal
strings and a list of forms. The first list has one more item than the second.
For example, this DUST template:
~"hello-,name"
has this RON representation:
#template [[hello- ""] [#local name]]
A comment can belong to a template as a whole. Write it above the template,
or after the template on the same line, as in ~"hello-,name" ; greeting.
A comment after the closing brackets of a #template form also belongs to
the template. A comment inside the payload, among the literal pieces or the
embedded forms, is an Invalid_Comment error at the comment. This rule
applies in DUST, RON and JSON. In JSON
that is a root $comment pointer into the payload, such as /t/0 for the
literal pieces of the template at /t.
#template [
["hello-" ""] ; refused: inside the payload
[name]]
DUST formatting writes the template literal when the tagged representation
can be expressed without changing its data. It always writes a one-line
~"…" literal, escaping line breaks as \n, so a multiline ~""" template
is reformatted on one line. A template that embeds a literal string value keeps the explicit
#template notation.
See string templates for construction, inspection, and rendering.
1.2.7. JSON Pointers
RFC 6901 defines JSON Pointer as a string syntax for identifying a value
within a JSON document. Its reference tokens are separated by /; within a
token, ~1 represents / and ~0 represents ~. The empty string refers
to the root, while / refers to a member with an empty name.
DUST uses that syntax for pointer text and adds pointer values and embedded forms. A pointer value can be used with DUST maps and lists. DUST distinguishes integer index segments from string key segments; numeric strings with valid index spelling become indices. Extensions to RFC 6901 lists everything DUST adds.
(get {a/b 1} /a~1b) ; 1
(get {items ["zero" "one"]} /items/1) ; one
(get {"" 7} /) ; 7
A slash-prefixed value constructs a pointer. Pass it to a collection path
function to read or update data. In callee position, / is division; a map
literal key beginning with / is a string.
(get {a 1} /a) ; 1
(/ 10 2) ; 5.0
(get {/a 1} "/a") ; 1
A pointer has slash-separated segments:
(get {"" 7} /) ; 7
(get {"" {a 1}} //a) ; 1
(get {a {"" 2}} /a/) ; 2
(get {a 1} (jsonptr "")) ; {a 1}
/ selects an empty key; it does not select the root. Use (jsonptr "")
for the root pointer.
Segments can contain embedded forms. As in a string template,
, followed by a form embeds it, and a comma that ends a token form is
consumed. A pointer needs no ~: a bare pointer cannot otherwise contain a comma.
(let [key "a"] (get {a 1} /,key)) ; 1
(let [id 2] (get {user-3 "ok"} /user-,(+ 1 id))) ; ok
(let [id 7] /users/,id,/name) ; /users/7/name
Names can contain /, so /users/,id/name reads the reference id/name;
the closing comma in /users/,id,/name ends id before the next segment.
An embedded segment value must be a string or an integer.
The RFC escapes ~1 and ~0 select keys containing / and ~:
(get {a/b 1} /a~1b) ; 1
(get {m~n 2} /m~0n) ; 2
DUST also accepts \{, \}, and \\ for literal braces and backslashes,
and ,, for a literal comma. Other tilde or backslash escapes are syntax
errors. Parentheses, caret, opening braces, and double quote are literal
pointer text; an unmatched closing parenthesis ends the pointer token.
Whitespace, square brackets, a closing brace, or a comma followed by whitespace
or a closer also ends the token.
1.2.7.1. Extensions to RFC 6901
A DUST pointer is RFC 6901 with the extensions in this table. Text that uses only RFC 6901 syntax selects what RFC 6901 selects, except that a token spelled as a negative index is an index on a list, where RFC 6901 has only keys.
| Extension | Example | RFC 6901 |
|---|---|---|
A negative index counts from the end of a list: -1 is the last item, -2 the one before it |
/items/-1 |
-1 is only a key, and has no meaning on an array |
| A segment can be a computed form | /users/,id,/name |
Tokens are text |
| A segment can join text and forms | /user-,(+ 1 id) |
Tokens are text |
Backslash escapes and ,, in source |
/a\{b |
Only ~0 and ~1 |
A negative index follows the same rules as a nonnegative one:
- A read before the first item is missing, as a read past the last item is, so
(get ["a"] -2)isnulland(contains? ["a"] -2)isfalse. - A write before the first item is
#err <invalid value>. There is no position to create, whereas a write at the list's length appends. - A removal before the first item changes nothing.
- On a map,
-1is the key"-1", as1is the key"1". - The token
-0is a key, not an index. - RFC 6901's
-token, which names the position after the last item, is a key.
(get ["a" "b" "c"] -1) (get ["a" "b" "c"] -2) (get ["a" "b" "c"] -3) (get ["a" "b" "c"] -4) (get ["a" "b" "c"] -4 "none") (get {items ["a" "b" "c"]} /items/-1) (let [i -2] (get {items ["a" "b" "c"]} /items/,i)) (get {items ["a" "b"]} (jsonptr "/items/-2")) (get {items ["a" "b"]} (lists/concat (jsonptr "/items") [-1])) (get {"-1" "key"} /-1) (get {items ["a"]} /items/-0) (get #b64 "F8gHWw==" -1) (contains? ["a"] -1) (contains? ["a"] -2) (put ["a" "b"] -1 "z") (put ["a" "b"] /-2 "z") (put ["a" "b"] -3 "z") (remove ["a" "b"] -1) (remove ["a" "b"] -3) (collections/update [1 2] -1 (fn [old] (+ old 10))) (str /a/-1)
(get ["a" "b" "c"] -1) (get ["a" "b" "c"] -2) (get ["a" "b" "c"] -3) (get ["a" "b" "c"] -4) (get ["a" "b" "c"] -4 "none") (get {items ["a" "b" "c"]} /items/-1) (let [i -2] (get {items ["a" "b" "c"]} /items/,i)) (get {items ["a" "b"]} (jsonptr "/items/-2")) (get {items ["a" "b"]} (lists/concat (jsonptr "/items") [-1])) (get {-1 "key"} /-1) (get {items ["a"]} /items/-0) (get #b64 "F8gHWw==" -1) (contains? ["a"] -1) (contains? ["a"] -2) (put ["a" "b"] -1 "z") (put ["a" "b"] /-2 "z") (put ["a" "b"] -3 "z") (remove ["a" "b"] -1) (remove ["a" "b"] -3) (collections/update [1 2] -1 (fn [old] (+ old 10))) (str /a/-1)
"c" "b" "a" null "none" "c" "b" "a" "b" "key" #err {<mismatch type> message "lists require integer indices"} 91 true false ["a" "z"] ["z" "b"] #err {<invalid value> message "index out of range"} ["a"] ["a" "b"] [1 12] "/a/-1"
Every format writes a pointer as RFC 6901 text when text can express it, and
/a/-1 is such text. A pointer with a computed segment is written as a list of
segments: /a/,i in DUST, #jsonptr [a #local i] in RON, and
{"#jsonptr":["a",{"#local":"i"}]} in JSON. Other RFC 6901 implementations read
/a/-1 as the key "-1", and can not read a list of segments.
RON represents a literal pointer as #jsonptr with a string payload. A
pointer containing embeds has a list payload. For example, these DUST pointers:
/a/0
/3/,"3"
/foo/user-,(+ 1 id)/,k,/0
have these RON representations:
[#jsonptr /a/0 #jsonptr /3/3 #jsonptr [foo [user- #invoke [+ 1 #local id]] #local k 0]]
Formatting the third pointer as DUST writes its embedded forms in the pointer
literal rather than the #jsonptr representation.
In the second example, both segments are indices. Map lookup converts an index to its decimal string key. Quotation, mute, and unevaluated parts of quasiquotation preserve tagged data; unquote follows the usual quasiquote rules.
(jsonptr? /) (str /) (str //a) (str /a/) (str /a~1b/x~0y) (str /f(x)) (let [k "name"] (str /users/,k)) (let [n 10] (str /user-,(+ n 1))) (let [k "a/b"] (str /,k)) (let [k "x~y"] (str /,k)) (let [p /3/,"3"] (get [null null null {3 "found"}] p)) (let [p /3/,(int "3")] (get [null null null ["a" "b" "c" "found"]] p)) /,null /,true (count /a/b/0) (first /a/b/0) (str (rest /a/b/0)) (= /a/0 (jsonptr "/a/0")) (let [x 3] (str /foo/,x)) (get ["a" "b" "c" "d"] /,"3") (get ["a" "b" "c" "d"] /,"\u0033") (let [n "3"] (get ["a" "b" "c" "d"] /,n)) (let [n "3"] (get {3 "yes"} /,n)) (let [n "03"] (get {03 "yes"} /,n)) (let [n "3"] (= /,n /3))
(jsonptr? /) (str /) (str //a) (str /a/) (str /a~1b/x~0y) (str /f(x)) (let [k "name"] (str /users/,k)) (let [n 10] (str /user-,(+ n 1))) (let [k "a/b"] (str /,k)) (let [k "x~y"] (str /,k)) (let [p /3/3] (get [null null null {3 "found"}] p)) (let [p /3/,(int "3")] (get [null null null ["a" "b" "c" "found"]] p)) /,null /,true (count /a/b/0) (first /a/b/0) (str (rest /a/b/0)) (= /a/0 (jsonptr "/a/0")) (let [x 3] (str /foo/,x)) (get ["a" "b" "c" "d"] /3) (get ["a" "b" "c" "d"] /3) (let [n "3"] (get ["a" "b" "c" "d"] /,n)) (let [n "3"] (get {3 "yes"} /,n)) (let [n "03"] (get {03 "yes"} /,n)) (let [n "3"] (= /,n /3))
true "/" "//a" "/a/" "/a~1b/x~0y" "/f(x)" "/users/name" "/user-11" "/a~1b" "/x~0y" "found" "found" #err {<mismatch type> message "pointer segments must be strings or integers"} #err {<mismatch type> message "pointer segments must be strings or integers"} 3 "a" "/b/0" true "/foo/3" "d" "d" "d" "yes" "yes" true
(let [p /3/,"3"] [p (get [null null null {3 "yes"}] p) (str p)]) (let [name "Ada"] (str /,~"hello-,name")) (str /,~"inner ,(str "x")") [(str /a,,b) (get {"a,b" 1} /a,,b) (str /a,,) (let [x "tail"] (str /,,,x))]
(let [p /3/3] [p (get [null null null {3 "yes"}] p) (str p)]) (let [name "Ada"] (str /,~"hello-,name")) (str /,~"inner ,(str "x")") [(str /a,,b) (get {"a,b" 1} /a,,b) (str /a,,) (let [x "tail"] (str /,,,x))]
[ [/3/3 "yes" "/3/3"] "/hello-Ada" "/inner x" ["/a,b" 1 "/a," "/,tail"]]
1.2.8. Invocations
Parentheses produce a #invoke tagged element whose payload is a list.
The first element is the callee, and the remaining elements are argument forms.
A direct callee is a name encoded as a string, without a #local or #const wrapper.
In this position, surrounding quote characters belong to the name.
This differs from string parsing in argument position.
A callee that begins with . or : is a reference, and therefore a computed callee.
(upper "hello")
#invoke [upper hello]
#cases [{bindings {upper (fn [x] x)} output "hello"}]
("upper" "hello")
#invoke [""" "upper" """ hello]
#cases [{bindings {""\"upper""" (fn [x] x)} output "hello"}]
("+" 1 2)
#invoke [""" "+" """ 1 2]
#cases [{bindings {""\"+""" (fn [a b] (+ a b))} output 3}]
(let [twice (fn [x] (* 2 x))] (twice 21))
(let [twice (fn [x] (* 2 x))] (twice 21))
#invoke [let [#local twice #invoke [fn [#local x] #invoke [* 2 #local x]]] #invoke [twice 21]]
(:upper "hello")
#invoke [#const upper hello]
#cases [{bindings {upper (fn [x] x)} output "hello"}]
(f :x)
#invoke [f #const x]
#cases [{bindings {f (fn [value] value) x "Ada"} output "Ada"}]
A computed callee is encoded as the first form in #invoke.
For example:
The parser does not resolve invocation names, check whether a callee produces a function, or evaluate arguments.
Unknown names and expressions such as (/ 1 0) are valid parser inputs.
Their evaluation belongs to DUST.
An empty invocation, (), parses as #invoke [].
Parsing does not require a callee; an empty invocation has no function to evaluate.
Whitespace separates forms throughout an invocation and list, including across
newlines, even when the callee begins on a later line. String arguments use
quotes or fences. Binding and parameter lists follow the same separation rules.
The parser does not interpret special-form names or binding positions.
(let [ first name "second name" ] ["first" "name"])
(let [ first name "second name"] ["first" "name"])
#invoke [let [ #local first #local name second name] [first name]]
1.2.9. Quotation forms
The four prefixes apply to the immediately following form and parse to a tagged element. The prefix and its form are adjacent; quote or fence a string beginning with one of these characters when it is meant as text.
| Prefix | Explicit tagged notation |
|---|---|
`form |
#quote form |
~form |
#quasiquote form |
,form |
#unquote form |
,@form |
#unquote-splicing form |
,@items
#unquote-splicing #local items
#err <outside quasiquote splicing unquote>
`~(f ,x ,@xs)
#quote #quasiquote #invoke [f #unquote #local x #unquote-splicing #local xs]
~(f ,x ,@xs)
Quoting a string does not turn it into a DUST quotation form.
#unquote name
,name
#unquote #local name
#err <outside quasiquote unquote>
Quotation names have no special meaning inside parentheses: (quote 1)
parses as #invoke [quote 1] and formats as (quote 1).
The explicit quotation notation is #quote 1, whose canonical DUST spelling
is `1. The same rules apply to the other three quotation tags.
Quote returns its enclosed form as data without evaluating references,
invocations, or collection contents within it.
Quasiquote constructs data in the same way, except that unquote evaluates
one enclosed form and substitutes its resulting value.
Unquote-splicing evaluates an enclosed list and inserts its elements into the
surrounding list, in order. Splicing null inserts nothing, so a rest
parameter that received no arguments splices as an empty list.
With x bound to 2 and xs bound to [3 4]:
`["a" x] ; returns ["a" x]
~["a" ,x ,@xs] ; returns ["a" 2 3 4]
Nested quasiquotes match unquotes by nesting depth: entering a quasiquote
increases the depth, and an unquote or splice belongs to its matching
quasiquote. An inner quasiquote's substitutions are not executed by an outer one.
Unquote outside quasiquote produces #err <outside quasiquote unquote>,
and unquote-splicing outside quasiquote produces
#err <outside quasiquote splicing unquote>.
Unquote-splicing outside a list-element position, or splicing a value that is
neither a list nor null, produces #err <invalid quotation>.
The DUST parser constructs the tagged elements. DUST decides how to resolve a reference, invoke a function, or process a quotation form. Those evaluation rules belong to DUST rather than the data format.
1.2.10. Application value prefixes
The meanings of #link, #dur, #utc, #uuid, #hash, and #b64 belong to DUST. They use RON’s generic #prefix value notation; RON accepts these prefixes without interpreting them. Payload validation and evaluation semantics belong to DUST. Parsing preserves the tagged representation without evaluating it, except that valid #utc, #dur, and #uuid payloads are rewritten to their canonical spelling: #utc 1970-01-01T00:00Z reads and formats as #utc 1970-01-01T00:00:00Z, and #dur PT90M as #dur PT1H30M. Invalid payloads produce parse errors.
#uuid holds a 16-byte UUID. Its string payload uses the hyphenated
8-4-4-4-12 representation. Input accepts uppercase or lowercase hexadecimal;
output uses lowercase. uuid? checks this native kind.
Stardust imports #utc as a typed UTC value. Evaluating it returns that same
value; it does not execute or reinterpret its timestamp payload. Formatting
exports the normal tagged representation through the selected notation codec.
#utc and #dur are distinct signed 64-bit counts of 100 ns ticks. UTC counts
from the Unix epoch; durations count elapsed ticks. Canonical text has at most
seven fractional second digits. Input accepts up to nine digits, rounded to the
nearest tick, with halfway cases rounded away from zero. A nonzero timestamp or
duration that would round to zero is represented by one tick in magnitude.
See the Time library for ranges, constructors, units,
calendar operations, and explicit tick/nanosecond conversion.
#link constructs a distinct link value with an integer, string, or tagged
payload. Integer payloads use the full signed 64-bit range. String payloads stay
strings, including numeric-looking names such as #link "42". Tagged payloads
retain their tag and value, as in #link #url "https://arst.com/arst".
String payloads require quotes: #link "foo" carries the name foo.
An unquoted payload such as #link foo evaluates the local reference foo. Stardust preserves
names without resolving them; a query or transaction engine can interpret a name
as a temporary ID. Stardust does not fetch or interpret tagged link targets.
A reference or invocation in the payload is evaluated before constructing the
link. For example, (let [foo 42] #link foo) produces #link 42.
Quotation preserves constructor syntax: `#link foo does not look up foo.
Booleans, floats, plain maps, and lists are invalid evaluated link payloads.
A payload that evaluates to an error is the result instead of a link:
#link missing returns the unbound-name error, so error? and falsiness see it.
#link missing #link (/ 1 0) (error? #link missing)
#err <name unbound> #err <division integer zero> true
Database patch documents declare temporary entities with keys beginning with
_. In patch values, a bare _name symbol refers to the temporary entity.
The quoted expression below produces a patch document as data:
`{patch {_paul {name "Paul"}
_chani {name "Chani" partner _paul}}}
Within a patch, _paul, #link _paul and #link "_paul" refer to the
same temporary entity. A plain string "_paul" remains text. Temporary
references work inside ordered lists, nested maps and ordinary tagged values.
A tagged target inside a link, such as #link #url "https://example.com",
keeps its own meaning rather than becoming an entity reference.
JSON uses a string link payload, because JSON has no symbols:
{"patch":{"_paul":{"name":"Paul"},
"_chani":{"name":"Chani","partner":{"#link":"_paul"}}}}
Temporary names need a suffix: _ alone is invalid. Every referenced name
must have a target in the same patch scope. Repeated names within a selected
query row refer to the same entity. Another row or invocation gets fresh
temporary entities. Existing entities still use integer links such as
#link 42. Outside patch values, _name follows ordinary binding rules.
Saving authored source preserves these symbols without creating entities.
The canonical form #link 42 has this JSON representation:
{"#link": 42}
A link is distinct from an integer even when their payloads match.
Both (int? #link 42) and (number? #link 42) return false, and numeric
operations reject link operands. Integer link payloads sort before string payloads, then tagged payloads.
Payloads use their type’s ordering; tagged ordering requires scalar tag payloads.
Comparing #link 42 with the integer 42 produces a type-mismatch error.
(do [#link 0 #link -1 #link -9223372036854775808 #link 9223372036854775807])
#link 0 #link -1 #link -9223372036854775808 #link 9223372036854775807
(do [(= #link 42 #link 42) (= #link 42 #link 43) (comparisons/identical? #link 42 #link 42)])
true false true
{ dependsOn #link 42 when #utc "2026-09-09T00:00:00Z" }
{dependsOn #link 42 when #utc "2026-09-09T00:00:00Z"}
dependsOn #link 42 when #utc 2026-09-09T00:00:00Z
{dependsOn #link 42 when #utc "2026-09-09T00:00:00Z"}
Braces make a map, not a tag:
{#utc "2026-10-24T12:34:56Z"}
"#utc" 2026-10-24T12:34:56Z
{#utc "2026-10-24T12:34:56Z"}
#hash holds a digest tagged with its algorithm; the
hash library defines its payload and equality.
#hash #sha256 "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
#hash #sha256 e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
#hash #sha256 "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
#b64 holds bytes as base64 text; the
bytes library defines its payload and equality.
1.2.12. Mute
A backslash prefix, \form, mutes the immediately following complete form.
The prefix and its form are adjacent.
It applies to invocations, references, scalar values, lists, maps, and tagged elements.
The parser still reads the muted form's notation and balances its delimiters;
malformed strings or unmatched delimiters remain syntax errors.
A muted form is represented as a #mute tagged element whose payload is the
preserved form. For example, (+ 1 \(* 20 30) 2) has the form representation
#invoke [+ 1 #mute #invoke [* 20 30] 2].
The explicit #mute form spelling is accepted, and canonical DUST writes the
backslash shorthand. RON and JSON keep the tagged element.
(+ 1 #mute (* 20 30) 2)
(+ 1 \(* 20 30) 2)
#invoke [+ 1 #mute #invoke [* 20 30] 2]
When reading files or interpreting source lists and invocation argument sequences,
DUST excludes muted elements before evaluation, macro expansion, and arity or binding checks.
Their payloads are not evaluated or checked for semantic validity.
Muted elements contribute no element or argument, not a null placeholder.
The active forms must satisfy the usual rules.
Known tags inside a muted payload are still validated on import, so \#local 42
is invalid just as #local 42 is.
(+ 1 \(* 2 3) 4) ; evaluates to 5
[\missing \[1 2] \{a 1}]
\missing \[1 2] \{a 1}
[#mute #local missing #mute [1 2] #mute {a 1}]
A file containing only muted forms produces no evaluation results. A muted value
cannot supply a root expression, a map value or an invocation callee.
These uses are evaluation errors, not parse errors: #err <mute root value>,
#err <map mute value>, and #err <callee mute>.
Data values are not filtered for mute elements.
To begin a literal string with a backslash, quote the string.
["\\path" "\\(+ 1 2)"]
"\\path" "\\(+ 1 2)"
[ \path \(+ 1 2)]
"\\path" "\\(+ 1 2)"
1.2.13. Canonical expression formatting
Canonical DUST formatting preserves the parsed form.
Consecutive forms in an invocation or packed list are separated by a space when they share a line.
Consecutive closing delimiters can be adjacent.
An invocation stays on one line when it fits RON's 100-column target.
Otherwise, it wraps between complete arguments, with continuation lines
indented two spaces from the invocation's starting column.
Multiline def forms keep each name/value pair together, and cond keeps
each tests/result pair together. The binding lists of let and for
keep each binding pattern with its value. Each pair starts a new line when
the form or binding list needs to wrap; comments can separate a pair, and
long values can wrap across additional lines. Short forms stay on one line.
Function forms keep their declaration names and short parameter lists together.
Valid references use name and :name, invocations use parentheses (including ()),
quotation forms use their short prefixes, and muted forms use \. Explicit tagged data that has no
faithful shorthand, such as #local "two words", #const "", or #local ".x",
retains explicit notation. A direct callee whose name begins with . or :
also keeps the explicit #invoke notation. Formatting and parsing the result preserves the JSON representation.
A comment on an invocation element stays on that element.
Canonical formatting writes it as ; lines above the element.
[ (quote 1) (quasiquote ["a" "b"]) (unquote x) (unquote-splicing xs) ]
(quote 1) (quasiquote ["a" "b"]) (unquote x) (unquote-splicing xs)
[#invoke [quote 1] #invoke [quasiquote [a b]] #invoke [unquote #local x] #invoke [unquote-splicing #local xs]]
{empty #local "" spaces #local "two words" non-string #local 42 quoted-name #local ".x" colon-name #const ":x" non-list #invoke 42 numeric-callee #invoke [1 2] spaced-callee #invoke ["two words" 1] var-callee #invoke [#local "f" 1] const-callee #invoke [#const "f" 1] dotted-callee #invoke [".f" 1] quoted-callee #invoke [#quote f 1] empty-call #invoke []}
{colon-name #const ":x" const-callee #invoke [:f 1] dotted-callee #invoke [".f" 1] empty #local "" empty-call #invoke [] non-list #invoke 42 non-string #local 42 numeric-callee #invoke [1 2] quoted-callee #invoke [`f 1] quoted-name #local ".x" spaced-callee #invoke [ "two words" 1] spaces #local "two words" var-callee #invoke [f 1]}
colon-name #const :x const-callee #invoke [#const f 1] dotted-callee #invoke [.f 1] empty #local "" empty-call #invoke [] non-list #invoke 42 non-string #local 42 numeric-callee #invoke [1 2] quoted-callee #invoke [#quote #local f 1] quoted-name #local .x spaced-callee #invoke [ two words 1] spaces #local "two words" var-callee #invoke [#local f 1]
(f ; before the first argument 1 ; first argument 2)
(f ; before the first argument ; first argument 1 2)
#invoke [f ; before the first argument ; first argument 1 2]
(function-name "a string argument with several words" "a string argument with several words" "a string argument with several words" "a string argument with several words" )
(function-name
"a string argument with several words"
"a string argument with several words"
"a string argument with several words"
"a string argument with several words")
#invoke [
function-name
a string argument with several words
a string argument with several words
a string argument with several words
a string argument with several words]
["foo(bar)" "(bar)" "abc)" ".name" ":name"]
"foo(bar)" "(bar)" "abc)" ".name" ":name"
[foo(bar) (bar) abc) .name :name]
These rules apply to DUST source, not str, which formats collections through the canonical RON formatter.
1.3. Values and Evaluation
DUST is an expression-oriented programming language, thus every language construct evaluates to a value. We call these language constructs forms. Forms beget values by evaluation. At the bottom lie the self-evaluating values. These are the values that evaluate to themselves.
null is the value that represents the absence of a value.
null is falsey.
true is the value that represents truth.
true is truthy.
false is the value that represents falsehood.
false is falsey.
String values use RON quotes, fences, and escapes. Strings are interned.
Numbers are RON numbers: integers are signed 64-bit and floats are IEEE 754
doubles. A literal outside those ranges, such as 1e400, is a parse error.
Numbers never convert implicitly. Arithmetic and comparison operands must be
all integers or all floats, so (+ 1 2.5) is #err <mismatch type>; write
(+ 1.0 2.5) or convert with float and
int. Division is the one operation whose result kind
differs from its operands: / always returns a float.
Operations check their results. Integer overflow is #err <integer overflow>,
a float result that would be infinite or NaN is #err <float overflow>, and
division by zero is #err <division integer zero> or
#err <division float zero> by operand kind. NaN and infinity therefore never
exist as numbers: a value can only hold a number that JSON can spell.
DUST does not have keywords because RON does not have keywords. Map keys are strings, so DUST does not need a separate keyword type.
1.3.1. References
However DUST does need references.
A reference is a name that refers to something else; in other languages you might know it as an identifier.
DUST has two kinds. Bare names look up locals; the : prefix looks up constants:
| Source | Tagged form | JSON | Looks up |
|---|---|---|---|
name |
#local "name" |
{"#local": "name"} |
Local bindings: let, fn parameters, a function's own name, for, and top-level def |
:name |
#const "name" |
{"#const": "name"} |
Constants: library entries and bindings supplied by the host |
References follow the source notation rules.
A quoted string whose contents begin with . or : is not a reference.
Map keys are always strings, including names beginning with . or :.
Parsing constructs a reference without resolving its name.
Binding forms interpret name forms as declarations.
A local reference resolves to the nearest enclosing local binding, whether
its value is a function or ordinary data. With no enclosing binding, it is
the top-level local of that name, read each time the reference runs. It
never reaches a constant: math/pi is unbound unless a local binding has
that name. An unbound local is an error when evaluation reaches it, so
(if true 1 missing) returns 1.
Schemas need a few names without a prefix, so these names are the exception.
With no let, fn or for binding of that name, a reference to one of them
is a builtin or a schema marker:
- the kind predicates, such as
int?,string?andmap?(the list is in schemas/valid?); - the comparisons
<,<=,>,>=,=,==,!=andcomparisons/not=, andschemas/meet,schemas/joinandschemas/simplify; - a prefixed predicate, such as
chars/letter?; - the markers
any,never,⊤,⊥,meet,join,not,maybe,map-of,count,error,default,is,optional,bind,...and=>.
A marker is not a function. As a value, count is the count marker, while
(count xs) and :count reach the function; the same holds for not.
Calling a marker, as in (error "x"), is #err <expected function>.
A def of one of these names is #err <conflict name>, so a bare
name such as int? has the same meaning in every top-level form. A function
that refers to it does not read the scope for it. A let or fn binding
still shadows it:
; A bare kind name or marker with no binding is the builtin. (schemas/valid? [meet int? [is > 3]] 8) ; A let or fn binding shadows the builtin meaning. (let [int? (fn [v] false)] (schemas/valid? int? 8)) ((fn [int?] (schemas/valid? int? 8)) (fn [v] false)) (let [is 5] is) ; A function that reads only bare schema names gives the same answer each call. (def positive? (fn [x] (schemas/valid? [meet int? [is > 0]] x))) [(positive? 3) (positive? -3) (positive? "3")]
; A bare kind name or marker with no binding is the builtin. (schemas/valid? [meet int? [is > 3]] 8) ; A let or fn binding shadows the builtin meaning. (let [int? (fn [v] false)] (schemas/valid? int? 8)) ((fn [int?] (schemas/valid? int? 8)) (fn [v] false)) (let [is 5] is) ; A function that reads only bare schema names gives the same answer each call. (def positive? (fn [x] (schemas/valid? [meet int? [is > 0]] x))) [(positive? 3) (positive? -3) (positive? "3")]
true false false 5 positive? [true false false]
A constant reference never reaches a local binding: (let [x 1] :x) is
unbound. Library entries are fixed: a host binding with the same name as a
library entry is rejected, and every evaluation with that binding produces
#err <conflict name>, whether or not the program refers to the name. A host
that needs its own value supplies it under another namespace.
Every constant in a program is resolved once, before evaluation starts. If any
of them is unbound, the program evaluates to that #err <name unbound>, even
when the reference is in a branch that would not run. Constants inside quoted
or muted forms are not evaluated, so they are not resolved.
A pointer has the type name pointer and holds a sequence of Key string
segments and Index integer segments. RFC 6901 text is used when
constructing, encoding, or printing it. Decoding splits at /, replaces ~1
with / and ~0 with ~, and treats decimal digits with no leading zeroes
as an index, with a leading - for one counted from the end, saturating at the
largest signed 64-bit integer. Encoding writes
indices in decimal and escapes ~ before / in keys. After printing and
reading again, Key "0" becomes Index 0. The two select the same map key,
but only the index can select a list element.
Pointer equality compares segment kinds and values. list? is false for a
pointer, and jsonptr? is true. str returns the RFC 6901 text, while format
and the REPL print the canonical DUST form. Functions that accept arbitrary
values also accept pointers, including equality, distinctness, and map values.
A direct invocation resolves the exact name stored in the first element of #invoke.
It looks first in the local bindings and then in the constants, so both
(increment 4) with a let-bound increment and (+ 1 2) work.
("+" 1 2) looks up a name containing the quote characters as well as the plus sign.
(f 1) is a direct invocation that can call a local function.
(:+ 1 2) is a computed callee whose reference follows the rules above.
A missing binding produces an unbound-name error.
1.3.2. Evaluation
Evaluation turns a form into a value. RON and JSON representations of the same source form have identical evaluation semantics. Input values and returned values are values, not source to evaluate again.
Known tagged elements are validated before evaluation. This includes known tags
inside quotations, muted forms, and branches that would not be selected during evaluation.
Unknown tags remain generic tagged data. Evaluating one returns its tag and
payload as data, without evaluating the payload or any nested invocation.
For example, #custom (/ 1 0) preserves the invocation as data and does not
divide by zero. Formatting and notation round trips preserve the normal tagged
representation.
This opaque evaluation rule does not bypass import validation. Known tags
nested inside an unknown payload are still validated eagerly; for example,
#custom #local 42 has an invalid known reference payload. Today that is the
parse error invalid tag.
#application { symbol missing invocation (unknown-function missing) unquote ,missing splice ,@missing nested #another (unknown-function (/ 1 0)) }
#application {invocation (unknown-function missing) nested #another (unknown-function (/ 1 0)) splice ,@missing symbol missing unquote ,missing}
#application {invocation (unknown-function missing) nested #another (unknown-function (/ 1 0)) splice ,@missing symbol missing unquote ,missing}
The self-evaluating forms already represent their value, so evaluating them results in themselves. Other forms describe how to obtain a value, for example by looking up a name to grab what it represents or invoking a function.
An invocation is encoded as a #invoke tagged element containing the callee followed by its argument forms.
For an ordinary function call, a string in the first element of #invoke names the function to resolve.
Any other form in that position is evaluated once to obtain the function.
Direct invocation names resolve to the nearest local binding, then to a
constant. References resolve as described in References.
The result must be a function.
A direct invocation name with no binding gives #err <name unbound>, which
names the missing binding. A declared local that has no value yet is
also unbound. A bound or computed callee that is not a function gives
#err <expected function>.
A computed callee that returns a string is an error, even if that string names a function. There is no second name lookup.
DUST excludes muted argument forms, then evaluates the active argument forms from left to right and passes their resulting values to the function. The function's return value becomes the value of the invocation.
Examples show DUST source beside its expected result.
(nope 1) (def declared) (declared 1) (def x 1) (x 2) ((if true nope 1) 1) (do (nope 1) 42) (let [ignored (nope 1)] 42) ((fn [] (nope 1) 42))
#err {<name unbound> message "unbound name: nope"} declared #err {<name unbound> message "unbound name: declared"} x #err {<expected function> message "expected a function value"} #err {<expected function> message "expected a function value"} #err {<name unbound> message "unbound name: nope"} 42 #err {<name unbound> message "unbound name: nope"}
(+ 1 (* 2 2)) can be thought of as being evaluated in two steps:
- Evaluate
(* 2 2)to obtain4. - Substitute
4for the multiplication, giving(+ 1 4), which evaluates to5.
Hence:
Square brackets construct lists and braces construct maps. List construction excludes muted elements and evaluates the active elements from left to right. Map construction evaluates each member value1; the order in which member values are evaluated is not defined. Canonical key order is a formatting rule, not an evaluation order. A muted form cannot supply a map member value.
Tags parse into ordinary boolean map members before evaluation. Their names are string keys, not references, and their boolean values evaluate to themselves. Tags introduce no new evaluation behavior.
An evaluation error is a value. It can be bound by let or stored in a list
or map, and evaluation of the other elements continues. A program can inspect
an error with error?.
A call whose argument is an error returns that error, and the function does
not run. The arguments are evaluated from left to right, and the first error
ends the call: the later arguments are not evaluated. Thus a function does not
replace the cause with an error of its own. For example, (count missing)
returns the unbound-name error of missing, not a type mismatch. The rule
applies to each call: of a library function, a plugin function, a function
made by fn, defn, defquery or defmutation, and a computed callee. A
callee is evaluated before the arguments, so a callee that is not a function
still gives its own error.
(count missing) (+ missing 1) (+ (/ 1 0) missing) (= missing 1) (compare (/ 1 0) 1) (str "rate: " missing) (format "%s" (/ 1 0)) (not missing) (put {} "a" (/ 1 0)) (lists/append [1] missing) (let [m {}] [(+ (/ 1 0) (count (put m "a" 1))) m]) (let [m {}] [(+ (* (/ 1 0) 2) (count (put m "a" 1))) m])
#err {<name unbound> message "unbound name: missing"} #err {<name unbound> message "unbound name: missing"} #err {<division integer zero> message "division by zero"} #err {<name unbound> message "unbound name: missing"} #err {<division integer zero> message "division by zero"} #err {<name unbound> message "unbound name: missing"} #err {<division integer zero> message "division by zero"} #err {<name unbound> message "unbound name: missing"} #err {<division integer zero> message "division by zero"} #err {<name unbound> message "unbound name: missing"} [#err {<division integer zero> message "division by zero"} {}] [#err {<division integer zero> message "division by zero"} {}]
((fn [amount] 5) (/ 1 0)) (let [rate (fn [amount] (* amount 2))] (rate missing)) (let [inspect (fn [value] (if (error? value) "caught" value))] (inspect (/ 1 0))) (let [measure :count] (measure missing)) ((if true :count :str) missing) (let [callee null] (callee (/ 1 0))) (let [countdown (fn countdown [n] (if (= n 0) 0 (countdown (- n (/ 1 0)))))] (countdown 3)) ((fn [a b] [a b]) (+ 1 "a") (count 5)) ((fn [a] a) (str "k" (/ 1 0))) ((fn [a] a) (count (/ 1 0))) ((fn [value] [[join int? error?] => boolean?] (error? value)) (+ 1 "a")) (let [total (fn total [n acc] (if (= n 0) acc (total (- n 1) (+ acc "x"))))] (total 3 0)) (let [total (fn total [n acc] (if (= n 0) acc (total (- n 1) (* acc 3))))] (total 50 1)) (error? (+ 1 "a")) ((fn [m] 1) (put 3 "a" 1)) (let [fill (fn fill [i acc] (if (= i 2) acc (fill (+ i 1) (put acc i (/ 1 0)))))] (fill 0 {})) (nope (/ 1 0))
#err {<division integer zero> message "division by zero"} #err {<name unbound> message "unbound name: missing"} #err {<division integer zero> message "division by zero"} #err {<name unbound> message "unbound name: missing"} #err {<name unbound> message "unbound name: missing"} #err {<expected function> message "expected a function value"} #err {<division integer zero> message "division by zero"} #err {<mismatch type> message "expected a number"} #err {<division integer zero> message "division by zero"} #err {<division integer zero> message "division by zero"} true #err {<mismatch type> message "expected a number"} #err {<integer overflow> message "integer overflow"} true #err {<mismatch type> message "expected a map or list"} #err {<division integer zero> message "division by zero"} #err {<name unbound> message "unbound name: nope"}
Some functions receive an error argument and run:
error?, the
errors/ functions, the value argument of
schemas/valid? and
schemas/explain, which match an error
with error? or [error S], and a function whose contract admits an error
for that parameter. This also applies when such a function is the value of
a local.
(error? missing) (let [inspect :error?] (inspect (/ 1 0))) (schemas/valid? error? (/ 1 0)) (schemas/valid? int? (/ 1 0)) (schemas/explain error? (/ 1 0)) (schemas/valid? missing 1)
true true true false null #err {<name unbound> message "unbound name: missing"}
Because str and format return an error argument, a program writes an
error's text with errors/message:
(let [result (/ 1 0)] [(str "failed: " (errors/message result)) (str "failed: " result) (if (error? result) (str "failed: " (errors/message result)) result)])
(let [result (/ 1 0)] [(str "failed: " (errors/message result)) (str "failed: " result) (if (error? result) (str "failed: " (errors/message result)) result)])
"failed: division by zero" #err {<division integer zero> message "division by zero"} "failed: division by zero"
((fn [value] [[join int? error?] => boolean?] (error? value)) (/ 1 0)) ((fn [value] [int? => int?] value) (/ 1 0)) ((fn [value] [any => boolean?] (error? value)) (/ 1 0)) ((fn [a b] [int? [join int? error?] => int?] 1) missing (/ 1 0)) ((fn [a b] [[join int? error?] int? => int?] 1) missing (/ 1 0))
true #err {<division integer zero> message "division by zero"} #err {<division integer zero> message "division by zero"} #err {<name unbound> message "unbound name: missing"} #err {<division integer zero> message "division by zero"}
Special forms are not calls. if, and, or and cond test an error as
falsey and evaluate only what they select, and let and do bind and
sequence errors as values. A list or map literal keeps an error as an
element or member value, but a call that adds an error to a collection, such
as put, returns the error.
(if (/ 1 0) "then" "else") (if true 1 missing) (and true missing) (or missing 3) (cond (error? missing) "error" true "value") (let [unused missing] 5) (when false missing)
"else" 1 #err {<name unbound> message "unbound name: missing"} 3 "error" 5 null
(count [missing missing]) [(/ 1 0) 1] {rate missing} (error? (first [(/ 1 0)]))
2 [#err {<division integer zero> message "division by zero"} 1] {rate #err {<name unbound> message "unbound name: missing"}} true
A higher-order function, such as map, reduce or lists/filter, calls its
function in the same way. An error element is the result of the call for that
element, and the function does not run for it.
(map (fn [x] (+ x 1)) [(/ 1 0) 1]) (map (fn [x] 7) [(/ 1 0) 1]) (map :error? [(/ 1 0) 1]) (lists/filter :error? [(/ 1 0) 1]) (lists/filter (fn [x] (error? x)) [(/ 1 0) 1]) (reduce :+ 0 [1 (/ 1 0)]) (apply :+ [(/ 1 0) 1]) (let [constant (if true (fn [x] 7) null)] (map constant [(/ 1 0) 1])) (map (functions/comp :count :str) [(/ 1 0) 12])
[[#err {<division integer zero> message "division by zero"} 2] [#err {<division integer zero> message "division by zero"} 7] [true false] [#err {<division integer zero> message "division by zero"}] [] #err {<division integer zero> message "division by zero"} #err {<division integer zero> message "division by zero"} [#err {<division integer zero> message "division by zero"} 7] [#err {<division integer zero> message "division by zero"} 2]]
In a query or mutation, a call that receives a captured error, such as
(in ?r ranks) with ranks bound to an error, makes the query return that
error, and a mutation then writes nothing.
An error is a #err tagged element. Its payload can be any value.
A map can contain a RON tag group that classifies the error and members
that describe the failure:
#err {<division integer zero>
column 1
line 1
message "division by zero"}
Match errors by their tags, such as #err <division integer zero>.
Messages and source positions can change between versions.
An error value retains its tags when passed through a program. Resource and
memory failures can stop evaluation.
Special forms control evaluation rather than following the ordinary function-call rule.
For example, if evaluates only the selected branch.
Macros transform forms before evaluation, while quotation allows a form to be used as data without evaluating it.
1.3.2.1. Error tags
Tags are a set, not a path: each tag is one word naming one facet of the
failure, so an error can be looked up by any predicate it carries. overflow
matches both integer and float overflow, integer matches every failure of
integer arithmetic, mismatch matches type and arity mismatches, and mute
matches every misuse of a muted form. Language errors use the tags below; Stardust errors carry
stardust, and applications should add a tag naming themselves.
| Tags | Raised when | Example |
|---|---|---|
<mismatch type> |
An operand has the wrong type, including mixed integer and float arithmetic | (+ 1 2.5) |
<integer overflow> |
An integer, duration, or timestamp result leaves the 64-bit range | (+ 9223372036854775807 1) |
<float overflow> |
A float result would be infinite or NaN | (* 1e308 10.0) |
<division integer zero> |
An integer or duration divisor is zero | (/ 1 0) |
<division float zero> |
A float divisor is zero | (/ 1.0 0.0) |
<invalid value> |
An argument has the right type but an unusable value | (time/duration "forever") |
<invalid tag> |
A known tag has a malformed payload | #utc "yesterday" |
<name unbound> |
A reference or callee has no visible binding | missing |
<conflict name> |
A host binding or a defmacro has the name of a special form or a library entry |
binding math/pi, (defmacro map [f xs] xs) |
<arity mismatch> |
A function receives a number of arguments it does not accept | ((fn [x] x)) |
<argument missing> |
A variadic operator receives no arguments where one is required | (/) |
<list missing> |
A function that takes lists receives none | (map :strings/case) |
<expected function> |
A callee evaluates to a non-function | (map upper [ada]) |
<callee string> |
A computed callee evaluates to a string | ((str "a") 1) |
<fn missing name rest> |
... is not followed by a capture name |
(fn [...] 1) |
<arity fn multiple variadic> |
More than one arity is variadic | (fn ([... a] 1) ([x ... b] 2)) |
<arity duplicate fixed fn> |
Two arities take the same fixed count | (fn ([x] 1) ([y] 2)) |
<arity exceeds fixed fn variadic> |
A fixed arity exceeds the variadic arity's minimum | (fn ([x y] 1) ([... r] 2)) |
<mute root value> |
A muted form supplies the root value | \1 |
<map mute value> |
A muted form supplies a map member value | {a \1} |
<callee mute> |
A muted form supplies a callee | (\f 1) |
<outside quasiquote unquote> |
Unquote appears outside quasiquote | ,x |
<outside quasiquote splicing unquote> |
Unquote-splicing appears outside quasiquote | ,@x |
<invalid quotation> |
Quasiquote splices into something other than a list | #quasiquote {a #unquote-splicing [1]} |
<algorithm hash unknown> |
hashes/digest receives an unsupported algorithm |
(hashes/digest "md5" 1) |
<function unrepresentable> |
A host asks for a function value without its source form | |
<invalid program> |
The engine rejects a program before evaluation, including a macro that returns an error or a non-form | (do (defmacro m [] 1)) |
<macro expansion limit> |
Expanding one form exceeds the macro expansion depth limit | (defmacro forever [] ~(forever)) then (forever) |
<configuration invalid> |
The host configured the engine incorrectly | |
<database no> |
A query, mutation or db/reactors call runs, but the database plugin has no path or temporary storage |
|
<limit resource> |
Parsing or evaluation exceeds a CPU, memory, or node limit | (bitsets/range 0 9007199254740992) |
<allocation failure> |
The host cannot allocate memory | |
<failure runtime> |
An evaluation failure |
1.3.3. Collection Paths
Collection paths select values in maps and lists. A string is always one
literal map key, including a string that starts with /. An integer is one
index; a negative index counts from the end of a list, as
Extensions to RFC 6901 describes. A list contains
only string keys and integer indices; an empty list selects the root. A pointer from /..., #jsonptr,
or jsonptr supplies its segments directly.
| Segment | Map | List | Null or missing entry |
|---|---|---|---|
Key s |
Member s |
#err <mismatch type> |
Missing |
Index n |
Member with decimal key n |
Zero-based element n |
Missing |
An out-of-range list index is missing. A missing read returns the default or
null, and contains? returns false. A write creates intermediate maps;
an index in a new map uses its decimal key. A list write at its length appends.
Other container types give #err <mismatch type>. A pointer inside a list path
is a type error.
A whole embedded segment becomes one segment based on its value:
| Embedded value | Result |
|---|---|
| String with valid index spelling | Index |
| Other string | Key, without further RFC 6901 decoding |
| Integer | Index |
| Null, boolean, float, list, map, pointer, or function | #err <mismatch type> |
| Error | The same error |
A mixed segment always becomes a key, even if its resulting text is digits.
Its literal parts and embedded strings are concatenated directly; null becomes
null, and other values use their canonical DUST text.
1.3.4. Calling a map or list
A map, list, or packed math value in callee
position reads from itself. The arguments are the
path and an optional default, as in get:
(c path) is (get c path), and (c path default) is (get c path default).
(let [cases {convert {to "json"}}] (cases /convert/to)) ; "json"
(let [cases {convert 1}] (cases "convert")) ; 1
(let [xs [5 6]] (xs 1)) ; 6
(let [cases {convert 1}] (cases /missing 0)) ; 0
({convert 1} /convert) ; 1
The callee can be a literal, a name, or the value of another form. A missing
entry returns the default, or null without one. The call raises the errors
of get: a call with no argument or more than two gives
#err <arity mismatch>, and a path that is not a string, integer, list, or
pointer gives #err <mismatch type>. Any other value that is not a function,
including a string, gives #err <expected function>. In callee position,
/ is still division, so (/ 10 2) is 5.0.
(let [cases {convert 1}] (cases /convert)) (let [cases {convert {from "edn" to "json"}}] (cases /convert/to)) (let [cases {convert 1}] (cases "convert")) (let [k "convert" cases {convert 1}] (cases /,k)) (let [cases {a/b 2}] (cases /a~1b)) ({convert 1} /convert) (let [get-to (fn [m] (m /to))] [(get-to {to 1}) (get-to {to 2})]) (let [id (fn [x] x) cases {convert 1}] ((id cases) /convert))
1 "json" 1 1 2 1 [1 2] 1
(let [xs [5 6]] (xs /1)) (let [xs [5 6]] (xs 1)) (let [xs [[1 2] [3 4]]] (xs /1/0)) (let [xs [{name "Ada"} {name "Bea"}]] (xs /1/name)) (let [i 0 xs [5 6]] (xs /,i)) ([5 6] 1) (let [xs [5 6]] (xs 2)) (let [xs [5 6]] (xs /-1))
6 6 3 "Bea" 5 6 null 6
(let [cases {convert 1}] (cases /missing)) (let [cases {convert 1}] (cases /missing 0)) (let [cases {convert 1}] (cases /convert 0)) (let [cases {convert null}] (cases /convert 0)) (let [cases <!convert>] (cases /convert true)) (let [xs [5 6]] (xs 9 "none")) (let [cases {convert 1}] (cases /convert/deeper "none"))
null 0 1 null false "none" #err {<mismatch type> message "path traverses a non-collection value"}
(let [cases {convert 1}] (cases)) (let [cases {convert 1}] (cases /convert /convert /convert)) (let [n 3] (n /a)) (let [s "convert"] (s /a)) (let [cases null] (cases /a)) (let [cases {convert 1}] (cases 1.5)) (/ 10 2)
#err {<arity mismatch> message "wrong number of arguments"} #err {<arity mismatch> message "wrong number of arguments"} #err {<expected function> message "expected a function value"} #err {<expected function> message "expected a function value"} #err {<expected function> message "expected a function value"} #err {<mismatch type> message "path must be a string, integer, list, or pointer"} 5.0
During namespace initialization, such a call is a read and has no effect. A function that it returns still follows the initialization rules.
1.4. Scope & Binding
DUST is a lexically scoped language. What one might call variables in another language are called bindings in DUST. A scope is the region of code where a binding is valid. A reference with no visible binding produces an unbound-name error.
Code uses a library with import, under an alias. A library names
the members that it provides with export. An import path names a
.dust file beside the importing file, or a namespace that is saved in the
database (Files).
To create local bindings you need to introduce a new scope, and in DUST, like many lisps, the main way to do that is with the let special form.
1.5. Namespace names
Builtin namespaces use plural countable nouns: schemas, documents,
functions, comparisons, errors, bitsets, hashes, pegs, regexes,
processes, scripts, terminals, tests and formats. Existing plural
names such as lists, maps, strings, collections and templates follow
this rule. Request methods use sessions, namespaces and programs.
Domain names and mass nouns keep their established spelling: math, time,
random, encoding and crypto. Standard abbreviations such as io, fs,
db, cli, net and stats also keep their spelling. There are no singular
aliases for plural builtin namespaces. Imported libraries choose their own
explicit aliases.
1.6. Identity & Equality
Equality asks whether two values contain the same data, regardless of how they were constructed or where they came from. Whereas identity asks whether references point to the same value.
Equality in DUST is by value, except for functions which compare by identity.
Equal values have equal hashes, because a hash covers a value's canonical bytes, which keep the integer/float distinction and drop comments. The converse fails only for functions: two closures with the same source hash alike but are not equal, since each is its own identity.
Since functions, constructs that do not exist in JSON or RON, can close over state it only makes sense for them compare by identity.
DUST provides = to test equality and comparisons/identical? to test identity.
1.7. Truth and Control Flow
Control-flow constructs in DUST are also expressions (reminder: everything is an expression), so they evaluate to values. DUST provides the following special forms and macros to enable branching and repetition. They decide which forms get evaluated and how often.
Every condition must be interpreted as either logically true or false. We must categorize each value as either logically true or false. DUST defines truth and falsehood so:
- `null`, `false`, and
#errvalues are falsey - everything else is truthy
An error used as a test therefore selects the false branch: (if ( 1 null) a b)= is b, since ( 1 null)= is an #err value.
We say that they are false/y/ or truth/y/ because they are logically true or false. To say they are true or false would imply they equal true or false, which obviously makes no sense.
DUST provides true? and false? to answer if some value is true or false. And boolean to coerce a value to true or false, and not to negate a value's truthiness.
1.7.1. Branching
1.8. Special forms and macros
Special forms and macros control evaluation or introduce bindings.
A special form is lowered by the evaluator. A macro is a DUST function that
runs before evaluation and returns the form to evaluate. The Macros
section defines them, and defmacro adds new ones.
Ordinary functions are documented in the Function Index.
1.8.1. Function construction
1.8.1.1. fn
Special Form(fn name? doc-or-meta? [params*] body*) → function
(fn name? doc-or-meta? ([params*] body*)+) → function
Creates a function.
The optional name is local to the function and supports self-reference from every arity body.
Functions can be selected, bound, passed, returned, and called.
A function's canonical form is its fn source, so printing and
hashing a closure use that form; values it captures are not part of
it. A library function's canonical form is its quoted name, such as "strings/case".
Recursion is supported.
The optional function name and parameter names are written as bare names.
References to parameters in the body use those same names.
The optional doc-or-meta slot accepts either a string docstring or a map of metadata.
A string docstring supplies the dust/doc entry in the function's metadata.
A bare name after fn names the function. A quoted string is a docstring,
including for an anonymous function. A metadata map can supply documentation
before the parameter list or arity clauses.
Only a docstring or dust/doc metadata documents a function. A comment is
never its documentation: a comment on the parameter list stays on that list.
1.8.1.1.1. Parameters and bodies
A parameter list without ... accepts exactly as many arguments as it has parameters.
An empty parameter list accepts no arguments.
Required parameters accept names or binding patterns.
A variadic parameter list contains one ... name capture, with positional parameters before or after it.
All positional arguments are required, including those after the capture.
The capture receives the intervening values as a nonempty list, or null when there are none.
The capture target is a name or the discard _.
The ... marker replaces & for variadic parameters.
Malformed patterns and duplicate parameter names are compilation errors.
The destructuring examples cover trailing and middle captures, nesting, missing values and discards.
1.8.1.1.2. Contracts
A contract is optional. Put it immediately after each parameter list.
List the input constraints before => and one result constraint after it.
Each arity has a separate contract.
Use ... at the same position as the variadic parameter capture.
One input constraint applies to each positional parameter or binding pattern.
Contract checks do not convert values.
Input checks run before parameter destructuring and body expressions.
A failed input check prevents body effects.
Result checks run after body effects.
An error that stops the body before its final expression is the result that the check examines.
A result constraint admits an error only through error? or [error S];
without one it rejects an error-valued result.
any, tagged?, [not S] and other predicates do not implicitly admit errors.
A union admits an error only through a matching explicit error branch.
An input constraint that admits an error receives an error argument at that position.
At another position, the call returns the error argument, not #err <contract input>,
and the body does not run. A function without a contract never receives an error argument.
A function constraint keeps the relation between an accepted argument sequence and its result.
Input comparison is contravariant. Result comparison is covariant.
A declaration alone does not prove a callable's behavior.
schemas/valid? returns false when it cannot establish the callable contract.
A function contract boundary gives an unproven callable a checked wrapper.
The wrapper checks each invocation; it does not run the callable to test it.
The wrapper is a new function value and does not change the original callable.
Aliases to one wrapper share its identity.
Passing an argument list with apply does not replace callbacks in that list.
The wrapper canonical form contains the contract and the wrapped definition or reference.
Captured runtime state is not part of that form.
An unavailable captured environment causes an explicit reconstruction error.
Contract schemas are evaluated when the function is constructed, so they keep the predicates selected then.
Function source loaded from a document must have contract headers whose construction
uses known pure direct operations without callbacks. Dynamic calls and effects in
these headers cause an explicit reconstruction error; function bodies remain deferred.
(fn [amount]
[int? => int?]
amount)
(fn [first ... more]
[int? ... int? => int?]
(reduce :+ first more))
(defn contracted [amount] [int? => int?] amount) (contracted 5) (defschema ContractInt int?) ((fn [callback] [[ContractInt => ContractInt] => ContractInt] (callback 2)) (fn [value] value)) (defschema ContractAnswer 42) (let [returned ((fn [value] [ContractAnswer => ContractAnswer] value) ContractAnswer) document (documents/from-value returned) definition (documents/value document) closed (documents/close document)] definition) ((fn [amount] [int? => int?] amount) 80) ((fn [amount] [int? => int?] amount) "80") ((fn [amount] [int? => int?] "bad") 80) ((fn [amount] [int? => int?] (/ amount 0)) 1) ((fn [amount] [int? => [join int? error?]] (/ amount 0)) 1) ((fn ([x] [int? => int?] x) ([x y] [int? int? => int?] (+ x y))) 1 2) ((fn [first ... more] [int? ... int? => int?] (reduce :+ first more)) 1 2 3) ((fn [{amount amount}] [map? => int?] amount) {amount 4}) (let [state {ran false} result ((fn [amount] [int? => int?] (put state "ran" true) amount) "80")] [result (get state "ran")]) (let [state {ran false} result ((fn [amount] [int? => int?] (put state "ran" true) "bad") 80)] [result (get state "ran")]) ((fn [callback] [[int? => int?] => int?] (callback 2)) (fn [value] (+ value 1))) ((fn [callback] [[int? => int?] => int?] (callback 2)) (fn [value] "bad")) [(schemas/valid? [int? => number?] (fn [value] [number? => int?] 1)) (schemas/valid? [number? => int?] (fn [value] [int? => number?] value)) (schemas/valid? [int? => int?] (fn [value] value)) (schemas/valid? [int? ... int? => number?] (fn [first ... values] [number? ... number? => int?] 1)) (schemas/valid? [number? ... number? => int?] (fn [first ... values] [int? ... int? => number?] 1))] (let [callback (fn [value] value)] ((fn [first second] [[int? => int?] [int? => int?] => boolean?] (comparisons/identical? first second)) callback callback)) (let [wrapped ((fn [callback] [fn? => [int? => int?]] callback) (fn [value] (+ value 1))) document (documents/from-value wrapped) definition (documents/value document) closed (documents/close document)] definition) (let [function (fn [value] [int? => int?] value) document (documents/from-value function) definition (documents/value document) bytes (encoding/tron/encode document) copy (encoding/tron/decode bytes) restored (documents/value copy) closed (documents/close document) copy-closed (documents/close copy)] [(= (str function) (str definition)) (= (str definition) (str restored))]) (let [original (fn [value] value) checked ((fn [callback] [fn? => [int? => int?]] callback) original)] [(comparisons/identical? original checked) (schemas/valid? [int? => int?] checked) (checked 2)])
(defn contracted [amount] [int? => int?] amount) (contracted 5) (defschema ContractInt int?) ((fn [callback] [[ContractInt => ContractInt] => ContractInt] (callback 2)) (fn [value] value)) (defschema ContractAnswer 42) (let [returned ((fn [value] [ContractAnswer => ContractAnswer] value) ContractAnswer) document (documents/from-value returned) definition (documents/value document) closed (documents/close document)] definition) ((fn [amount] [int? => int?] amount) 80) ((fn [amount] [int? => int?] amount) "80") ((fn [amount] [int? => int?] "bad") 80) ((fn [amount] [int? => int?] (/ amount 0)) 1) ((fn [amount] [int? => [join int? error?]] (/ amount 0)) 1) ((fn ([x] [int? => int?] x) ([x y] [int? int? => int?] (+ x y))) 1 2) ((fn [first ... more] [int? ... int? => int?] (reduce :+ first more)) 1 2 3) ((fn [{amount amount}] [map? => int?] amount) {amount 4}) (let [state <!ran> result ((fn [amount] [int? => int?] (put state "ran" true) amount) "80")] [result (get state "ran")]) (let [state <!ran> result ((fn [amount] [int? => int?] (put state "ran" true) "bad") 80)] [result (get state "ran")]) ((fn [callback] [[int? => int?] => int?] (callback 2)) (fn [value] (+ value 1))) ((fn [callback] [[int? => int?] => int?] (callback 2)) (fn [value] "bad")) [(schemas/valid? [int? => number?] (fn [value] [number? => int?] 1)) (schemas/valid? [number? => int?] (fn [value] [int? => number?] value)) (schemas/valid? [int? => int?] (fn [value] value)) (schemas/valid? [int? ... int? => number?] (fn [first ... values] [number? ... number? => int?] 1)) (schemas/valid? [number? ... number? => int?] (fn [first ... values] [int? ... int? => number?] 1))] (let [callback (fn [value] value)] ((fn [first second] [[int? => int?] [int? => int?] => boolean?] (comparisons/identical? first second)) callback callback)) (let [wrapped ((fn [callback] [fn? => [int? => int?]] callback) (fn [value] (+ value 1))) document (documents/from-value wrapped) definition (documents/value document) closed (documents/close document)] definition) (let [function (fn [value] [int? => int?] value) document (documents/from-value function) definition (documents/value document) bytes (encoding/tron/encode document) copy (encoding/tron/decode bytes) restored (documents/value copy) closed (documents/close document) copy-closed (documents/close copy)] [(= (str function) (str definition)) (= (str definition) (str restored))]) (let [original (fn [value] value) checked ((fn [callback] [fn? => [int? => int?]] callback) original)] [(comparisons/identical? original checked) (schemas/valid? [int? => int?] checked) (checked 2)])
contracted 5 ContractInt 2 ContractAnswer (defschema ContractAnswer 42) 80 #err <contract input> #err <contract result> #err <contract result> #err <division integer zero> 3 6 4 [#err <contract input> false] [#err <contract result> true] 3 #err <contract result> [false false false false false] true (fn [argument1] [int? => int?] (apply (fn [value] (+ value 1)) [argument1])) [true true] [false true 2]
(defn positive [value] (> value 0)) (defschema ContractInt int?) (defschema LocalContract (fn [value] [ContractInt => boolean?] (> value 0))) (defschema TaggedContract (fn [value] [positive => boolean?] (> value 0))) (defschema ParameterShadow (fn [ContractInt] [ContractInt => boolean?] (> ContractInt 0))) (let [positive (fn [value] (< value 0)) local-document (documents/from-value LocalContract) local-loaded (schemas/load (documents/value local-document)) tag-document (documents/from-value TaggedContract) tag-loaded (schemas/load (documents/value tag-document)) shadow-document (documents/from-value ParameterShadow) shadow-loaded (schemas/load (documents/value shadow-document))] [(schemas/valid? local-loaded 1) (schemas/valid? local-loaded -1) (schemas/valid? tag-loaded 1) (schemas/valid? tag-loaded -1) (schemas/valid? shadow-loaded 1) (schemas/valid? shadow-loaded -1)]) (let [positive (fn [value] (> value 0))] [((fn [value] [positive => int?] value) 1) ((fn [value] [positive => int?] value) -1)]) (let [wrapped ((fn [callback] [fn? => [int? => boolean?]] callback) :int?)] (schemas/valid? wrapped 1)) (defschema Factory (fn [] (fn [value] [positive => boolean?] (> value 0)))) (let [snapshot (documents/from-value Factory) restored (schemas/load (documents/value snapshot)) predicate (restored)] [(predicate 1) (predicate -1)])
(defn positive [value] (> value 0)) (defschema ContractInt int?) (defschema LocalContract (fn [value] [ContractInt => boolean?] (> value 0))) (defschema TaggedContract (fn [value] [positive => boolean?] (> value 0))) (defschema ParameterShadow (fn [ContractInt] [ContractInt => boolean?] (> ContractInt 0))) (let [positive (fn [value] (< value 0)) local-document (documents/from-value LocalContract) local-loaded (schemas/load (documents/value local-document)) tag-document (documents/from-value TaggedContract) tag-loaded (schemas/load (documents/value tag-document)) shadow-document (documents/from-value ParameterShadow) shadow-loaded (schemas/load (documents/value shadow-document))] [(schemas/valid? local-loaded 1) (schemas/valid? local-loaded -1) (schemas/valid? tag-loaded 1) (schemas/valid? tag-loaded -1) (schemas/valid? shadow-loaded 1) (schemas/valid? shadow-loaded -1)]) (let [positive (fn [value] (> value 0))] [((fn [value] [positive => int?] value) 1) ((fn [value] [positive => int?] value) -1)]) (let [wrapped ((fn [callback] [fn? => [int? => boolean?]] callback) :int?)] (schemas/valid? wrapped 1)) (defschema Factory (fn [] (fn [value] [positive => boolean?] (> value 0)))) (let [snapshot (documents/from-value Factory) restored (schemas/load (documents/value snapshot)) predicate (restored)] [(predicate 1) (predicate -1)])
positive ContractInt LocalContract TaggedContract ParameterShadow [true false true false true false] [1 #err <contract input>] true Factory [true #err <contract input>]
1.8.1.1.3. Inferred signatures
The compiler infers a signature from each function body. A declared contract adds runtime checks, but it does not prove the body. The compiler keeps the declaration source and the inferred facts separately.
Each inferred clause records these facts:
- Required and variadic arguments.
- Input kinds and nested field or list paths.
- Relations between inputs, results, callbacks, and returned functions.
- Mutation, clock, random, host, and unknown effects.
- Result aliases and mutation after-states.
- A possible success region and a guaranteed success region.
The possible region includes every input that can succeed.
The guaranteed region includes only inputs that the compiler proves will succeed.
The signature is exact when both regions are equal.
An unsupported operation or an analysis limit keeps the signature approximate.
Inference uses bounded iterative walks; a large body cannot consume the native call stack.
An indirect call without a supported rule also keeps the signature approximate.
Expressions that may raise, and results without known facts, cannot establish a guaranteed region.
It does not turn an unknown fact into a proven fact.
Builtin rules apply only when lexical lookup selects that builtin.
A parameter named + or get remains an arbitrary callable.
A local binding also hides an older input alias when its value is unknown.
A get call with a fallback does not prove that the input field exists or has the fallback's kind.
Reads in a function that may mutate collections do not prove constraints on original input fields.
A get path that may be empty does not require a collection root.
Map and list destructuring accept null, which binds missing members to null.
A failing conditional arm does not exclude inputs that can take a successful arm.
An ordinary call error in an unused binding also does not exclude an input when
the function can return a successful final value. A call error in an earlier body
expression stops the body, so it excludes the input.
An error argument is not part of an input region: a call with one returns it
before the body runs, unless the parameter's contract admits an error.
Relations remain part of the signature. For example, multiplication keeps the same-number-kind and integer-overflow relations. Division keeps the same-kind and nonzero-denominator relations. The compiler does not replace these relations with unrelated argument bounds.
(let [multiply (fn [left right] (* left right))
divide (fn [numerator denominator] (/ numerator denominator))]
[(multiply 3037000499 3037000499)
(error? (multiply 9223372036854775807 2))
(divide 9 3)
(error? (divide 9 0))])
The inferred multiplication signature requires compatible numeric or duration operands.
Numeric operands use matching kinds.
Its integer or duration result must fit in a signed 64-bit integer.
The inferred division signature also requires a nonzero denominator.
The boundary cases are in conformance/signatures/cases.dust.
Collection signatures keep paths, callback calls, aliases, and mutation after-states. A returned function remains linked to its inferred signature. Opaque callback behavior stays unknown because inference does not call the callback.
A body contains zero or more expressions, evaluated in order.
Its final expression supplies the return value.
An empty body returns null.
When an expression before the final expression has an #err value, the body
stops and returns that value. The later expressions do not run. An error inside
a list, a map or a call argument does not stop the body, and a reference
resolves only when it runs, so a function can still refer to a top-level local
that a later form defines.
((fn [] nope 1)) (let [check (fn [x] (/ 1 x) x)] [(check 2) (check 0)]) (map (fn [x] (/ 1 x) x) [1 0 2]) ((fn [amount] [int? => int?] (/ amount 0) amount) 1) ((fn [amount] [int? => int?] (+ amount 1) amount) 1)
#err <name unbound> [2 #err <division integer zero>] [1 #err <division integer zero> 2] #err <contract result> 1
1.8.1.1.4. Multiple arities
The single-arity form has one parameter list followed by its body expressions.
The clause form has one or more parenthesized arity clauses, each with a parameter list followed by its body expressions.
Both forms create one function.
The optional name and documentation or metadata apply to the whole function.
An arity clause parses as a #invoke tagged element containing its parameter list followed by its body forms.
fn interprets this structure as a clause, not a call.
A function can have distinct fixed arities and at most one variadic clause. With a variadic clause, no fixed arity may exceed its required parameter count. Duplicate fixed arities, multiple variadic clauses, and fixed arities above that count are errors when compiling the function.
A call selects an exact fixed-arity match first.
Otherwise, it selects the variadic clause if enough arguments were supplied for its required parameters.
If neither matches, the call produces an arity error.
Selection depends on argument count, not argument types or clause order.
Only the selected body is evaluated, with parameter bindings local to that call.
Ordinary calls and apply use the same selection rules.
Functions capture their lexical bindings, including bindings retained by escaping closures. Top-level functions can call each other through top-level locals. Tail-call guarantees remain to be defined.
1.8.1.1.5. Examples
(let [increment (fn increment [x] (+ 1 x))] [(increment 0) (increment 1) (increment 41)])
(let [increment (fn increment [x] (+ 1 x))] [(increment 0) (increment 1) (increment 41)])
1 2 42
(let [increment (fn increment "Return x plus one." [x] (+ 1 x))] [(increment 0) (increment 1) (increment 41)])
(let [increment (fn increment "Return x plus one." [x] (+ 1 x))] [(increment 0) (increment 1) (increment 41)])
1 2 42
(let [increment (fn increment {dust/doc "Return x plus one."} [x] (+ 1 x))] [(increment 0) (increment 1) (increment 41)])
(let [increment (fn increment {dust/doc "Return x plus one."} [x] (+ 1 x))] [(increment 0) (increment 1) (increment 41)])
1 2 42
(let [increment (fn {dust/doc "Return x plus one."} [x] (+ 1 x))] [(increment 0) (increment 1) (increment 41)])
(let [increment (fn {dust/doc "Return x plus one."} [x] (+ 1 x))] [(increment 0) (increment 1) (increment 41)])
1 2 42
(let [increment (fn [x] (+ 1 x))] (increment 4))
(let [increment (fn [x] (+ 1 x))] (increment 4))
(let [greet (fn greet "Greet one or more people." ([name greeting ... more] (strings/join [greeting ", " name (strings/join more "")] "")) ([] (greet "world")) ([name] (greet name "Hello")) ([name greeting] (strings/join [greeting ", " name "!"] "")))] [(greet) (greet "Ada") (greet "Ada" "Hi") (greet "Ada" "Hi" " and " "Bob" "!")])
(let [greet (fn greet "Greet one or more people." ([name greeting ... more] (strings/join [ greeting ", " name (strings/join more "")] "")) ([] (greet "world")) ([name] (greet name "Hello")) ([name greeting] (strings/join [ greeting ", " name "!"] "")))] [(greet) (greet "Ada") (greet "Ada" "Hi") (greet "Ada" "Hi" " and " "Bob" "!")])
"Hello, world!" "Hello, Ada!" "Hi, Ada!" "Hi, Ada and Bob!"
1.8.1.2. defn
Macro(defn name doc-or-meta? [params*] body*) → name
Defines a top-level function using the existing def and fn semantics.
The name is a declaration. Documentation, metadata, parameter rules, contracts,
multiple arities and variadic clauses follow fn. The result is the binding name, as
with def. Nested defn forms are errors.
(defn increment "Add one." [n]
(+ n 1))
(increment 41)
; 42
This is shorthand for (def increment (fn "Add one." [n] (+ n 1))).
As for fn, comments do not become its documentation.
Canonical formatting keeps short function headers together, including
defn name [params], fn [params] and def name (fn [params]. Comments
and long parameter lists can require separate lines. Formatting keeps each
comment on its value and is idempotent.
(defn increment "Add one." [n] (+ n 1)) (increment 41) (defn sum ([] 0) ([x] x) ([x y ... more] (reduce :+ (+ x y) more))) [(sum) (sum 2) (sum 2 3 4 5)] (def odd?) (defn even? [n] (if (= n 0) true (odd? (- n 1)))) (defn odd? [n] (if (= n 0) false (even? (- n 1)))) [(even? 10) (odd? 9)] (defn scale {dust/doc "Multiply by two." category "example"} [n] (* n 2)) (scale 21) (defn identity-with-doc "Constructor note\nParameter note" [x] x) (str identity-with-doc) (defn no-body []) (no-body) (= (str identity-with-doc) (str (fn "Constructor note\nParameter note" [x] x))) (let [doc (documents/from-value identity-with-doc) bytes (encoding/tron/encode doc) closed (documents/close doc) copy (encoding/tron/decode bytes) same (= bytes (encoding/tron/encode copy)) text (encoding/dust/encode copy) closed-copy (documents/close copy)] [same (strings/includes? text "Constructor note") (strings/includes? text "Parameter note")]) (defn muted-definition #mute "ignored documentation" [x] #mute (get missing "value") x) (muted-definition 42) (= (str muted-definition) (str (fn [x] x)))
(defn increment "Add one." [n] (+ n 1)) (increment 41) (defn sum ([] 0) ([x] x) ([x y ... more] (reduce :+ (+ x y) more))) [(sum) (sum 2) (sum 2 3 4 5)] (def odd?) (defn even? [n] (if (= n 0) true (odd? (- n 1)))) (defn odd? [n] (if (= n 0) false (even? (- n 1)))) [(even? 10) (odd? 9)] (defn scale {category "example" dust/doc "Multiply by two."} [n] (* n 2)) (scale 21) (defn identity-with-doc """ Constructor note Parameter note """ [x] x) (str identity-with-doc) (defn no-body []) (no-body) (= (str identity-with-doc) (str (fn """ Constructor note Parameter note """ [x] x))) (let [doc (documents/from-value identity-with-doc) bytes (encoding/tron/encode doc) closed (documents/close doc) copy (encoding/tron/decode bytes) same (= bytes (encoding/tron/encode copy)) text (encoding/dust/encode copy) closed-copy (documents/close copy)] [same (strings/includes? text "Constructor note") (strings/includes? text "Parameter note")]) (defn muted-definition \"ignored documentation" [x] \(get missing "value") x) (muted-definition 42) (= (str muted-definition) (str (fn [x] x)))
increment 42 sum [0 2 14] odd? even? odd? [true true] scale 42 identity-with-doc """" #invoke [ fn """ Constructor note Parameter note """ [#local x] #local x] """" no-body null true [true true true] muted-definition 42 true
{missing (defn) name (defn "wrong" [x] x) parameters (defn f) clauses (defn f 1) nested (let [] (defn f [x] x)) bad-parameter (defn f [42] 1) duplicate-arity (defn f ([x] x) ([y] y))}
{bad-parameter (defn f [42] 1) clauses (defn f 1) duplicate-arity (defn f ([x] x) ([y] y)) missing (defn) name (defn "wrong" [x] x) nested (let [] (defn f [x] x)) parameters (defn f)}
#cases [{output #err <invalid program> select "missing"} {output #err <invalid program> select "name"} {output #err <invalid program> select "parameters"} {output #err <invalid program> select "clauses"} {output #err <invalid program> select "nested"} {output #err <invalid program> select "bad-parameter"} {output #err <arity duplicate fixed fn> select "duplicate-arity"}]
(defn quoted [] '[1 2]) (quoted) (defn typo [] nope 1) (typo) (defn never-called [] missing 1) 2 (defn uses-later [] later) (def later 5) (uses-later) (defn rest-fails [x] (/ 10 x) (* x 2)) [(rest-fails 5) (rest-fails 0)]
(defn quoted [] ' [1 2]) (quoted) (defn typo [] nope 1) (typo) (defn never-called [] missing 1) 2 (defn uses-later [] later) (def later 5) (uses-later) (defn rest-fails [x] (/ 10 x) (* x 2)) [(rest-fails 5) (rest-fails 0)]
quoted #err {<name unbound> message "unbound name: '"} typo #err {<name unbound> message "unbound name: nope"} never-called 2 uses-later later 5 rest-fails [10 #err <division integer zero>]
1.8.1.3. do
Special Form(do expr*) → value
Evaluates the expr forms in order and returns the last result.
With no expressions, returns null.
When an expression before the last has an #err value, do returns that value
and does not evaluate the later expressions.
do introduces no bindings.
[(do) (do 7) (do 1 2 3) (if true (do "ignored" 42) (/ 1 0))]
(do) (do 7) (do 1 2 3) (if true (do "ignored" 42) (/ 1 0))
null 7 3 42
(do nope 1) (error? (do (nope 1) 1)) (do (/ 1 0) 1) (do #jsonptr ["a" (/ 1 0)] 1) (def r (do nope 1)) (error? r) [(do (/ 1 0) 1) 2] {value (do (/ 1 0) 1)} (count [(do (/ 1 0) 1)]) (do "ignored" (+ 1 2) 3)
(do nope 1) (error? (do (nope 1) 1)) (do (/ 1 0) 1) (do /a/,(/ 1 0) 1) (def r (do nope 1)) (error? r) [(do (/ 1 0) 1) 2] {value (do (/ 1 0) 1)} (count [(do (/ 1 0) 1)]) (do "ignored" (+ 1 2) 3)
#err <name unbound> true #err <division integer zero> #err <division integer zero> #err <name unbound> true [#err <division integer zero> 2] {value #err <division integer zero>} 1 3
1.8.2. Destructuring
Binding patterns select values and bind names in fn parameters, let bindings and for bindings.
Map keys select members. The corresponding pattern value supplies a binding name or a nested pattern, or the member is a tag.
List patterns select values by position. Maps and lists can nest inside either pattern.
Each binding input is evaluated once. Later let bindings and for collections can use the names already bound.
Selected collections retain their ordinary aliases. Destructuring does not deep-copy them.
(let [{name pilot spice amount} {name "Chani" spice 80}] [pilot amount])
(let [[pilot amount] ["Chani" 80]] [pilot amount])
(let [{name pilot cargo [amount unit]} {name "Chani" cargo [80 "kg"]}] [pilot amount unit])
((fn [[pilot amount]] [pilot (* amount 2)]) ["Chani" 80])
(for [[pilot amount] [["Chani" 80] ["Stilgar" 120]]] [pilot (* amount 2)])
Results, in the same order:
["Chani" 80]
["Chani" 80]
["Chani" 80 "kg"]
["Chani" 160]
[["Chani" 160] ["Stilgar" 240]]
1.8.2.1. Missing values and type errors
Missing map members and list items bind null. List patterns ignore extra items unless a capture collects them.
A null input supplies null throughout a pattern, including nested patterns.
A non-null input of the wrong kind reports #err <mismatch type>.
Stardust responses include the error's source position when available.
For example, the list type error below points to its [a b] pattern.
(let [[a b] [1]] [a b])
(let [[a b] [1 2 3]] [a b])
(let [[a b] null] [a b])
(let [{name pilot} null] pilot)
Results, in the same order:
[1 null]
[1 2]
[null null]
null
The following examples show wrong input kinds and missing required function arguments:
(let [[a b] 42] [a b])
(let [{name pilot} ["Chani"]] pilot)
((fn [head ... middle last] [head middle last]) 1)
Results, in the same order:
#err {<mismatch type> message "list destructuring requires a list, a packed math value, or null"}
#err {<mismatch type> message "map destructuring requires a map or null"}
#err {<mismatch arity> message "wrong number of arguments"}
1.8.2.2. Captures
A list pattern can contain one ... name capture. Nested list patterns can each contain their own capture.
The capture selects the values between the positional prefix and suffix.
A nonempty capture creates a new list container. Its elements retain their ordinary aliases.
An empty capture is null.
For short inputs, the prefix consumes available items first.
The suffix aligns with the end of the remaining input. Missing suffix positions bind null.
No input item is used twice.
(let [[a ... remaining] [1 2 3]] [a remaining])
(let [[head ... middle last] [1 2 3 4]] [head middle last])
(let [[a ... remaining] [1]] [a remaining])
(let [[head ... middle last] [1 2]] [head middle last])
(let [[head ... middle last] [1]] [head middle last])
(let [[head ... middle before-last last] [1 2]] [head middle before-last last])
Results, in the same order:
[1 [2 3]]
[1 [2 3] 4]
[1 null]
[1 null 2]
[1 null null]
[1 null null 2]
(let [[[a ... xs] [b ... ys]] [[1 2] [3 4]]] [a xs b ys])
Results, in the same order:
[1 [2] 3 [4]]
The target immediately after ... must be a name or _.
To destructure a captured list, bind its name first and destructure that value in a later binding.
1.8.2.3. Tags
In a map pattern, a tag binds a member to a local with the same name as its key.
The pattern <name spice> binds the same names and values as {name name spice spice}.
A tag group can stand alone as a pattern, or it can share a map pattern with ordinary members.
A tag is a member whose value is true, thus {name true} is the same pattern as <name>.
The tag <_> is a discard.
(let [<name spice> {name "Chani" spice 80}] [name spice])
(let [{<name> spice amount} {name "Chani" spice 80}] [name amount])
(let [{pilot <name rank>} {pilot {name "Chani" rank 3}}] [name rank])
((fn [<name spice>] [name (* spice 2)]) {name "Chani" spice 80})
(for [<name spice> [{name "Chani" spice 80} {name "Stilgar" spice 120}]] [name spice])
(let [<name missing> {name "Chani"}] [name missing])
(let [<name> null] name)
Results, in the same order:
["Chani" 80]
["Chani" 80]
["Chani" 3]
["Chani" 160]
[["Chani" 80] ["Stilgar" 120]]
["Chani" null]
null
A negated tag, such as <!name>, is a compilation error. A tag whose key is not a name is also a compilation error.
1.8.2.4. Variadic functions
Function argument lists also support trailing and middle captures. Unlike a list pattern, a function requires every positional argument before and after its capture. Missing required arguments report an arity error. Fixed arity clauses retain precedence over a variadic clause at equal arity.
((fn [head ... remaining] [head remaining]) 1 2 3)
((fn [head ... middle last] [head middle last]) 1 2 3 4)
Results, in the same order:
[1 [2 3]]
[1 [2 3] 4]
1.8.2.5. Discards and duplicate names
The discard pattern _ consumes a value without creating a binding. Repeated discards are allowed, including a ... _ capture.
A discard does not remove a position like the source mute form.
(let [[a _ c] [1 2 3]] [a c])
(let [[head ... _ last] [1 2 3 4]] [head last])
Results, in the same order:
[1 3]
[1 4]
A name can appear only once within one pattern or one function parameter list. This check includes nested patterns and capture targets. Repeated names are compilation errors. Malformed patterns also fail during compilation. These forms demonstrate duplicate names, repeated captures, invalid capture targets and invalid tags:
[
(let [[a a] [1 2]] a)
(let [{name x age x} {name "Chani" age 27}] x)
(fn [a a] a)
(fn [{name x} [x]] x)
(let [[a ... xs ... ys] []] a)
(let [[a ... [b c]] [1 2 3]] a)
(let [[a ... {x x}] [1]] a)
(let [[a ...] [1]] a)
(let [[... a a] [1]] a)
(fn [a ... xs ... ys] a)
(fn [a ... [b]] a)
(fn [a & rest] a)
(let [42 1] 2)
(let [<!a> {a 1}] a)
(let [{<a> b a} {a 1 b 2}] a)
(let [{"not a name" true} {}] 1)
(let [{... true} {}] 1)
(let [[a true] [1 2]] a)
(let [true 1] 2)
(fn [<a> a] a)
]
Sequential let rebinding and ordinary lexical shadowing remain available.
Bind the whole input normally before destructuring it when both are needed.
(let [a 1 a (+ a 1)] a)
(let [shipment {name "Chani" spice 80} {name pilot} shipment] [shipment pilot])
Results, in the same order:
2
[{name "Chani" spice 80} "Chani"]
1.8.2.6. Defaults and scope
Use ordinary expressions to supply defaults:
(let [{name pilot} {}] (if (= pilot null) "Unknown" pilot))
Results, in the same order:
"Unknown"
Dedicated default syntax, whole-value pattern shorthand, map-rest captures and constraint annotations are deferred.
New patterns apply to fn, let and for. Other binding forms keep their existing behavior.
1.8.3. let
Special Form(let [bindings*] exprs*)
Introduces local bindings and evaluates a body in their scope.
The binding list contains zero or more pairs of binding patterns and value expressions. A name in a pattern declares a local. It does not look up an existing value. A later binding can reuse a name from an earlier binding.
(let [price (* 5 2) quantity 3] (* price quantity))
(let [price (* 5 2) quantity 3] (* price quantity))
The value expressions are evaluated once and in order. Each binding becomes available to use in later expressions.
(let [price 10 quantity 3 total (* price quantity)] total)
(let [price 10 quantity 3 total (* price quantity)] total)
Bindings are in scope throughout the body of their let and within nested expressions.
Inner scopes can introduce the same names, shadowing the outer bindings.
(let [price 10] [(let [price (+ price 2)] price) price])
(let [price 10] [(let [price (+ price 2)] price) price])
12 10
A function closes over the bindings it references from its surrounding lexical scope. The resulting closure has those bindings available when the function is called, even after execution has left that scope (indefinite extent).
(let [name "outer" read-name (fn [] name)] (let [name "inner"] (read-name)))
(let [name "outer" read-name (fn [] name)] (let [name "inner"] (read-name)))
"outer"
(let [read-name (let [name "outer"] (fn [] name))] (read-name))
(let [read-name (let [name "outer"] (fn [] name))] (read-name))
"outer"
Body expressions inside the let are evaluated in order.
When a body expression before the last has an #err value, the let returns
that value and does not evaluate the later expressions. A binding whose value is
an error does not stop the let.
The let special form is an expression and evaluates to the value of the final expression in the body of the let, unless the body is empty in which case it evaluates to null.
(let [] nope 1) (let [x 1] nope x) (let [x (/ 1 0)] x 1) (let [x (/ 1 0)] 1) (let [x (/ 1 0)] (error? x)) (let [x (do (/ 1 0) 1)] [x 2])
#err <name unbound> #err <name unbound> #err <division integer zero> 1 true [#err <division integer zero> 2]
Additional forms that introduce bindings are: fn, for, and def.
1.8.4. def
Special Form(def name value? ...) → local reference
Defines top-level locals: bindings that the later top-level forms of the same file, or of the same REPL session, read as their names.
def is a top-level form. Inside any other form it is
#err <invalid program>. Each top-level form is evaluated on its own, so a
form sees the locals that earlier forms define.
The operands are name/value pairs, evaluated from left to right. Each binding
is visible to the values that follow it and to later top-level forms.
(def name value) returns the reference name.
(def name value other other-value) returns the reference other.
Zero operands and an incomplete pair are #err <arity mismatch>. A name
position that is not a name is #err <invalid program>.
A later def with the same name gives the same binding a new value. A
reference to a top-level local is read each time it runs, so a function made
earlier sees the new value, and a function can call a function that is
defined after it, once that function exists.
(def name) declares a local without a value, and leaves the value of a
local that has one. A declared local is #err <name unbound> until a later
def gives it a value. A declaration lets two top-level functions call
each other, as in Clojure's declare.
(def odd?) (def even? (fn [n] (if (= n 0) true (odd? (- n 1))))) (def odd? (fn [n] (if (= n 0) false (even? (- n 1))))) (even? 10)
odd? even? odd? true
When a value is an #err value, def returns that value, declares the name
without a value, and does not evaluate later pairs.
A let, fn, or for binding with the same name shadows a top-level local.
A constant reference never reaches a top-level local. The name of a library
entry is #err <conflict name>, because a direct call of that name always
calls the library entry. The name of a schema marker, such as meet or is,
is also #err <conflict name>, because a bare marker name always means the
marker. This holds for a saved namespace and a REPL session too: a namespace
that defines such a name does not load, and in a REPL the def returns the
error and the name keeps its builtin meaning.
(def int? (fn [v] true))
#err {<conflict name> message "int? is a builtin constant"}
1.8.5. import
(import {alias path ...}) → null
Declares namespace dependencies under explicit aliases. The argument is one map. Each member imports one namespace. A map key is an unqualified alias.
A member value is one of:
- A JSON Pointer.
(import {spice /arrakis/spice})imports the saved namespacearrakis/spiceasspice. - A string namespace key.
(import {spice "arrakis/spice"})is the same import. true.(import {spice true})imports/spiceasspice.
A true member uses the map key as the namespace path and the last path segment
as its alias. A tag-only map is shorthand for such members.
(import <arrakis/spice guild/shipping>) imports arrakis/spice as spice
and guild/shipping as shipping.
(import {shipping /guild/shipping tax "imperial/tax"})
A pointer's segments decode and join with /. The root pointer, empty
segments, and segments that contain / are errors. A string value is a
namespace key, so a leading / is invalid. Boolean false and other values
are errors.
When formatting program source, stardust fmt uses the short form if an alias
is the last path segment.
(import {bar /foo/bar}) and (import {bar "foo/bar"}) format as
(import <foo/bar>). An explicit alias that is not the last segment stays a
map member, as in (import {label /a/b/c}). Data encoding and conversion keep
the map keys and values.
An import belongs at the top level, outside functions and other expressions.
It does not return a namespace object. The two-operand (import path alias)
form is invalid. Choose an alias that does not conflict with a local or a
selected builtin namespace, such as math or strings. A stored path may
still use those names; choose a different alias when importing it.
Save this source as arrakis/spice:
; Spice production calculations. (def reserve-percentage 10) (defn usable-spice "Return the harvest after the imperial reserve." [harvest] (/ (* harvest (- 100 reserve-percentage)) 100)) (defn harvester-output [crews yield] (* crews yield)) (export usable-spice harvester-output)
; Spice production calculations. (def reserve-percentage 10) (defn usable-spice "Return the harvest after the imperial reserve." [harvest] (/ (* harvest (- 100 reserve-percentage)) 100)) (defn harvester-output [crews yield] (* crews yield)) (export usable-spice harvester-output)
[ ; Spice production calculations. #invoke [def #local reserve-percentage 10] #invoke [ defn #local usable-spice Return the harvest after the imperial reserve. [#local harvest] #invoke [/ #invoke [* #local harvest #invoke [- 100 #local reserve-percentage]] 100]] #invoke [defn #local harvester-output [#local crews #local yield] #invoke [* #local crews #local yield]] #invoke [export #local usable-spice #local harvester-output]]
A second namespace can import its exports:
(import <arrakis/spice>) (defn shipment [harvest] (spice/usable-spice harvest)) (export shipment)
(import <arrakis/spice>) (defn shipment [harvest] (spice/usable-spice harvest)) (export shipment)
[#invoke [import <arrakis/spice>] #invoke [defn #local shipment [#local harvest] #invoke [spice/usable-spice #local harvest]] #invoke [export #local shipment]]
The call (shipping/shipment 1000) returns 900.0. Only explicitly exported
names are public; reserve-percentage remains private. Read an exported
constant with :alias/name, and invoke an exported function with
(alias/name arguments).
An import path can name a local file (Files). Other paths name saved namespaces. Use namespace commands to save a namespace.
Each namespace initializes its top-level definitions before its exports become available. Initializers may perform pure calculations. Host effects, reading the clock and executing a database query are refused during initialization. A function containing a query is valid: its query runs when called, rather than when its definition is loaded. Import cycles and missing exports are errors.
Unchanged imports keep their current mutable values. A new initializer reads
those values; loading a consumer does not reset its dependencies. For example,
if depot/lots started as [100] and an earlier call appended 200, a new
consumer's (def lots :depot/lots) shares [100 200] and
(count :depot/lots) returns 2. Later mutations through either reference
remain visible through the other.
A valid save checks the proposed source in a fresh context. Loading that version in an existing session may still fail because an imported value was mutated. A failed load keeps the previous aliases and instances intact. Calls requiring the changed version report the initialization error; they do not silently run the old definition. Repair the source or reset the session to recover.
An ordinary database invocation uses one consistent version of its code, imports and data. Later invocations observe valid saved changes without reloading an alias. This also applies to an exported function retained in a local for a later call. A running call keeps its starting version. Saving a namespace does not change an invocation already in progress.
1.8.5.1. Files
An import path can name a local file. The runtime looks for PATH.dust in the
directory of the importing file. Code without a file, such as a REPL entry,
uses the working directory. In app/main.dust, (import {s "lib/shapes"})
names app/lib/shapes.dust. When that file imports "util", the path names
app/lib/util.dust. A path to a file can contain . and .. segments, as in
(import {check "../lib/check"}). A saved namespace path cannot.
An import reads only files under an import root. The root of stardust eval,
run and a script is the directory of the program's file. The root of the
REPL and of an nREPL server is the working directory. The imports setting of
the configuration adds roots (Configuration
files). The runtime resolves symlinks and .. before it compares a file
with the roots. A file that exists outside every root is refused with
#err <denied fs>. Its message names the import path, the resolved file and
the roots:
#err {<denied fs>
column 1
line 1
message "import ../lib/check resolves to /home/ada/lib/check.dust, outside the import roots: /home/ada/tools"}
The .. of (import {check "../lib/check"}) in tools/main.dust thus needs
a configuration whose roots include the parent of tools/.
When the file exists and the database has no saved namespace of that path, the import uses the file. When only the saved namespace exists, the import uses it. When both exist, the import uses the newer one. The file is newer when its modification time is the same as or later than the save time of the namespace. The rule applies to each import, also to the imports in an imported file. Without a database, there are no saved namespaces, and an import of a path without a file fails.
The comparison uses the clock of the filesystem and the clock of the database. A file with a time in the future stays newer until a later save. A saved namespace without a recorded save time is older than all files. When the runtime cannot read the time of a file, it uses the file, and the read of the file then fails.
A file is one namespace, whatever path names it. Two importers in different
directories that name the same file share one namespace. The namespace of a
file does not replace the saved namespace of the same path for other code. A
saved namespace that imports that path continues to use the saved namespace.
The runtime does not save a file. Use
stardust namespace save to save one.
Each evaluation of an import form reads the files again. This includes the
files that the form names, the files that they import, and each file that the
session loaded before. A new or changed file initializes again, and so does
each file that imports it. An unchanged file keeps its values. A file
initializes as a saved namespace does, so its initializers have no host
effects. A library reads cli/args or scripts/path in a function, not in a
def. The runtime reads an imported file as source, as stardust eval reads
its file. Inside the roots, this needs no io grant.
The alias rules do not change. (import <lib/math>) gives the alias math,
which is a builtin namespace, and fails. Use (import {m "lib/math"}).
An import cycle through files is #err <cycle import>. A file that exists but
cannot be read is #err <fs io>. An error in an imported file gives the
file and the line and column in it. Parse errors, compile errors and
failed initializers are examples.
#err {<cycle import>
column 1
file "/home/ada/app/lib/a.dust"
line 1
message "import cycle: /home/ada/app/lib/a.dust -> /home/ada/app/lib/b.dust -> /home/ada/app/lib/a.dust"}
1.8.6. export
Special Form(export name*) → list
Names the top-level locals that a library file provides. When code
imports the file, as (import {s "lib/shapes"}) does, each named local becomes
the constant :s/name. Its value is the value of the local after the file
runs. The other locals of the file stay private. The file's functions read
them, not the locals of the code that calls them.
; lib/shapes.dust
(def area (fn [w h] (* w h)))
(def square (fn [s] (area s s)))
(def unit 1)
(export square unit)
After (import {s "lib/shapes"}), (s/square 3) returns 9 and :s/unit
returns 1. :s/area is #err <name unbound>.
export is a top-level form, and a file can have more than one. A file
with no export provides nothing. An import fails when export names a local
that does not exist or has no value, or when a top-level form returns an
#err value. Evaluated directly, export returns the list of the named
references and has no other effect.
1.8.7. Control Flow
1.8.7.1. and
Special Form(and forms*) → value
Evaluates forms once each, from left to right, and returns the first falsey
value without evaluating later forms; an #err value is falsey, so and returns it. If every form is truthy, returns the
last value. With no forms, returns true.
Only false, null, and #err values are falsey; zero and the empty string are truthy.
The result is an operand value rather than a conversion to boolean.
(and) (and 0 "" "x") (and false (/ 1 0)) (and null (/ 1 0)) (let [m {n 0}] [(and (do (patch m {n (+ (get m "n") 1)}) "x") "y") (get m "n")])
true "x" false null ["y" 1]
1.8.7.2. or
Special Form(or forms*) → value
Evaluates forms once each, from left to right, and returns the first truthy
value without evaluating later forms. If every form is falsey, returns the
last value. With no forms, returns null.
Only false, null, and #err values are falsey; zero and the empty string are truthy.
The result is an operand value rather than a conversion to boolean.
(or) (or null false "x") (or 0 (/ 1 0)) (or "" (/ 1 0)) (let [m {n 0}] [(or (do (patch m {n (+ (get m "n") 1)}) null) "y") (get m "n")])
null "x" 0 "" ["y" 1]
1.8.7.3. if
Special Form(if test then)
(if test then else)
Selects a branch according to the truthiness of a test.
The test is evaluated once. The resulting value's truthiness is used to choose a branch.
A truthy result selects then, and a falsey result selects else.
Only the selected branch is evaluated, and its value becomes the value of the whole if expression.
If else is omitted, a falsey test evaluates to null.
Each branch contains one expression.
if is a special form because it controls which arguments are evaluated, rather than evaluating all of them before making the choice.
1.8.7.4. when
Macro(when test body...)
Runs a body when its test is truthy.
It evaluates the test once, then evaluates the body expressions in order and returns the last result.
If the test is falsey, the body is not evaluated and the result is null.
An empty body also returns null.
Unlike if, when has no alternative branch and can contain several body expressions.
1.8.7.5. when-not
Macro(when-not test body...)
Runs a body when its test is falsey.
Like when, it evaluates the test once, evaluates the selected body in order, and returns the last result.
A truthy test skips the body and returns null, and an empty body returns null regardless of the test's value.
1.8.7.6. cond
Special Form(cond test result ...)
Chooses among pairs of tests and result expressions.
It evaluates tests once each, in order, until one is truthy.
It then evaluates and returns that test's result expression, without evaluating any later tests or results.
A selected result of false or null is still the result, not a reason to continue to another pair.
If no test is truthy, cond returns null.
With no pairs, it also returns null.
Every test must have a result expression, so an unmatched final test is an error before evaluation.
cond is a special form, not a macro: a macro would nest one if for each pair, and a cond of tens of thousands of pairs would then fill the LuaJIT stack (see Nesting depth).
A final pair with true as its test supplies a default result.
This is an ordinary truthy test, not a separate default-branch syntax.
1.8.7.7. for
Special Form(for [name collection ...] body)
Evaluates a body for each combination of collection values and returns a list of the results.
Evaluation is eager: all iterations complete before for returns.
Each collection value is bound through a name or binding pattern.
The bindings are local to the for.
Multiple binding pairs introduce nested iteration, with the leftmost binding as the outermost loop. Lists are traversed in order. The body evaluates once per combination, contributing one value to the result list.
(for [x [1 2] y [10 20]] (+ x y))
(for [x [1 2] y [10 20]] (+ x y))
11 21 12 22
Each collection expression is evaluated once each time its loop is entered. Later collection expressions can reference earlier bindings. An empty collection contributes no combinations.
The body contains one expression. Use (do ...) to evaluate several expressions
and collect the final value; callers may ignore the result list for effects.
A let in the body can introduce additional bindings for calculated values.
If the body produces a list, that list is one element of the result.
{ case0 (let [values []] [(for [x [1 2] y [10 20]] (do (lists/append values (+ x y)) (+ x y))) values]) case1 (let [values []] (for [x [1 2 3]] (do (lists/append values x) (lists/append values (- x)))) values) case2 (let [values []] (for [x [] y (lists/append values 1)] (lists/append values 2)) values) case3 (let [values []] (for [x [1 2] y (lists/range x)] (lists/append values [x y])) values) case4 (for [] 42) case5 (for [x [1 2]] (do)) case6 (for [x 42] x) case7 (for [x [1]] (do (for [x [2 3]] x) x)) case8 (let [x 10] (for [x [1 2]] x) x) case9 (let [values [] f (fn [xs] (for [x xs] (lists/append values x)))] (f [1 2]) (f [3]) values) case10 (for [x [1]] (tests/assert false "for body executes")) }
{case0 (let [values []] [(for [x [1 2] y [10 20]] (do (lists/append values (+ x y)) (+ x y))) values]) case1 (let [values []] (for [x [1 2 3]] (do (lists/append values x) (lists/append values (- x)))) values) case10 (for [x [1]] (tests/assert false "for body executes")) case2 (let [values []] (for [x [] y (lists/append values 1)] (lists/append values 2)) values) case3 (let [values []] (for [x [1 2] y (lists/range x)] (lists/append values [x y])) values) case4 (for [] 42) case5 (for [x [1 2]] (do)) case6 (for [x 42] x) case7 (for [x [1]] (do (for [x [2 3]] x) x)) case8 (let [x 10] (for [x [1 2]] x) x) case9 (let [values [] f (fn [xs] (for [x xs] (lists/append values x)))] (f [1 2]) (f [3]) values)}
#cases [{output [[11 21 12 22] [11 21 12 22]] select "case0"} {output [1 -1 2 -2 3 -3] select "case1"} {output [] select "case2"} {output [[1 0] [2 0] [2 1]] select "case3"} {output [42] select "case4"} {output [null null] select "case5"} {output #err <mismatch type> select "case6"} {output [1] select "case7"} {output 10 select "case8"} {output [1 2 3] select "case9"} {output #err <assertion test> select "case10"}]
1.8.8. Quotation
1.8.8.1. quote
Special Form#quote form
Returns the enclosed form as data without evaluating it. References, invocations, and collection contents retain their form representation. See Quotation forms for prefix syntax and encoding.
1.8.8.2. quasiquote
Macro#quasiquote form
Constructs data while evaluating unquotes at the matching nesting depth. List-element splices insert the elements of their evaluated list. See Quotation forms for prefix syntax and encoding.
1.8.8.3. unquote
Macro#unquote form
Evaluates the enclosed form within its matching quasiquote and substitutes the resulting value. Outside quasiquote, this is an error. See Quotation forms for prefix syntax and encoding.
1.8.8.4. unquote-splicing
Macro#unquote-splicing form
Evaluates the enclosed list within its matching quasiquote and inserts its elements into the surrounding list. A non-list result or a splice outside a list-element position is an error. See Quotation forms for prefix syntax and encoding.
1.8.9. Macros
A macro is a DUST function that the compiler runs before evaluation. Its parameters bind the unevaluated argument forms as data, and its result is the form that takes the place of the call. The compiler then lowers that form as if the program had contained it. Macros are procedural, as in Clojure, Janet and Fennel: the body is ordinary DUST code, and quasiquote is the usual way to build the result.
(defmacro unless [test ... body]
~(if ,test null (do ,@body)))
(unless (= 1 2) "ran")
; "ran"
(macroexpand-1 `(unless a b c))
; (if a null (do b c))
The core macros when, when-not and defn
are defined this way. The evaluator lowers the special forms if, cond,
let, fn, do, and, or, def, export and for directly.
1.8.9.1. defmacro
Special Form(defmacro name doc-or-meta? [params*] body*) → name
Defines a macro for the later forms of the file or session.
defmacro is a special form: it adds a macro instead of binding a
value. The name is a declaration, and the result is the name, as with
def and defn. The documentation slot, metadata, parameter
rules, variadic ... parameters and arity checks follow fn.
Each parameter receives one argument form, and the body returns a form.
Forms that the body does not include in its result are never evaluated.
A rest parameter with no argument forms is null, which a splice inserts
as nothing, so (do ,@body) with an empty body is (do).
(defmacro unless [test ... body] ~(if ,test null (do ,@body))) (unless (= 1 2) "ran") (unless (= 1 1) "skipped") (unless false 1 2 3)
unless "ran" null 3
(defmacro first-form "Returns its first argument form." [x ... more] x) (defmacro second-form {dust/doc "Returns its second argument form." category "example"} [x y] y) (first-form 1 (/ 1 0)) (second-form (/ 1 0) 2)
(defmacro first-form "Returns its first argument form." [x ... more] x) (defmacro second-form {category "example" dust/doc "Returns its second argument form."} [x y] y) (first-form 1 (/ 1 0)) (second-form (/ 1 0) 2)
first-form second-form 1 2
(defmacro unless [test ... body] ~(if ,test null (do ,@body))) (unless true) (unless false)
unless null null
defmacro is a top-level form. A defmacro inside another form is
#err <invalid program>, as a nested defn is. A missing name or parameter
list is the same error.
{missing (defmacro) name (defmacro "wrong" [x] x) parameters (defmacro m) nested-do (do (defmacro m [] 1)) nested-let (let [] (defmacro m [] 1))}
{missing (defmacro) name (defmacro "wrong" [x] x) nested-do (do (defmacro m [] 1)) nested-let (let [] (defmacro m [] 1)) parameters (defmacro m)}
#cases [{output #err <invalid program> select "missing"} {output #err <invalid program> select "name"} {output #err <invalid program> select "parameters"} {output #err <invalid program> select "nested-do"} {output #err <invalid program> select "nested-let"}]
1.8.9.1.1. Scope
A macro applies to the top-level forms that follow its definition in the same
file, saved namespace or REPL session. A form before the definition calls an ordinary function
of that name, or fails when there is none. The body of a macro can call
defn helpers defined earlier in the file, because the body runs as ordinary
code.
(wrapped 1) (defn wrap [form] ~(do ,form)) (defmacro wrapped [x] (wrap x)) (wrapped 5)
#err <name unbound> wrap wrapped 5
export can name a macro. Code that imports the file calls the
macro as alias/name, as it calls a function of the library. After
(import {c "lib/control"}), (c/unless ( x 0) (/ 1 x))= expands with the
imported unless. This applies to files and to saved namespaces. When the
imported namespace changes, the code that imports it expands the new version.
The forms of a namespace also expand its own macros and the macros of its
imports. Evaluated directly, export returns the list of the named references
and has no other effect.
A save checks the names in the forms that the macros expand to, as it checks the names in the source. A name that a macro adds is reported at the macro call.
(defmacro unless [test ... body] ~(if ,test null (do ,@body))) (export unless)
unless [unless]
1.8.9.1.2. Not a value
A macro is not a value. Only an invocation whose head names the macro
expands. A reference to the name has no binding: :ns/name and a bare name
in an argument position are #err <name unbound>. Passing the name to
apply, or reaching the macro through a computed callee, is
#err <expected function>.
(defmacro unless [test ... body] ~(if ,test null (do ,@body))) :unless [unless] (apply unless [true 1]) ((functions/identity unless) true 1)
unless #err {<name unbound> message "unbound name: unless"} [#err {<name unbound> message "unbound name: unless"}] #err {<name unbound> message "unbound name: unless"} #err {<expected function> message "expected a function value"}
A let, fn or for binding of the same name shadows the macro inside its
scope. Inside the scope, the name calls the bound function. Outside the
scope, the macro applies again.
(defmacro twice [x] ~[,x ,x]) (twice 3) (let [twice (fn [x] (* 2 x))] (twice 3)) ((fn [twice] (twice 3)) (fn [x] (+ x 1))) (for [twice [(fn [x] (- x 1))]] (twice 3)) (twice 3)
twice [3 3] 6 4 [2] [3 3]
A defmacro whose name is a special form, a library entry or a schema
marker is #err <conflict name>, as a def of that name is.
1.8.9.1.3. Expansion
The compiler expands each invocation in two steps. First, while the head names a macro, it runs the macro and replaces the invocation with the result. A macro can expand to another macro call, and expansion continues until the head is not a macro. Then it expands the subforms of the result, and lowers the result.
(defmacro unless [test ... body] ~(if ,test null (do ,@body))) (defmacro guard [test ... body] ~(unless (not ,test) ,@body)) (guard true "ok") (guard false "ok") (macroexpand-1 `(guard t a)) (macroexpand `(guard t a))
unless guard "ok" null (unless (not t) a) (if (not t) null (do a))
(defmacro unless [test ... body] ~(if ,test null (do ,@body))) (+ 1 (unless false 2)) [(unless false 1) {a (unless false 2)}] (let [x (unless false 3)] (if (unless false true) x "no"))
unless 3 [1 {a 2}] 3
Expansion does not enter a quote payload or a quoted builtin form such
as a query or mutation body. A macro call inside them stays data. Inside a
quasiquote, the unquoted parts are evaluated, so a macro call in an
unquote or a splice expands. The quoted parts stay data.
(defmacro unless [test ... body] ~(if ,test null (do ,@body))) `(unless a b) `[(unless a b)]
unless (unless a b) [(unless a b)]
(defmacro unless [test ... body] ~(if ,test null (do ,@body))) ~(unless a ,(unless false 1)) ~[,@(unless false [1 2]) (unless x y)]
unless (unless a 1) [1 2 (unless x y)]
1.8.9.1.4. Hygiene
A macro of a saved namespace calls the namespace's own definitions from its
templates. In a quasiquote template of such a macro, a bare name that the
expansion calls or evaluates refers to the namespace's top-level definition
of that name, private or exported, when the namespace defines it and the
template does not bind it. The expansion holds a private reference to the
definition, written #private ["lib/helpers" helper] with the namespace's
path. A binding at the call site does not capture it, and the definition
stays private.
;; saved as lib/helpers
(defn helper [x] (* x 10))
(defmacro tenfold [x] ~(helper ,x))
(defmacro helper-name [] ~`helper)
(export tenfold helper-name)
;; caller
(import {helpers /lib/helpers})
(helpers/tenfold 3) ; 30
(let [helper (fn [n] n)] (helpers/tenfold 3)) ; 30
(helpers/helper 4) ; #err <name unbound>
(helpers/helper-name) ; helper
The reference resolves in the version of the namespace that the call runs
with, as an imported name does, and also while the namespace initializes
its own later forms. A name stays as written, and resolves at the call site,
when it is in an unquote or a splice, quoted, a literal map key, a name that
the template's let, for, fn, defn or schemas/match binds or that
its def, defn or defmacro declares, inside a quoted builtin form such
as a query, at another depth of a nested quasiquote, or a name that the
namespace does not define, such as a builtin. Macros of the namespace are
not definitions: a template that names one expands it at the call site.
Only the runtime makes a private reference. A #private tag that is typed,
pasted, read from a host document or from JSON is data. As a call's head it
is #err <name unbound> with the name it spells:
(#private ["lib/helpers" helper] 3) is #err <name unbound> with the
message unbound name: lib/helpers/helper. A function's printed form shows
the tag, and a function rebuilt from that text has no references. A
function that the runtime holds or stores keeps them.
Other names in a macro's result resolve at the call site: a macro of a
session or a REPL file, and a name that a namespace macro's template does
not resolve, can capture a name from the call site. The macro author
prevents this with new names.
gensym returns a new name, and a bare name ending in # inside a
quasiquote is an automatic gensym. Each different name# in one quasiquote
form is one new name. tmp# written twice in the same quasiquote is the
same name, and tmp# in another quasiquote is a different name.
(defmacro swap-order [a b]
~(let [tmp# ,a] [,b tmp#]))
(let [tmp 5] (swap-order tmp 2))
; [2 5]
New names are spelled prefix__N: tmp# becomes tmp__1, and (gensym)
becomes G__1. The counter starts at 1 when the expansion of a top-level
form starts. Every gensym and name# inside that expansion continues the
count in order of first use. A macroexpand call starts its own count.
Thus the same source expands to the same text.
(defmacro swap-order [a b] ~(let [tmp# ,a] [,b tmp#])) (defmacro two-forms [] [~tmp# ~tmp#]) (defmacro pair-names [] ~(let [a# 1 b# 2] [a# b#])) (let [tmp 5] (swap-order tmp 2)) (macroexpand-1 `(swap-order tmp 2)) (macroexpand-1 `(two-forms)) (macroexpand-1 `(pair-names))
swap-order two-forms pair-names [2 5] (let [tmp__1 tmp] [2 tmp__1]) [tmp__1 tmp__2] (let [a__1 1 b__2 2] [a__1 b__2])
(defmacro swap-order [a b] ~(let [tmp# ,a] [,b tmp#])) (= (macroexpand `(swap-order x 2)) (macroexpand `(swap-order x 2))) (str (macroexpand `(swap-order x 2))) (let [text (str (fn [] [(swap-order a 1) (swap-order b 2)]))] [(strings/includes? text "tmp__1") (strings/includes? text "tmp__2") (strings/includes? text "tmp__3")])
(defmacro swap-order [a b] ~(let [tmp# ,a] [,b tmp#])) (= (macroexpand `(swap-order x 2)) (macroexpand `(swap-order x 2))) (str (macroexpand `(swap-order x 2))) (let [text (str (fn [] [(swap-order a 1) (swap-order b 2)]))] [(strings/includes? text "tmp__1") (strings/includes? text "tmp__2") (strings/includes? text "tmp__3")])
swap-order true "#invoke [let [#local tmp__1 #local x] [2 #local tmp__1]]" [true true false]
1.8.9.1.5. Sandbox
A macro body runs with no capabilities. Calls to fs/, crypto/random/,
time/now, random/ and database operations fail inside a macro as they do in an
evaluation without the matching capability. The failure becomes an
#err <invalid program> at the call site. Expansion shares the memory and
CPU limits of the evaluation, and the expansion depth of one form is limited.
A macro that expands to itself without end is #err <macro expansion limit>.
A head chain permits 1000 expansions. Introspection inside a macro permits
four simultaneous macro calls; deeper re-entry returns the same error before
the native or Lua stack is exhausted.
(defmacro at-build [] (time/now)) (at-build)
#err {<invalid program> column 1 line 2}
1.8.9.1.6. Errors
A macro reports a bad call by returning an #err value. The compiler turns
it into #err <invalid program> positioned at the call site. Its message is
macro NAME: MESSAGE, with the macro's name and the message of the returned
error. A result that is not a form, such as a function, is the same error.
(defmacro checked [x] (if (int? x) ~(+ ,x 1) #err "checked needs an integer literal")) (checked "a")
#err {<invalid program> column 1 line 2 message "macro checked: checked needs an integer literal"}
1.8.9.1.7. Canonical functions
A function's canonical form is its expanded fn source. Printing, hashing
and storing a closure use the expansion. Two functions written with and
without a macro have the same text and the same hash. A stored function
recompiles from its expansion, without the macros that produced it.
(defmacro unless [test ... body] ~(if ,test null (do ,@body))) (def safe-inverse (fn [x] (unless (= x 0) (/ 1 x)))) (str safe-inverse) (= (str safe-inverse) (str (fn [x] (if (= x 0) null (do (/ 1 x)))))) (= (hashes/digest "sha256" safe-inverse) (hashes/digest "sha256" (fn [x] (if (= x 0) null (do (/ 1 x)))))) [(safe-inverse 0) (safe-inverse 4)]
(defmacro unless [test ... body] ~(if ,test null (do ,@body))) (def safe-inverse (fn [x] (unless (= x 0) (/ 1 x)))) (str safe-inverse) (= (str safe-inverse) (str (fn [x] (if (= x 0) null (do (/ 1 x)))))) (= (hashes/digest "sha256" safe-inverse) (hashes/digest "sha256" (fn [x] (if (= x 0) null (do (/ 1 x)))))) [(safe-inverse 0) (safe-inverse 4)]
unless safe-inverse "#invoke [fn [#local x] #invoke [if #invoke [= #local x 0] null #invoke [do #invoke [/ 1 #local x]]]]" true true [null 0.25]
1.8.9.2. gensym
Function(gensym) → name
(gensym prefix) → name
Returns a new name that no source form contains.
The name is prefix__N, where N counts the new names of the current
expansion from 1. Without a prefix, the prefix is G. Two calls in one
expansion return different names. See Hygiene for the name#
quasiquote shorthand, which calls gensym once per quasiquote form.
(defmacro two-names [] [(gensym) (gensym)]) (defmacro prefixed [] ~(let [,(gensym "tmp") 1] 2)) (macroexpand-1 `(two-names)) (= (gensym) (gensym)) (macroexpand-1 `(prefixed))
two-names prefixed [G__1 G__2] false (let [tmp__1 1] 2)
1.8.9.3. macroexpand-1
Function(macroexpand-1 form) → form
Expands one macro call and returns the resulting form.
When the head of form names a macro, the result is the form the macro
returns, with the subforms unexpanded. Otherwise the result is form
unchanged, including forms that are not invocations. The argument is a form
value, usually built with quote.
(defmacro unless [test ... body] ~(if ,test null (do ,@body))) (defmacro guard [test ... body] ~(unless (not ,test) ,@body)) (macroexpand-1 `(unless a b c)) (macroexpand-1 `(guard a b)) (macroexpand `(guard a b)) (macroexpand-1 `(+ 1 2)) (macroexpand `(f (unless a b))) (macroexpand-1 `x) (macroexpand 42)
unless guard (if a null (do b c)) (unless (not a) b) (if (not a) null (do b)) (+ 1 2) (f (unless a b)) x 42
1.8.9.4. macroexpand
Function(macroexpand form) → form
Applies macroexpand-1 to the head again and again until it is not a macro call.
The subforms of the result are not expanded, because the compiler expands them in a later step. A form whose head is not a macro returns unchanged. Each call starts a new gensym count, so the same form expands to the same text.
02 Schemas and contracts
A schema describes which values an operation accepts. A schema is a plain
value, a function, any or never, or an operator form, and each form has
one meaning wherever it is written. Compound schemas use meet to require
every constraint and join to require at least one; Schema algebra explains
their construction and simplification. Schemas are ordinary DUST values.
Checking one does not convert a value, add defaults, or attach a permanent
type to it.
Use this chapter for schema construction, validation, defaults, generation, and saved definitions. Function contracts connect schemas to callable boundaries and generated tests. Ordinary type predicates and conversions remain in Types.
2.1. Choose an operation
| Task | Operation |
|---|---|
| Test whether a value matches | schemas/valid? |
| Select a branch and capture matching values | schemas/match |
| Construct a value from determined fields and defaults | schemas/materialize |
| Generate a value from a schema and a seeded generator | schemas/fakerize |
| Test a function with generated cases and replay failures | schemas/check |
| Explain a mismatch with schema and candidate paths | schemas/explain |
| Reconstruct an owned saved definition | schemas/load |
| Intersect or unite schema constraints | schemas/meet, schemas/join |
| Simplify a schema value | schemas/simplify |
Start with the required fields of a value. A shape such as
{pilot string? spice int?} requires those fields and permits extra fields.
Write [optional string?] as the value of a field that can be absent, and
[maybe string?] for a value that can be null. Use [... int?] for a list
of integers and [map-of int?] for a map with integer values. A scalar
schema, including a string, matches that literal value.
any accepts every value and never accepts none. map? and {} accept
every map. A function is a schema: int?, positive? and chars/letter?
accept the values for which they return true. See Custom predicates to
define your own checks. Unknown names, impure predicates, and malformed
descriptions are errors, not successful checks. schemas/valid? below gives the
full rules.
2.2. Named definitions
The top-level form (defschema name description) binds a named schema. The body
can refer to its own name for recursive child values. A named definition keeps
the predicates it selected and its namespace revision. Export and import it through
ordinary namespace files; no separate schema registry is required.
A named schema keeps the native kind of its description. A named integer is still an integer. Saved definitions preserve source and finite reference graphs, excluding captured runtime state. Reading that data does not execute it; loading it is an explicit operation.
2.3. schemas/valid?
Function(schemas/valid? schema value) → boolean
Tests a value against a schema without converting it. A schema is one of four things:
- A plain value. A scalar or a tagged value accepts only an equal value. A map is an open shape: it accepts every map that has its fields, with values that its field schemas accept. A list is positional: one schema for each position, and the same length.
- A function. It accepts a value when calling it on that value returns
true.false, another result, or an ordinary error rejects the value. Exhausted resources or cancellation stop the check, so[not S]never accepts a value because the check ofSstopped. The function must be pure. anyornever(also⊤and⊥), which accept every value and no value.- An operator form: a list whose first element is a schema operator. The
operators are
meet,join,not,maybe,map-of,count,error,defaultandis. An operator is a marker, not a function. Only its schema operands are read as schemas; the arguments ofisanddefaultare values.
The kind predicates are schemas for the value kinds: null?, boolean?,
int?, float?, number?, string?, template?, bytes?, bitset?,
list?, map?, fn?, local?, const?, jsonptr?, uuid?, utc?,
duration?, link?, hash?, regex?, regex-matcher?, peg?, invoke?,
quote?, quasiquote?, unquote?, unquote-splicing?, tagged?,
error?, and the packed math kind predicates v2?, v3?,
v4?, m22?, m33?, m44?, quat?, aabb?, ray?, sphere?, plane?,
triangle? and frustum?, and the packed vector kind
predicates vf? and vi?. Kinds are exact: int? accepts no float, and tagged? accepts no
error. true, false and null are literals. A kind is an ordinary name, so
a local binding with the same name hides it.
(schemas/valid? int? 80) // => true
A map has no reserved keys: value, key and bind, and the operator
names, are ordinary field names. Each described field is required, and extra
fields are allowed, so adding a field to a shape only narrows it.
A tag in a schema position names predicates. The name t reads as the
builtin t when it ends in ?, and as the builtin t? when it does not. Thus
<string> and <string?> are both string?, and {name <string>} is
{name string?}. A tag with two or more names is their meet, and a negated
name is a not: {age <int? math/even?>} and {age <int math/even>} are
{age [meet int? math/even?]}, and {nick <!null?>} is
{nick [not null?]}. Only builtins are read. A local function with the same
name does not change the meaning of the tag. A tag whose name has no builtin
is #err <invalid schema>, and the message names the tag: <nope> gives
"<nope> has no nope? predicate". JSON writes <string> as
{"string": true}, which is the same value, so a schema in JSON or in host
data reads the same way.
A tag is a map whose members are all true or false. Thus the map
{active true} is the tag <active>, and it is an invalid schema because
there is no active? builtin. To require a field to be true, write
{active [is = true]}. A map that has tags and other fields, such as
{<active> name string?}, is a shape: it requires active to be true and
name to be a string. When schemas/simplify or schemas/meet reduces each
field of a shape to a boolean, it writes each field as [is = b], so the
result stays a shape.
(schemas/valid? {name string?} {age 23 name "Chani"}) // => true (schemas/valid? {name string?} {age 23}) // => false (schemas/valid? [int? string?] [80 "melange"]) // => true (schemas/valid? {value int?} {value 42}) // => true
(schemas/valid? {active [is = true]} <!active>) // => false
(defschema Pilot {name <string> age [optional <int? !float>]}) // => Pilot (defn greet [<name>] [{name <string>} => <string>] (str "Hello " name)) // => greet {bare [(schemas/valid? <string> "Ada") (schemas/valid? <string?> "Ada") (schemas/valid? <string> 1)] field [(schemas/valid? {name <string>} {name "Ada"}) (schemas/valid? {name <string?>} {name "Ada"}) (schemas/valid? {name <string>} {name 1})] simplified (schemas/simplify {name <string> nick <string?>}) group [(schemas/valid? {age <int? math/even?>} {age 4}) (schemas/valid? {age <int? math/even?>} {age 3}) (schemas/valid? {age <int math/even>} {age 4}) (schemas/valid? {age <int math/even>} {age 4.0})] group-simplified (schemas/simplify <int math/even>) negated [(schemas/valid? {nick <!null?>} {nick "Usul"}) (schemas/valid? {nick <!null?>} {nick null}) (schemas/valid? {nick <!null?>} {})] negated-simplified (schemas/simplify <!null>) nested [(schemas/valid? {pilot {age <int>}} {pilot {age 23}}) (schemas/valid? {pilot {age <int>}} {pilot {age "23"}})] positions [(schemas/valid? [<int> <string>] [1 "a"]) (schemas/valid? [... <int>] [1 2 "a"]) (schemas/valid? [map-of <string> <int>] {a 1}) (schemas/valid? [maybe <string>] null) (schemas/valid? [count <int>] [1 2]) (schemas/valid? [not <int>] 1) (schemas/valid? {nick [optional <string>]} {})] mixed [(schemas/valid? {<active> name <string>} {active true name "Ada"}) (schemas/valid? {<active> name <string>} {active false name "Ada"})] true-field [(schemas/valid? {active [is = true]} {active true}) (schemas/valid? {active [is = true]} {active false})] error-payload [(schemas/valid? [error <division>] (/ 1 0)) (schemas/valid? [error <division>] (+ 1 "a")) (schemas/valid? [error <invalid schema>] (schemas/valid? <nope> 1)) (schemas/valid? [error {<invalid schema> message string?}] (schemas/valid? <nope> 1))] shared-payload (let [division <division> number <int>] [(schemas/valid? [join number [error division]] (/ 1 0)) (schemas/valid? [join number [error number]] 3) (schemas/valid? [join number [error number]] "3")]) unknown (schemas/valid? <nope> 1) unknown-negated (schemas/valid? <!nope> 1) unknown-field (schemas/valid? {name <nope>} {name "Ada"}) unknown-group (schemas/valid? <int nope> 1) no-active (schemas/valid? <active> {active true}) builtins-only (let [active? (fn [value] true)] (schemas/valid? <active> 1)) explain (schemas/explain {name <string> age <int? math/even?>} {name 1 age 3}) meet (schemas/meet <int> <math/even>) materialize (schemas/materialize {name [meet <string> [default "Ada"]] nick [optional <string>]}) fakerize (let [a (random/seeded 7) b (random/seeded 7) value (schemas/fakerize a {age <int> name <string>})] [value (= value (schemas/fakerize b {age int? name string?}))]) match (map (fn [value] (schemas/match value ({name [bind n <string>]} n) (any "none"))) [{name "Ada"} {name 1}]) definition [(schemas/valid? Pilot {name "Ada" age 3}) (schemas/valid? Pilot {name "Ada" age 3.0}) (schemas/valid? Pilot {name 1})] contract [(greet {name "Ada"}) (greet {name 1})] contract-error (let [safe (fn [x] [<int> => <error>] (/ x 0))] (errors/message (safe 1))) callable (let [wide ((fn [callback] [<fn> => [<number> => <int>]] callback) (fn [value] 1)) apply-one (fn [f] [[<int> => <int>] => <int>] (f 1))] [(schemas/valid? [int? => number?] wide) (schemas/valid? [<int> => <number>] wide) (schemas/valid? [<string> => <number>] wide) (apply-one (fn [x] (+ x 1))) (apply-one (fn [x] "one"))])} // => {bare [true true false] // builtins-only #err {<invalid schema> // message "<active> has no active? predicate"} // callable [true // true // false // 2 // #err {<contract result> // message "function contract result mismatch"}] // contract [ // "Hello Ada" // #err {<contract input> // message "function contract input mismatch"}] // contract-error "division by zero" // definition [true false false] // error-payload [true false true true] // explain #err {<schema-mismatch> // errors [{in /age // message "predicate rejected the value" // path /age/2 // schema #builtin "math/even?" // value 3} // {in /name // message "predicate rejected the value" // path /name // schema #builtin "string?" // value 1}] // message "value does not match schema" // schema {age [#builtin "meet" #builtin "int?" #builtin "math/even?"] // name #builtin "string?"} // value {age 3 // name 1}} // fakerize [{age -443 name ""} true] // field [true true false] // group [true false true false] // group-simplified [#builtin "meet" #builtin "int?" #builtin "math/even?"] // match ["Ada" "none"] // materialize {name "Ada"} // meet [#builtin "meet" #builtin "int?" #builtin "math/even?"] // mixed [true false] // negated [true false false] // negated-simplified [#builtin "not" #builtin "null?"] // nested [true false] // no-active #err {<invalid schema> // message "<active> has no active? predicate"} // positions [true false true true true false true] // shared-payload [true true false] // simplified {name #builtin "string?" // nick #builtin "string?"} // true-field [true false] // unknown #err {<invalid schema> // message "<nope> has no nope? predicate"} // unknown-field #err {<invalid schema> // message "<nope> has no nope? predicate"} // unknown-group #err {<invalid schema> // message "<nope> has no nope? predicate"} // unknown-negated #err {<invalid schema> // message "<!nope> has no nope? predicate"}}
Openness permits extra fields; it does not make described fields optional.
For example, {name string?} rejects {} and accepts {name "Chani" extra 1}.
Whether a field can be missing is a property of the field, not of its value.
Write [optional S] as the value of a field, and nowhere else. [maybe S] is
a schema: it accepts what S accepts, and null. Thus
{nick [optional string?]} accepts {} and rejects {nick null}, and
{nick [maybe string?]} rejects {} and accepts {nick null}. A field that
can be missing or null is [optional [maybe S]].
(schemas/valid? {name [optional [maybe string?]]} {}) // => true (schemas/valid? {name [optional [maybe string?]]} {name null}) // => true (schemas/valid? {items [optional [maybe [... int?]]]} {items [1 2]}) // => true
A list schema is positional: [int? string?] accepts a list of one integer and
one string. ... repeats the schema immediately after it zero or more times,
so [... int?] accepts any number of integers. A prefix and a suffix can
surround the repeated section. A trailing ... accepts any remaining elements.
A list schema can contain one .... list? accepts every list, and []
accepts only the empty list.
(schemas/valid? [... int?] [1 2 3]) // => true (schemas/valid? [string? ... int? string?] ["head" 1 2 "tail"]) // => true (schemas/valid? [string? ...] ["head" 1 null]) // => true
[map-of V] accepts a map whose values V accepts. [map-of K V] also checks
each key with K. All map keys are strings, so write K only when it says
more than that. A map with no entries satisfies its entry constraints; a value
that is not a map does not. A dictionary and a shape combine with meet:
[meet [map-of int?] {total int?}] requires an integer total and integer
values. Nest the forms directly: [... [... int?]] describes a list of integer
lists, and [map-of [... int?]] a map of integer lists.
(schemas/valid? [map-of int?] {melange 80 water 12}) // => true (schemas/valid? {foo [... int?]} {foo [1 2]}) // => true (schemas/valid? [map-of [... int?]] {melange [80 90] water []}) // => true
[is f arg...] accepts a value x when (f x arg...) returns true. It is
the one way to call a function with extra arguments, so bounds and equality
use it too: [is < 5], [is >= 2.0] and [is = [1 2]]. With a builtin
comparison it is a bound, which simplification and generation read. Strings
and templates compare as text. [is = v] matches the value v exactly, unless
v is an error. [is ! 3]= rejects "a", because != fails on mixed types,
but [not [is = 3]] accepts it.
(schemas/valid? [is >= 18] 21) // => true (schemas/valid? [is >= "A"] "Bob") // => true (schemas/valid? [is = [1 2]] [1 2 3]) // => false
[count S] checks the number of elements in a list or map, bytes in a byte
string, or Unicode code points in a string or template. The count must match
S; other kinds do not match. count is a marker in a schema; (count xs)
and :count still reach the function.
(schemas/valid? [count [is >= 3]] [1 2 3]) // => true (schemas/valid? [count [is = 2]] "éé") // => true
Use [int?] when exactly one integer is required, and [is = [1 2]] to match
a literal list.
[not S] accepts exactly the values that S rejects; it is a single
alternative and carries no defaults. [error S] accepts an error whose
payload S accepts, so [error <division>] accepts every error tagged
division. The operand of error is compared with the payload as data, so a
tag in it is not a predicate: [error {<invalid schema> message string?}]
accepts an invalid-schema error that has a string message. error? accepts
any error.
In a schema, these values have their own meaning and are never read as
literals: a function; an error value; an operator, optional, bind, any,
never, ... and =>; a name or a quoted form; a list that starts with an
operator or contains ... or =>; and any map or list that contains one of
these. An error value nested in a schema, or an operator anywhere but the head
of a list, is an invalid schema. An unbound name evaluates to an error value,
so a misspelled predicate such as {age itn?} is #err <invalid schema>. An
error passed as the whole schema argument is the result of the call.
(schemas/meet int? string?) // => #builtin "never" (schemas/valid? int? {int true}) // => false (let [int? (fn [v] false)] (schemas/valid? int? 8)) // => false (schemas/valid? [not int?] "x") // => true (schemas/valid? [not [not int?]] 3) // => true (schemas/meet int? [not int?]) // => #builtin "never" (let [positive? (fn [x] (> x 0))] [(schemas/valid? positive? "x") (schemas/valid? [not positive?] "x")]) // => [false true] (schemas/valid? {items :count} {items [1 2]}) // => false [(schemas/valid? {age itn?} {age 3})] // => [#err {<invalid schema> // message "an error value is not a schema"}] (schemas/valid? {default 5 not true} {default 5 not true}) // => true [(schemas/valid? {mode not} {mode 1})] // => [#err {<invalid schema> // message "schema operator is not valid in this position"}] (schemas/valid? {nick [optional string?]} {}) // => true (schemas/valid? {nick [optional string?]} {nick null}) // => false (schemas/valid? {nick [maybe string?]} {}) // => false (schemas/valid? {nick [maybe string?]} {nick null}) // => true (schemas/valid? {nick [not null]} {}) // => false (schemas/match {} ({nick [optional [bind nick string?]]} nick)) // => null (schemas/valid? [meet [map-of int?] {total int?}] {total 5 a 1}) // => true (schemas/valid? [meet [map-of int?] {total int?}] {a 1}) // => false (schemas/valid? [is != 3] "a") // => false (schemas/valid? [not [is = 3]] "a") // => true (schemas/valid? {age #builtin "int?"} {age 3}) // => true [(schemas/valid? (documents/value (encoding/decode "dust" "{age int?}")) {age 3})] // => [#err {<invalid schema> // message "a name or a quoted form is not a schema"}] (schemas/explain {a int? b (fn positive? [x] (> x 0)) c (fn [x] (> x 0))} {a "x" b -1 c -1}) // => #err {<schema-mismatch> // errors [{in /a // message "predicate rejected the value" // path /a // schema #builtin "int?" // value "x"} // {in /b // message "predicate rejected the value" // path /b // schema (fn positive? [x] (> x 0)) // value -1} // {in /c // message "predicate rejected the value" // path /c // schema (fn [x] (> x 0)) // value -1}] // message "value does not match schema" // schema {a #builtin "int?" // b (fn positive? [x] (> x 0)) // c (fn [x] (> x 0))} // value {a "x" // b -1 // c -1}}
(schemas/valid? <active> {active true name "Ada"}) // => #err {<invalid schema> // message "<active> has no active? predicate"} (schemas/valid? {active [is = true]} {active true}) // => true (schemas/valid? (schemas/meet {active [is = true]} {name string?}) {active true name "Ada"}) // => true (schemas/valid? {} 42) // => false (schemas/valid? {} {a 1}) // => true (schemas/valid? any 42) // => true (schemas/valid? [] [1]) // => false (schemas/valid? [] []) // => true (let [f (fn [x] x)] (schemas/valid? f f)) // => false (let [f (fn [x] x)] (schemas/valid? [is = f] f)) // => true (let [f (fn [x] x)] [(schemas/valid? f true) (schemas/valid? f 3)]) // => [true false] (schemas/valid? [error <division>] (/ 1 0)) // => true (schemas/valid? [error <division>] (+ 1 "a")) // => false (schemas/valid? error? (/ 1 0)) // => true
The top-level form (defschema name description) binds a named description.
Its body can refer to the name being defined. For example, each house below
has a required name and a list of child houses. A recursive leaf has an
empty children list; omitting the children field does not match.
(defschema House {children [... House] name string?}) // => House (schemas/valid? House {children [{children [] name "Paul"}] name "Atreides"}) // => true
Each recursive cycle must descend into a child value. A definition such as
(defschema Loop [meet Loop]) is invalid because it never reaches a child.
Checking a cyclic candidate terminates and rejects it. Sharing a child
between two finite branches is allowed.
A named description keeps the predicates and namespace revision selected when
it was defined, including qualified imports. Replacing a namespace later does
not change existing descriptions. Ordinary collection mutation still changes
the description itself; the next check uses its current contents. For example,
(defschema Alias House) gives the existing description another name without
changing its recursive references or predicates.
A named scalar keeps its native value kind. Its definition provenance follows
bindings, direct returns, and copies. A computation makes a new value without
that provenance: Answer below snapshots as (defschema Answer 42), while
(+ Answer 0) snapshots as plain 42.
(defschema Answer 42) // => Answer (documents/value (documents/from-value Answer)) // => (defschema Answer 42) (documents/value (documents/from-value (+ Answer 0))) // => 42
A schema read from plain data is not evaluated. A kind or an operator is
written there as #builtin "int?" or #builtin "meet", and in JSON as
{"#builtin": "int?"}. A bare name in plain data is still a name, so it is an
invalid schema. A predicate that a program defines cannot be named in plain
data; a saved definition carries its functions. A document snapshot writes a
builtin function in a schema as its #builtin form.
(documents/value (documents/from-value [>= 3])) // => [#builtin ">=" 3]
2.4. schemas/match
Special Form(schemas/match candidate (pattern [when guard] body...) ...)
Evaluates candidate once. It checks branches in source order and selects the first matching pattern with a true guard.
A [bind name S] pattern captures the candidate after S matches it. For
example, [bind amount int?] checks an integer and names it amount inside
the selected branch. [bind name] captures its candidate without a check. The
capture name is not evaluated. A capture exists only after the complete
pattern matches. bind belongs to match patterns; it is invalid in a
schemas/valid? description.
(schemas/match 80 ([bind amount int?] (+ amount 1))) // => 81
Capture names must be declared in that branch's pattern source. A computed descriptor cannot introduce a new capture name. Dynamic patterns without captures remain valid.
An absent optional field captures null. Repeated captures keep these
slots, preserving their list shape.
Captures retain named-schema definition provenance without changing native value kinds. This also applies to values collected by repeated captures.
A repeated list constraint collects its capture values in order. Nested repetitions produce nested lists, including empty lists for zero matches.
Map keys are always strings, so capturing a key needs no string check.
Collection captures bind the same lists and maps as the values they match.
For {a 1 b 2}, the pattern [map-of [bind keys] [bind values int?]] binds
keys to {a "a" b "b"} and values to {a 1 b 2}. Both captures use the
original input keys; their result does not depend on traversal order. Empty
maps yield empty maps.
A list schema such as [... [bind values int?]] captures an ordered list, including an empty list for empty input. Nested collection captures preserve each map or list layer. Failed branches discard all partial captures.
The optional guard can use branch captures. It must be pure and return a boolean. False or an ordinary error skips the branch. Calling a map or list reads a path and is permitted as a pure guard.
Patterns and guards use ordinary lexical name resolution. Pure functions from the current session or imported namespaces can be guards; function references whose purity cannot be established are invalid guards.
Resource exhaustion, cancellation, and other operation failures stop the match. They do not select a later branch.
An impure guard or a nonboolean guard is invalid. The engine rejects an impure guard before its effect occurs.
Only the selected body runs. Its forms run in order, and schemas/match returns the last result. No matching branch returns null.
Use an any branch for an explicit fallback. Separate branches can use the same capture name, but one pattern cannot contain duplicate names.
Captures are invalid inside join and not. Use separate branches when each alternative needs captures or source-order selection.
(schemas/match {pilot "Chani" reserve 50 spice 80} ({pilot [bind pilot string?] reserve [bind reserve int?] spice [bind amount int?]} [when (> amount reserve)] ~",pilot can release ,(- amount reserve)") (any "Keep the reserve")) // => "Chani can release 30" (schemas/match [{spice 80} {spice 90}] ([... {spice [bind amounts int?]}] amounts)) // => [80 90] (schemas/match {melange 80 water 12} ([map-of [bind keys] [bind values int?]] [keys values])) // => [{melange "melange" water "water"} {melange 80 water 12}]
2.5. schemas/materialize
Function(schemas/materialize schema) → value
error
Creates a concrete value only when the schema determines one. It can select a
literal, a forced value, or a default preference. It does not convert values.
Defaults do not restrict accepted values; schemas/valid? ignores them. Write a
preference beside its constraint, for example [meet int? [default 8080]].
A schema with or without defaults is materialized by the same rules. Each
join alternative keeps its own constraints and defaults, and an alternative
that accepts no value takes no part, so schemas/meet distributes over
schemas/join: [meet int? [join string? 0]] materializes to 0.
(schemas/materialize [join 1 2]) // => #err {<invalid value> // message "schema does not determine a value"} (schemas/materialize [meet int? [join string? 0]]) // => 0 (schemas/materialize (schemas/meet int? (schemas/join string? 0))) // => 0 (schemas/materialize (schemas/join (schemas/meet int? string?) (schemas/meet int? 0))) // => 0 (schemas/materialize [join 0 [meet string? int?]]) // => 0 (schemas/materialize (schemas/simplify [join 0 [meet string? int?]])) // => 0 (schemas/materialize {port [meet int? [join "auto" 80]]}) // => {port 80} (schemas/materialize {settings map?}) // => {settings {}} (schemas/materialize [map-of int?]) // => {} (schemas/materialize [meet string? map?]) // => #err {<invalid value> // message "schema does not determine a value"}
Materialization resolves defaults after all hard constraints. A default is
read in pieces. A map default gives one piece for each field and one piece
that says a map exists. A list default gives one piece for each position and
one piece for its length. A constraint that excludes a piece gives it up. A
constraint that fixes the kind of a position, such as map?, a shape or a
literal, also gives up the pieces below it that need another kind. A fixed
value, written as a literal or as [is = x], wins over a default at its
position. A function at a position is a predicate, not a fixed value. Compatible pieces at separate map fields or list positions combine.
(defschema Q [meet [is = 5] [default 0]]) // => Q (schemas/materialize [meet [is = 5] [default 0]]) // => 5 (schemas/materialize [meet 5 [default 0]]) // => 5 (schemas/materialize [is = 5]) // => 5 (schemas/materialize Q) // => 5 (schemas/materialize (schemas/load (documents/value (documents/from-value Q)))) // => 5 (schemas/materialize [meet [is = [1 2]] [default [0 0]]]) // => [1 2] (schemas/materialize {port [meet int? [is = 443] [default 80]]}) // => {port 443}
Fixed map and list values remain unchanged while deeper constraints are checked. A contradictory field or position returns an error and does not change the original value or schema.
(def original {x 1}) // => original [(schemas/materialize [meet [is = original] {x 2}]) original] // => [#err {<invalid value> // message "schema does not determine a value"} // {x 1}] (def nested {a {x 1}}) // => nested [(schemas/materialize [meet [is = nested] {a {x 2}}]) nested] // => [#err {<invalid value> // message "schema does not determine a value"} // {a {x 1}}] (def sequence [1 2]) // => sequence [(schemas/materialize [meet [is = sequence] [3 4]]) sequence] // => [#err {<invalid value> // message "schema does not determine a value"} // [1 2]] (def wrapped {a [1 2]}) // => wrapped [(schemas/materialize [meet {a [is = (get wrapped "a")]} {a [3 4]}]) wrapped] // => [#err {<invalid value> // message "schema does not determine a value"} // {a [1 2]}] [(schemas/materialize [meet [is = original] {x 1}]) original] // => [{x 1} {x 1}] (schemas/materialize [meet [is = {a 1}] [default {a 1}] [default {a 2}]]) // => {a 1} (schemas/materialize [meet [is = {a 1}] [default {a 1 b 2}] [default {a 1 b 3}]]) // => {a 1} (schemas/materialize [meet [is = {a {b 1}}] [default {a {b 1}}] [default {a {b 2}}]]) // => {a {b 1}}
A default is identified by its position and value. Equal defaults at one position are one default, also when they are written separately or restored after save and load.
(def D [default 8080]) // => D (def S [join [meet D int?] [meet D "auto"]]) // => S (def R (documents/value (documents/from-value S))) // => R (schemas/materialize [join [meet [default 8080] int?] [meet [default 8080] "auto"]]) // => 8080 (= R [#builtin "join" [#builtin "meet" [#builtin "default" 8080] #builtin "int?"] [#builtin "meet" [#builtin "default" 8080] "auto"]]) // => true (schemas/materialize S) // => 8080 (schemas/materialize R) // => 8080 (schemas/materialize [join [meet {port int?} [default {port 8080}]] [meet {port "auto"} [default {port 8080}]]]) // => {port 8080} (schemas/materialize [join [meet [default [1 2]] [int? int?]] [meet [default [1 2]] [1 3]]]) // => [1 2]
A join keeps its alternatives and their defaults separate. An alternative
that accepts no value takes no part: a literal or [is = x] that another
constraint at its position rejects removes its alternative. One alternative
beats another when, among the defaults that applied to both, it gave up a
strict subset of what the other gave up. Materialization uses only the
preferred alternatives, which no other alternative beats.
(schemas/materialize [meet "auto" [join [is >= 0] [default 0]]]) // => "auto" (schemas/materialize (schemas/meet "auto" (schemas/join [is >= 0] [default 0]))) // => "auto" (schemas/materialize [join [meet 5 [is < 3]] [meet int? [default 1]]]) // => 1 (schemas/materialize [join [meet [is = 5] [is < 3]] [meet int? [default 1]]]) // => 1 (schemas/materialize [join [meet 2 [is < 3]] [meet int? [default 1]]]) // => #err {<invalid value> // message "schema does not determine a value"} (schemas/materialize [join [meet {port int?} 5] [meet int? [default 1]]]) // => 1 (schemas/materialize [join [meet [int? int?] "auto"] [meet string? [default "a"]]]) // => "a"
Defaults that disagree at one position in a preferred alternative, or in two
preferred alternatives that share an accepted value, return
conflicting defaults as an invalid-value error. A beaten alternative cannot
cause this error. Defaults of different kinds at one position, such as a
scalar and a map, or a map and a list, disagree.
(def D1 [default 1]) // => D1 (schemas/materialize [join [meet int? D1] [meet [is >= 5] D1 [default 7]]]) // => 1 (schemas/materialize [join [meet int? [default 1]] [meet [is >= 5] [default 1] [default 7] [default 8]]]) // => 1 (schemas/materialize [join [meet int? [default 1]] [meet [is >= 0] [default 2]]]) // => #err {<invalid value> // message "conflicting defaults"} (schemas/materialize [join [meet int? [default 1]] [meet string? [default "a"]]]) // => #err {<invalid value> // message "schema does not determine a value"}
(schemas/materialize [meet [default [0 1]] [default {port 0}]]) // => #err {<invalid value> // message "conflicting defaults"} (schemas/materialize [meet [default {port 0}] [default [0 1]]]) // => #err {<invalid value> // message "conflicting defaults"} (schemas/materialize [meet [default 1] [default {port 0}]]) // => #err {<invalid value> // message "conflicting defaults"} (schemas/materialize [meet [default {port 0}] [default 1]]) // => #err {<invalid value> // message "conflicting defaults"} (schemas/materialize [meet map? [default 1] [default {port 0}]]) // => {port 0} (schemas/materialize [join [meet any [default 1]] [meet any [default {port 0}]]]) // => #err {<invalid value> // message "conflicting defaults"} (schemas/materialize [join [meet int? [default 1]] [meet map? [default {port 0}]]]) // => #err {<invalid value> // message "schema does not determine a value"} (schemas/materialize [meet map? [default {port 0}] [default [0 1]]]) // => {port 0} (schemas/materialize [meet map? [default [0 1]] [default {port 0}]]) // => {port 0} (schemas/materialize [meet list? [default [0 1]] [default {port 0}]]) // => [0 1] (schemas/materialize [meet {port int?} [default [0 1]] [default {port 0}]]) // => {port 0} (schemas/materialize [meet 5 [default {port 0}]]) // => 5 (schemas/materialize [meet [int? int?] [default {port 0}] [default [0 1]]]) // => [0 1] (schemas/materialize [meet (fn [x] (map? x)) [default {port 0}] [default [0 1]]]) // => #err {<invalid value> // message "schema does not determine a value"}
Materialization returns the most general value of the preferred alternatives.
If none is most general, it returns schema does not determine a value.
Values are compared by structure, not read as schemas. A value is more general
than another when each piece that it states is in the other: an equal scalar,
a map with all of its fields, or a list of the same length, position by
position. Thus {a 1} is more general than {a 1 b 2}, but [1] is not more
general than [1 1], and [] is more general only than [].
(schemas/materialize {tls [meet boolean? [default false]]}) // => <!tls> (schemas/materialize {tls [meet boolean? [default true]]}) // => <tls> (schemas/materialize [join [meet [count [is = 1]] [default [1]]] [meet [1 1] [default [1 1]]]]) // => #err {<invalid value> // message "schema does not determine a value"} (schemas/materialize [join [meet [count [is = 0]] [default []]] [meet [1 2] [default [1 2]]]]) // => #err {<invalid value> // message "schema does not determine a value"} (schemas/materialize [join [meet {a int?} [default {a 1}]] [meet {a int? b int?} [default {a 1 b 2}]]]) // => {a 1} (schemas/materialize [join [meet [int? int?] [default [1 2]]] [meet [int? int?] [default [1 3]]]]) // => #err {<invalid value> // message "conflicting defaults"}
A default inside optional applies only when the field is present, so it
never makes the field present. To prefer a present field, put the default on
the enclosing map: [meet {note [optional [maybe string?]]} [default {note "ready"}]]
materializes to {note "ready"}, while {note [optional [default "ready"]]}
materializes to {}. map?, a shape and a map-of dictionary materialize to
{} at any position, because the empty map is the most general map; int? and
list? do not determine a value.
A repeated element schema such as [... int?] does not choose a list length.
Supply a forced value or default when materializing it. It does not give up the
length of a list default, so [meet [... int?] [default [1]] [default [1 2]]]
returns conflicting defaults, the same as with list?.
(schemas/materialize [meet [... int?] [default [1]] [default [1 2]]]) // => #err {<invalid value> // message "conflicting defaults"} (schemas/materialize {tags [meet [... string?] [default []] [default ["viewer"]]]}) // => #err {<invalid value> // message "conflicting defaults"} (schemas/materialize [meet list? [default [1]] [default [1 2]]]) // => #err {<invalid value> // message "conflicting defaults"} (schemas/materialize [meet [... any] [default [1]] [default [1 2]]]) // => #err {<invalid value> // message "conflicting defaults"} (schemas/materialize [meet [... int?] [default [1 2]]]) // => [1 2] (schemas/materialize {tags [meet [... string?] [count [is = 1]] [default []] [default ["viewer"]]]}) // => {tags ["viewer"]}
A constraint on the whole list also applies to the pieces of a list default.
A repeated element schema, [... S], gives up a position whose value it rejects. A count gives
up a length it rejects, and a position that no permitted length reaches. Thus
[meet [... int?] [count [is < 1]] [default [1]] [default [1 2]]]= materializes to
[1]: the count gives up the length 2 and the second position.
(schemas/materialize [meet [... int?] [count [is <= 3]] [default [1]] [default [1 2]]]) // => #err {<invalid value> // message "conflicting defaults"} (schemas/materialize [meet [... int?] [count [is <= 1]] [default [1]] [default [1 2]]]) // => [1] (schemas/materialize {v [meet [... int?] [count [is <= 1]] [default [1 2]]]}) // => {v [1]} (schemas/materialize [meet [... string?] [count [is < 2]] [default ["a" "b"]]]) // => ["a"] (schemas/materialize {v [meet [... int?] [count [join [is = 0] [is = 1]]] [default [1]] [default [1 2]]]}) // => {v [1]} (schemas/materialize [meet [... int?] [count [meet [is >= 0] [is <= 1]]] [default [1]] [default [1 2]]]) // => [1] (schemas/materialize [meet [... int?] [default [1 "a"]]]) // => #err {<invalid value> // message "schema does not determine a value"} (schemas/materialize [meet [... int?] [default [1 "a"]] [default [1 2]]]) // => [1 2] (schemas/materialize [meet [... int?] [default [{a 1}]] [default [1]]]) // => [1] (schemas/materialize [meet [... int?] [default [[1]]] [default [1]]]) // => [1] (schemas/materialize [meet [... [... int?]] [default [[{a 1}]]] [default [[1]]]]) // => [[1]] (schemas/materialize [meet [... {a int?}] [default [[1]]] [default [{a 1}]]]) // => [{a 1}] (schemas/materialize [meet [... {a int? b int?}] [default [{a 1}]] [default [{b 2}]]]) // => [{a 1 b 2}] (schemas/materialize [meet [... [join int? string?]] [default [{a 1}]] [default [1]]]) // => [1] (defschema IntElement int?) // => IntElement (schemas/materialize [meet [... IntElement] [default [{a 1}]] [default [1]]]) // => [1] (defschema MapElement {a int? b int?}) // => MapElement (schemas/materialize [meet [... MapElement] [default [{a 1}]] [default [{b 2}]]]) // => [{a 1 b 2}] (defschema Row [meet {a int?} {b int?}]) // => Row (schemas/materialize [meet [... Row] [default [{a "x" b 1}]] [default [{a 1 b 1}]]]) // => [{a 1 b 1}] (schemas/materialize [meet [... [int? int?]] [default [{a 1}]] [default [[1 2]]]]) // => [[1 2]] (schemas/materialize [meet [... [int? int?]] [default [[1 "x"]]] [default [[1 2]]]]) // => [[1 2]]
A repeated element schema also gives up incompatible container pieces and
pieces below them. For example, [meet [... int?] [default [{a 1}]] [default [1]]]
gives [1].
Compatible partial map defaults still combine their fields.
A repeated list schema such as [1 ... 2] fixes some positions but not the
list length. It needs a fixed value or default to materialize; the shortest
accepted list is not more general than longer lists.
(schemas/materialize [... 1]) // => #err {<invalid value> // message "schema does not determine a value"} (schemas/materialize [1 ... 2]) // => #err {<invalid value> // message "schema does not determine a value"} (schemas/materialize [1 ...]) // => #err {<invalid value> // message "schema does not determine a value"} (schemas/materialize [meet [1 ... 2] [default [1 2 2]]]) // => [1 2 2] (schemas/materialize [meet [1 ... 2] [is = [1 2]]]) // => [1 2] (schemas/materialize [meet [1 ... 2] [default [1]]]) // => [1] (schemas/materialize [meet [1 ... 2] [is = [1]]]) // => [1] (schemas/materialize [meet [1 ... 2] [default [2]] [default [1]]]) // => [1] (schemas/materialize [meet [1 ... 2] [default [1 "x"]] [default [1 2]]]) // => [1 2]
Materialization does not call an opaque predicate to search for a value. This
reasoning is incomplete by design. An opaque predicate constraint alone does not determine
a value. Compatible nested shapes in a meet combine their required fields;
different join alternatives do not invent a merged value. After selection, the shared checker runs
all applicable predicates on the concrete candidate.
(schemas/materialize {host "localhost" port [default 8080]}) // => {host "localhost" // port 8080} (schemas/materialize {name [default "Chani"] note [optional [maybe string?]]}) // => {name "Chani"} (schemas/materialize {port int?}) // => #err {<invalid value> // message "schema does not determine a value"} (schemas/materialize [meet {port [default 8080]} {port [default 9090]}]) // => #err {<invalid value> // message "conflicting defaults"}
2.6. schemas/fakerize
Function(schemas/fakerize generator schema) → value
error
(schemas/fakerize generator schema options) → value
error
Makes a random value that matches schema. The function advances the supplied
random generator. Equal generator states and equal schemas produce equal values.
The generator selects join branches, maybe alternatives, optional fields, repeated elements,
collection lengths, scalar boundaries, and ordinary scalar values.
The default size is 64 choices.
Set size in the options map to use a different budget. The valid range is
1 through 8,192 choices. Recursion, collections, strings, and scalar choices
use the same budget.
schemas/fakerize supports exact values, kind predicates, bounds, shapes, positional lists,
repetition, count constraints, map-of dictionaries, [error S], defaults, and recursive
named schemas. It can construct each native value kind. A not operand
constructs nothing; another operand of the same meet builds the value, and the
final check filters it.
schemas/fakerize does not call an opaque predicate. When no constructive alternative
remains, an opaque predicate returns
#err <unsupported generation>. A schema with no accepted values returns
#err <impossible generation>. An empty size budget returns
#err <exhausted generation>.
Generated values pass the shared checker for their constructive branch before return. Opaque alternatives are never called. Rejected candidates use the same bounded budget.
(schemas/fakerize (random/seeded 42) [meet int? [is >= 18] [is <= 21]]) // => 18 (schemas/fakerize (random/seeded 42) [meet [... int?] [count [is = 3]]] {size 8}) // => [360 -242 -833]
Guarded recursive schemas use the same budget. The generator selects a terminating collection length before the budget is empty.
2.7. schemas/check
Function(schemas/check function) → report
error
(schemas/check function options) → report
error
Generates isolated calls from a declared contract or an exact inferred signature.
The default options are {seed 0 cases 1000 size 8192}. cases must be from
1 through 1,000,000; size must be from 1 through 8,192 choices per case.
A declared contract is an obligation to test, not proof of correct behavior.
Approximate inference alone returns <unsupported>.
Each case starts with fresh inputs and function state. Arguments can share
collections. Named schema definitions are copied into the check; captured caller
state is unsupported. Tested functions cannot access the real filesystem,
network, processes, or database. Clock reads use generated times. Seeded random
operations retain their deterministic algorithm and record their outputs.
Effects without a model return <unsupported> before the body runs.
A report contains status (<passed>, <failed>, or <unsupported>), cases,
seed, and failures. Unsupported reports also contain reason.
Failures contain minimized inputs, effects, before and after state,
diagnostics, origin, and replay. Result mismatches use the shared schema
diagnostics. Function values in reports are owned definition data, including
builtin names; report publication does not reconstruct a live closure.
Passing means the requested generated cases completed; it is not
proof for every possible input. A CPU, memory, cancellation, or generation-budget
interruption returns an error and cannot become a passing report.
(schemas/check (fn [amount] [int? => int?] amount) {cases 4 seed 42 size 64}) // => {cases 4 // failures [] // seed 42 // status <passed>}
To reproduce a failure, pass only {replay "BLOB"} as the options map. Do not
combine replay with seed, cases, or size. Replay checks the definition,
owned schema snapshot, and draw protocol. A changed snapshot returns
#err <check mismatch replay>; malformed or non-reproducing traces return an
error. Copy the returned blob verbatim.
2.8. schemas/explain
Function(schemas/explain schema value) → null
error
Returns null when value matches schema. A mismatch returns a structured
#err <schema-mismatch> value. An invalid schema returns a separate
#err <invalid schema> value.
The top-level error contains schema, value, and errors. Each error entry
contains path, in, schema, value, and message. path points into the
schema. in points into the candidate. Both fields use JSON Pointers, including
(jsonptr "") for the root.
A predicate is shown as it prints: a builtin by its name, such as
#builtin "int?", a named function such as (fn positive? [x] ...) with its
name, and an anonymous function as its source. An error that a predicate
returned is available in cause. When every join branch fails,
errors contains diagnostics for each failed branch. Recursive references and
nested collections retain their local schema and candidate paths. Successful
sibling fields do not produce error entries.
(schemas/explain {pilot {age int? name string?}} {pilot {age "23" name "Chani"}}) // => #err {<schema-mismatch> // errors [{in /pilot/age // message "predicate rejected the value" // path /pilot/age // schema #builtin "int?" // value "23"}] // message "value does not match schema" // schema {pilot {age #builtin "int?" // name #builtin "string?"}} // value {pilot {age "23" // name "Chani"}}}
2.9. schemas/load
Function(schemas/load definition) → schema
Reconstructs a named schema from definition data returned by documents/value.
A self-contained definition is a (defschema name description) source form.
A definition that refers to other named schemas or predicate functions uses
a finite graph with explicit definition identities and reference bindings.
Same-named definitions in different namespaces remain distinct.
The graph records namespace paths and revisions. Its source fields describe
the snapshot's current constraints; authored_source metadata retains the
original schema code without comments. Loading uses the effective definitions
and does not execute the authored-source metadata. Missing references,
unsupported captured values, and invalid definition graphs produce errors.
A saved predicate can refer to another named schema. The snapshot records that schema's definition and identity, including scalar and function-valued schemas. Two saved predicates can retain different definitions of the same constant name. Ordinary captured runtime values are unsupported; pass candidate data as arguments instead. Structural schema cycles must descend into child values; a cycle through an opaque function capture is an error.
Literal source forms, such as a quoted (fn [x] true) or (defschema Inner 42),
remain data when a definition is loaded. Only the graph's explicit saved
function definitions are reconstructed as callable values.
A Document owns its definition data independently of the runtime that made it.
Reading or decoding the Document returns data without executing the definition.
Use schemas/load with definition data to reconstruct a runtime schema, then
use schemas/valid? to check a candidate against that schema. Pass definition
data to schemas/load, rather than an opaque Document handle. Publish named
namespace schemas with defschema. Loading runs outside namespace initialization.
(defschema Pilot {name string?}) // => Pilot (let [definition (documents/value (documents/from-value Pilot)) restored (schemas/load definition)] (schemas/valid? restored {name "Chani"})) // => true
2.10. Function contracts and generated checks
A function can put [input-schema ... => result-schema] after its parameter
list. Each arity can declare its own contract. Calls check arguments and the
returned value. A declaration states an obligation; it does not prove the body.
Contract schemas keep the bindings selected when the function is constructed.
The function reference describes variadic contracts and checked callbacks.
The compiler also infers signatures from function bodies. An exact signature has matching possible and guaranteed success regions. Unsupported behavior keeps inference approximate. schemas/check tests declared contracts or exact inferred signatures using fresh generated inputs, modeled effects and bounded work. It reports passed, failed or unsupported, with minimized failures and replay. An interrupted run cannot pass. Captured caller state and effects without a supported model are unsupported.
Use stardust test to check a file's functions from the command line. Hosts use the shared schema and signature request methods.
2.11. Database checks and presentation
Queries can explicitly select entities whose complete documents match a schema. Checked transactions validate complete post-patch entities before any facts commit. A patch may omit a required field already present in the entity. One invalid candidate rejects the transaction. These checks do not insert defaults or assign permanent types to database fields.
Encoding can take an explicit schema and presentation hints to choose field order and line layout. Presentation does not change equality, validation or canonical encoding. Schema checking, default materialization, generation, database admission and display remain explicit operations.
2.12. Custom predicates
Define a predicate as a pure function that accepts one candidate and returns
true or false. Bind it with let or def, then use it as a schema, alone
or with other constraints in a meet. For example, the positive? function
below is used in [meet int? positive?]: the candidate must be an integer and
satisfy positive?. The standard chars/ predicates are ordinary predicates
too. For example, [meet string? chars/letter?] accepts a one-code-point
string that is a Unicode letter. PEG patterns use the same predicates directly.
Use [not positive?] to require that the predicate rejects the candidate.
Any result other than true rejects the candidate, including an ordinary
error, so a function never makes a schema invalid by what it returns. An
impure predicate is an invalid schema. A predicate is an ordinary value:
lexical scope selects it, and a local binding hides a builtin of the same name.
(let [positive? (fn [value] (> value 0))] (schemas/valid? [meet int? positive?] 80)) // => true
The schema can be computed before the check. A direct schemas/valid? call
uses the predicates in scope at the call, and a schema inside a function keeps
the predicates of that function's lexical scope.
[is f arg...] calls f with the candidate first, followed by the arguments.
A list headed by a function has no special meaning: [positive?] is a
positional list of one element.
(schemas/valid? [is strings/starts-with? "spice/"] "spice/melange") // => true
Reuse a predicate in a named schema with defschema. The schema retains the
predicates selected at its definition. A predicate alone describes a check; it
does not tell schemas/materialize or schemas/fakerize how to construct a
matching value. See those operations for construction limits.
2.13. Schema algebra: meet and join
A schema describes a set of accepted values. meet takes the intersection:
a value must satisfy every operand. join takes the union: a value must
satisfy at least one operand. any accepts every value and never accepts
none. ⊤ and ⊥ are short forms for any and never.
Write [meet schemas...] or [join schemas...] inside a schema description.
Call schemas/meet or schemas/join to construct and simplify a schema value.
Both calls accept zero or more operands. An empty meet returns any; an
empty join returns never.
Both operations flatten matching combinations, remove duplicate builtin
constraints and apply any=/=never identities. They recognize a builtin kind
predicate, such as int?, by its function value, not by its name, and so do
schemas/simplify, schemas/materialize, schemas/fakerize and
schemas/check. Every other function stays opaque: it is retained, not used to
discover reductions. A named definition keeps its identity and can remain
unsimplified. Results write a builtin function in its plain-data form, such as
#builtin "int?", and a marker as #builtin "meet".
Defaults are preferences and do not change accepted values. Cyclic combinations are invalid.
Normalization has a bounded work budget; exhausting it returns a resource
error rather than a partially combined schema.
2.13.1. schemas/meet
Function(schemas/meet schemas*) → schema
Returns the intersection of its operands. Incompatible builtin constraints
reduce to never: (schemas/meet int? string?) and (schemas/meet int? [not int?])
are never. Open shapes without a name meet field by field, so
(schemas/meet {active [is = true]} {name string?}) is one shape with both
fields. A field
stays optional only when it is optional in every shape.
A meet that reduces to a literal keeps its defaults, also a default that the
literal excludes: (schemas/meet [default 1] 2) returns [meet 2 [default 1]].
The literal has given up that default, and a later join prefers an
alternative that kept it. Thus schemas/meet distributes over schemas/join,
and schemas/simplify does not change what a schema materializes.
(def D [default 8080]) // => D (def One [default 1]) // => One (def S [join [meet D int?] [meet D "auto"]]) // => S (schemas/materialize S) // => 8080 (schemas/materialize (schemas/simplify S)) // => 8080 (schemas/materialize (schemas/meet D [join int? "auto"])) // => 8080 (schemas/materialize (schemas/join (schemas/meet D int?) (schemas/meet D "auto"))) // => 8080 (schemas/meet [default 8080] "auto") // => [#builtin "meet" "auto" [#builtin "default" 8080]] (schemas/meet [default 1] 2) // => [#builtin "meet" 2 [#builtin "default" 1]] (schemas/meet [default 1] 2 int?) // => [#builtin "meet" 2 [#builtin "default" 1]] (schemas/meet [default 1] 2 string?) // => #builtin "never" (schemas/simplify [meet [default 1] 2]) // => [#builtin "meet" 2 [#builtin "default" 1]] (schemas/materialize (schemas/join (schemas/meet One 2) [meet int? One])) // => 1
(schemas/meet int? 3) // => 3 (schemas/meet int? string?) // => #builtin "never" (schemas/meet) // => #builtin "any"
2.13.2. schemas/join
Function(schemas/join schemas*) → schema
Returns a schema accepting values from any operand.
(schemas/join int? string?) // => [#builtin "join" #builtin "int?" #builtin "string?"] (schemas/join int? any) // => #builtin "any" (schemas/join) // => #builtin "never"
2.14. schemas/simplify
Function(schemas/simplify schema) → schema
Returns a simplified schema without changing its input. It reduces supported combinations at the root and within map fields, lists and collection constraints.
(schemas/simplify [join [meet int? 3] never]) // => 3 (schemas/simplify {amount [meet int? 3]}) // => {amount 3} (let [schema [meet int? 3] result (schemas/simplify schema)] [result (= schema [meet int? 3])]) // => [3 true]
Simplification changes constraints; canonical formatting controls their written representation. It validates the full input while preserving declared defaults, and retains opaque predicates rather than using them to discover reductions. Literal bound and default operands remain data. Scope-dependent and recursive definitions can remain intact; there is no guaranteed fully expanded form for every schema. Exhausting the normalization budget returns a resource error.
03 Core Functions
The core library holds every function whose name has no prefix, such as map,
+, and str. Prefixed names belong to other libraries, such as
time/now. See DUST for source notation, evaluation, and
special forms, and the Function Index for all callable entries.
Ordinary function arguments evaluate before the call. Functions can be passed
as values and called through apply. This page covers function calls,
equality, and booleans; the rest of the core library is grouped by area:
- Collections — Lists and maps: access, update, transformation, and generation.
- Order — Comparison, sorting, uniqueness, and grouping.
- Types — Type predicates, conversion, and formatting.
- Arithmetic — Operators and bounds.
- Collection library — Namespaced list, map, and path operations.
- Math library — Namespaced numeric operations.
- Hash library — Digests of DUST values.
- Bytes library — Binary values and bitwise operations.
- Encoding library — Codecs between bytes and strings.
- Random library — Seeded random generators.
3.1. apply
Function(apply function arguments) → value
Calls a function value with the elements of a list as its arguments.
Both operands are evaluated before the call.
The first must produce an ordinary function, and the second must produce a list or null.
The function is checked first, so (apply true false) gives expected a function value.
A null argument list supplies no arguments.
A string naming a function is not a function value.
Special forms and macros cannot be called through apply.
The list elements are passed as values, without evaluating them again as source.
(let [increment (fn [x] (+ 1 x))] (apply increment [4]))
(let [increment (fn [x] (+ 1 x))] (apply increment [4]))
(errors/message (apply true false)) (errors/message (apply true [1])) (errors/message (apply (fn [x] x) 5)) (errors/message (let [f (fn [a b] (apply a b))] (f true false))) (errors/message (reduce (fn [acc x] (apply acc x)) true [false []]))
"expected a function value" "expected a function value" "expected a list or null" "expected a function value" "expected a function value"
3.2. =
Function(= x) → boolean
(= x y) → boolean
(= x y more*) → boolean
Returns true if all supplied values are equal, otherwise false.
With one argument, returns true.
With no arguments, produces an arity error.
With two or more arguments, compares adjacent values from left to right.
The first unequal pair returns false without comparing later pairs.
If every pair is equal, returns true.
Each compared pair must have the same type.
A type mismatch in a pair being compared produces #err <mismatch type>.
Types are not checked in advance across all arguments.
For example, ( 1 2 "2")= returns false, but ( 1 1 "1")= produces a type error.
Integers and floats are different types, so ( 1 1.0)= produces a type error.
= is an ordinary function.
Its argument expressions are evaluated before comparison begins.
Short-circuiting skips comparisons, not argument evaluation.
Thus ( 1 2 (/ 1 0))= produces a division-by-zero error.
- Numbers of the same type compare by value.
- Links compare their signed 64-bit payloads; a link and an integer have different types.
- Lists compare positionally.
- Maps compare keys and values independently of member order.
- Functions compare by identity.
[(= 1) (= null) (= [1 2]) (= (fn [])) (= 1 1) (= 1 2) (= 1 1 1) (= 1 1 2) (= 1 2 1) (= 1 2 "2") (= 1 1 2 null) (= null null null) (= [1] [1] [1])]
(= 1) (= null) (= [1 2]) (= (fn [])) (= 1 1) (= 1 2) (= 1 1 1) (= 1 1 2) (= 1 2 1) (= 1 2 "2") (= 1 1 2 null) (= null null null) (= [1] [1] [1])
true true true true true false true false false false false true true
(let [a {x 1} b {x 1} c a] (= a b))
(let [a {x 1} b {x 1} c a] (= a b))
true
(let [a {x 1} b {x 1} c a] (= a c))
(let [a {x 1} b {x 1} c a] (= a c))
true
(let [f (fn [x] x) g f h (fn [x] x)] (= f g))
(let [f (fn [x] x) g f h (fn [x] x)] (= f g))
true
(let [f (fn [x] x) g f h (fn [x] x)] (= f h))
(let [f (fn [x] x) g f h (fn [x] x)] (= f h))
false
(let [f (fn [x] x) g f h (fn [x] x)] (= f "a"))
(let [f (fn [x] x) g f h (fn [x] x)] (= f "a"))
#err <mismatch type>
(let [f (fn [x] x) g f h (fn [x] x)] (= [f] [g]))
(let [f (fn [x] x) g f h (fn [x] x)] (= [f] [g]))
true
(let [f (fn [x] x) g f h (fn [x] x)] (= [f] [h]))
(let [f (fn [x] x) g f h (fn [x] x)] (= [f] [h]))
false
(let [f (fn [x] x) g f h (fn [x] x)] (= {callback f} {callback g}))
(let [f (fn [x] x) g f h (fn [x] x)] (= {callback f} {callback g}))
true
3.3. ==
Function(== x) → boolean
(== x y) → boolean
(== x y more*) → boolean
Is another name for the equality function. It takes the same arguments and returns the same results and errors.
3.4. not
Function(not value) → boolean
Returns true if value is null or false, otherwise false.
An error argument is the result, as for other calls. An error is falsey, so
(if (not (f)) a b) selects b when (f) returns an error. Use
error? to select a branch for an error.
(not (/ 1 0)) (if (not (/ 1 0)) "then" "else") (if (error? (/ 1 0)) "error" "value")
#err {<division integer zero> message "division by zero"} "else" "error"
3.5. Collections
These core functions build, read, and transform lists and maps. Functions that change a
collection change it in place and return it; collections/copy makes a copy to change
instead. They are part of the
core library; see DUST for source notation, evaluation, and
special forms.
3.5.1. Collection Functions
Pointers can be used where these list functions accept a list. Pointer segments are strings for keys and integers for indices.
| Function | Pointer behavior |
|---|---|
count, empty? |
Count segments or test for no segments |
first, second, last, nth |
Return one segment value |
rest, slice, take, drop |
Return a pointer containing the selected segments |
concat |
Return a pointer when the first argument is a pointer; list-first concatenation returns a list |
map, filter, reduce, some, every?, take-while, drop-while |
Iterate segment values and return the usual list-function result |
Pointers are values that do not change, so the functions that change a list, such as
lists/append, lists/reverse, and sort, reject pointers with #err <mismatch type>.
Unless stated otherwise, list operations that make a new list accept null as an empty list, and map operations that make a new map accept null as an empty map.
Functions that change a collection require a target of the stated collection type, not null.
Map keys are strings.
Callbacks receive existing values without copying. Their side effects are not undone.
3.5.1.1. map
Function(map f xs) → list
(map f xs lists*) → list
Returns a list of the results of applying f to corresponding elements of xs and any additional lists.
The function receives one argument from each input list.
Calls occur in sequence order and stop when the shortest input is exhausted.
The result is built eagerly. Inputs are lists, pointers, bytes, bitsets, or null, with
null treated as an empty list. Bytes supply their byte values, the
integers 0 to 255, and the result is a list.
[(map (fn [x] (strings/case "upper" x)) ["ada" "straße" ""]) (map :+ [1 2] [10 20 30]) (map :+ [1 2] [10] [100 200]) (map :+ [1 2] [10 20] [100] [1000 2000]) (map (fn [x] (strings/case "upper" x)) []) (map (fn [x] (strings/case "upper" x)) null) (map :+ [1] null) (map (fn [x] [x]) [1 2])]
(map (fn [x] (strings/case "upper" x)) ["ada" "straße" ""]) (map :+ [1 2] [10 20 30]) (map :+ [1 2] [10] [100 200]) (map :+ [1 2] [10 20] [100] [1000 2000]) (map (fn [x] (strings/case "upper" x)) []) (map (fn [x] (strings/case "upper" x)) null) (map :+ [1] null) (map (fn [x] [x]) [1 2])
[["ADA" "STRASSE" ""] [11 22] [111] [1111] [] [] [] [[1] [2]]]
(reduce (fn [sum x] (+ sum x)) 0 #b64 "F8gHWw==") (map (fn [x] (+ x 1)) #b64 "F8gHWw==") (map (fn [x] x) #b64 "") (map (fn [x y] (+ x y)) #b64 "AQI=" [10 20 30]) (map (fn [x] (str x)) #b64 "AAE=") (lists/filter (fn [x] (> x 50)) #b64 "F8gHWw==") (for [x #b64 "AQID"] (* x 2)) (lists/concat #b64 "AQI=" [3]) (bytes/of (map (fn [x] (- 255 x)) #b64 "AP8="))
321 [24 201 8 92] [] [11 22] ["0" "1"] [200 91] [2 4 6] [1 2 3] #b64 "/wA="
3.5.1.2. reduce
Function(reduce function initial list) → value
Starts with initial and calls function with the accumulator and each list
element, in list order. Each call's result becomes the next accumulator.
Returns the final accumulator. An empty list or null returns initial
without calling the function. The first argument must be an ordinary function
value and the third must be a list, pointer, bytes, or null. Errors stop reduction immediately: a call
that returns an #err value ends the reduction, and that value is the result.
(reduce :+ 0 [1 2 3]) (reduce :- 10 [1 2 3]) (reduce (fn [acc x] (strings/join [acc x] "")) "" ["a" "b" "c"]) (reduce :+ 9007199254740993 [1 1])
6 4 "abc" 9007199254740995
(reduce (fn [acc x] (/ 1 0)) "seed" []) (reduce :+ false null) (reduce :+ null [])
"seed" false null
3.5.1.3. patch
Function(patch map changes*) → map
Applies JSON Merge Patch member semantics to map in place and returns the same map.
All arguments must be maps, checked before any patch is applied.
With no changes maps, returns map unchanged.
Applies changes maps from left to right. Within each map, processes keys in ascending Unicode order:
nullremoves the member. A missing member is a no-op.- A map recursively patches the corresponding map. A missing or non-map destination is replaced with an empty map first.
- Any other value replaces the member without copying. Lists are replaced whole, not patched element by element.
Omitted members are unchanged. Nested patch maps are traversed, not installed by reference.
Collects the keys of each patch map before visiting its members, then reads each value when its key is processed, ignoring keys since removed.
Patch sources that alias the target observe earlier mutations.
Encountering a cycle through patch maps produces #err <invalid value> before applying the cyclic member. Earlier writes are not undone.
(patch {} a b) merges into a fresh map, and (patch (collections/copy m shallow) changes) into a copy of m.
Neither is a deep copy of the changes: null-valued members are omitted and list values are shared.
Use put to store null as a value.
(let [m {a 1}] [(patch m {a 2}) m]) (patch {} {a {b 1}} {a {c 2}}) (patch {a 1} {a null})
[[{a 2} {a 2}] {a {b 1 c 2}} {}]
(patch {items ["a" "b" "c"] keep 1} {items ["x" null] missing null}) (patch {a 1} {a {b 2 gone null}}) (patch {a {b 1 c 2}} {a {b null}})
{items ["x" null] keep 1} {a {b 2}} {a {c 2}}
3.5.1.4. seq
Function(seq value) → list
Returns the elements of a list, pointer, Bytes or Bitset as a list. A Bitset
supplies its members in ascending order. null gives an empty list.
3.5.1.5. count
Function(count collection) → integer
Returns the number of list elements, pointer segments, map members, Unicode string code points,
or bytes of a Bytes value. For null, returns zero.
(count #b64 "F8gHWw==") (count #b64 "") (count #b64 "w6k=") (empty? #b64 "") (empty? #b64 "AA==")
4 0 2 true false
For strings, count returns the number of Unicode code points. For example,
é猫 has two code points. The letter e followed by a combining acute accent
also counts as two code points.
A failed argument is the result, as for other calls: (count (map f 5)) is the
error of map, not an error of count.
(errors/message (count (lists/keep (fn [x] x) 0))) (errors/message (count (map (fn [x] x) 5))) (errors/message (count (lists/filter (fn [x] x) true)))
"expected a list or null" "expected a list or null" "expected a list or null"
3.5.1.6. empty?
Function(empty? collection) → boolean
Returns whether count is zero. Lists, pointers, maps, strings, bytes, and null are accepted.
(errors/message (empty? (lists/keep (fn [x] x) 0))) (errors/message (empty? (map (fn [x] x) 5))) (errors/message (empty? (lists/filter (fn [x] x) 1.5)))
"expected a list or null" "expected a list or null" "expected a list or null"
3.5.1.7. first
Function(first list) → value
Returns the first element or pointer segment, or null when empty.
3.5.1.8. rest
Function(rest list) → list
Returns a fresh sequence without the first element. A pointer produces a
pointer; an empty list produces [] and an empty pointer produces the root pointer.
(rest ["a" "b" "c"]) (rest ["a"]) (rest []) (rest null) (rest ["a" null false]) (rest ["a" ["b" "c"] {name "Ada"}]) (let [list ["a" "b" "c"]] [(rest list) list])
[["b" "c"] [] [] [] [null false] [["b" "c"] {name "Ada"}] [["b" "c"] ["a" "b" "c"]]]
{boolean (rest false) extra (rest ["a" "b"] 1) map (rest {a 1 b 2}) missing (rest) number (rest 2) string (rest "abc")}
#cases [{output #err <mismatch type> select "string"} {output #err <mismatch type> select "map"} {output #err <mismatch type> select "number"} {output #err <mismatch type> select "boolean"} {output #err <arity mismatch> select "missing"} {output #err <arity mismatch> select "extra"}]
3.5.1.9. jsonptr
Function(jsonptr text) → pointer
Converts RFC 6901 text to a pointer. The empty string gives the root pointer;
a nonempty string must start with / and contain only valid ~0 and ~1
escapes. Invalid text gives #err <invalid value>; a non-string gives
#err <mismatch type>.
3.5.1.10. get
Function(get root path) → value
(get root path default) → value
Returns the value selected by path in root, or default if an entry is missing.
Without default, a missing entry returns null.
A selected value of null or false is returned unchanged, not replaced by default.
get does not modify root or copy the selected value.
A map or list in callee position calls get with itself as root: see Calling a map or list.
In a packed math value, an index selects a part and a string swizzles a vector: see Destructuring and lookup.
A missing key or out-of-range nonnegative list index returns the default, including during nested traversal.
An empty path returns root.
(get {name "Ada"} "name") (get {settings {theme "dark"}} (jsonptr "/settings/theme")) (get {users [{name "Ada"} {name "Bea"}]} ["users" 1 "name"]) (get {} "theme" "default")
"Ada" "dark" "Bea" "default"
An integer index into a Bytes value selects the byte there, an integer from 0 to 255.
(get #b64 "F8gHWw==" 0) (get #b64 "F8gHWw==" 3) (get #b64 "F8gHWw==" 4) (get #b64 "F8gHWw==" 4 "none") (get #b64 "AP8=" 1) (get #b64 "F8gHWw==" [1]) (contains? #b64 "F8gHWw==" 3) (contains? #b64 "F8gHWw==" 4) (first #b64 "F8gHWw==") (first #b64 "") (lists/last #b64 "F8gHWw==") (lists/nth #b64 "F8gHWw==" 1) (get #b64 "F8gHWw==" "a") (get #b64 "F8gHWw==" -5)
23 91 null "none" 255 200 true false 23 null 91 200 #err {<mismatch type> message "lists require integer indices"} null
3.5.1.11. put
Function(put root path value) → collection
Stores value at path in root in place and returns the same root collection.
Inserts or replaces a map entry, or replaces an existing list element.
A list index equal to its length appends one element. Larger indices are errors.
Values replace rather than merge, and null is stored rather than deleted.
Creates maps, never lists, for missing or null intermediate values.
Integer path segments require an existing list.
The root must be a map or list, not null.
An empty path is an error.
Path, type, and bounds errors leave the target unchanged.
value is stored without copying, so a collection reachable from more than one place shows the change in each.
Use collections/copy to change a copy instead.
(let [user {name "Ada"}] [(put user "name" "Bea") user]) (put {settings {theme "light"}} (jsonptr "/settings/theme") "dark") (put {users [{name "Ada"}]} ["users" 0 "name"] "Bea")
[[{name "Bea"} {name "Bea"}] {settings {theme "dark"}} {users [{name "Bea"}]}]
(let [user {name "Ada"} changed (put (collections/copy user) "name" "Bea")] [user changed]) (let [root {settings {theme "light"}} changed (put (collections/copy root) (jsonptr "/settings/theme") "dark")] [root changed]) (let [root {users [{name "Ada"}]} changed (put (collections/copy root "shallow") ["users" 0 "name"] "Bea")] [root changed]) (let [root {users [{name "Ada"}]} changed (put (collections/copy root "shallow") "users" [])] [root changed])
(let [user {name "Ada"} changed (put (collections/copy user) "name" "Bea")] [user changed]) (let [root {settings {theme "light"}} changed (put (collections/copy root) (jsonptr "/settings/theme") "dark")] [root changed]) (let [root {users [{name "Ada"}]} changed (put (collections/copy root "shallow") ["users" 0 "name"] "Bea")] [root changed]) (let [root {users [{name "Ada"}]} changed (put (collections/copy root "shallow") "users" [])] [root changed])
[[{name "Ada"} {name "Bea"}] [{settings {theme "light"}} {settings {theme "dark"}}] [{users [{name "Bea"}]} {users [{name "Bea"}]}] [{users [{name "Ada"}]} {users []}]]
A change is visible through every value that shares the changed collection:
(let [original {profile {name "Ada"} settings {theme "dark"}} renamed (put (collections/copy original "shallow") "profile" {name "Bea"})] (put renamed ["settings" "theme"] "light") [original renamed])
(let [original {profile {name "Ada"} settings {theme "dark"}} renamed (put (collections/copy original "shallow") "profile" {name "Bea"})] (put renamed ["settings" "theme"] "light") [original renamed])
{profile {name "Ada"} settings {theme "light"}} {profile {name "Bea"} settings {theme "light"}}
3.5.1.12. remove
Function(remove root path) → collection
Removes the entry selected by path from root in place and returns the same root collection.
Removes a map member or a list element, shifting later list elements left.
Empty parent collections are not removed.
A missing key, out-of-range nonnegative index, or missing or null intermediate value leaves root unchanged.
No containers are created.
The root must be a map or list, not null.
An empty path produces #err <invalid value>.
Path and type errors leave the target unchanged.
(let [m {a "b"}] [(remove m "a") m]) (let [m {}] [(remove m "a") m]) (let [m {a {b 1}}] [(remove m (jsonptr "/a/b")) m])
[[{} {}] [{} {}] [{a {}} {a {}}]]
(let [m {a 1 b 2} changed (remove (collections/copy m) "a")] [m changed]) (let [m {a {b 1 c 2}} changed (remove (collections/copy m) (jsonptr "/a/b"))] [m changed]) (let [m {a {b 1 c 2}} changed (remove (collections/copy m "shallow") (jsonptr "/a/b"))] [m changed]) (let [xs ["Ada" "Bea"] changed (remove (collections/copy xs) 0)] [xs changed])
[[{a 1 b 2} {b 2}] [{a {b 1 c 2}} {a {c 2}}] [{a {c 2}} {a {c 2}}] [["Ada" "Bea"] ["Bea"]]]
3.5.1.13. contains?
Function(contains? root path) → boolean
Returns true if path selects a value in root, including null or false, otherwise false.
(contains? {x null} "x") (contains? {<!x>} "x") (contains? {} "x")
(contains? {x null} "x") (contains? <!x> "x") (contains? {} "x")
true true false
(contains? {a null} "a") (contains? <!a> (jsonptr "/a")) (contains? {a {b 1}} ["a" "b"]) (contains? ["a" "b"] 1) (contains? {a 1} "missing") (contains? {a {}} ["a" "b"]) (contains? ["a" "b"] 2) (contains? {a/b null} "a/b") (contains? <!/a> ["/a"]) (contains? <!/a> (jsonptr "/~1a")) (contains? {users [{name null}]} ["users" 0 "name"]) (contains? {users [{name null}]} (jsonptr "/users/0/name")) (contains? {"" null} "") (contains? {} []) (contains? [] []) (contains? null "a")
true true true true false false false true true true true true true true true false
{escaped-token (jsonptr "/~2") extra (contains? {} "a" false) list-key (contains? ["a"] ["0"]) map-index (contains? {a 1} [0.5]) missing (contains?) missing-path (contains? {}) path-type (contains? {a 1} true) scalar-intermediate (contains? {a 1} ["a" "b"])}
#cases [{output #err <mismatch type> select "path-type"} {output #err <invalid value> select "escaped-token"} {output #err <mismatch type> select "map-index"} {output #err <mismatch type> select "list-key"} {output #err <mismatch type> select "scalar-intermediate"} {output #err <arity mismatch> select "missing"} {output #err <arity mismatch> select "missing-path"} {output #err <arity mismatch> select "extra"}]
3.5.1.15. values
Function(values map) → list
Returns map values in the same ascending key order used by keys.
3.5.1.16. pairs
Function(pairs map) → list
Returns [key value] pairs in the same ascending key order used by keys.
(pairs {a 2 z 1}) (pairs {}) (pairs {a null}) (pairs null) (pairs {<!""> /a 1 a/b 2})
[[["a" 2] ["z" 1]] [] [["a" null]] [] [["" false] ["/a" 1] ["a/b" 2]]]
{extra (pairs {} {}) list (pairs ["a" 1]) missing (pairs) string (pairs "abc")}
#cases [{output #err <mismatch type> select "list"} {output #err <mismatch type> select "string"} {output #err <arity mismatch> select "missing"} {output #err <arity mismatch> select "extra"}]
3.5.1.17. from-pairs
Function(from-pairs list) → map
Returns a fresh map from [key value] pairs in list.
Later duplicate keys win.
(from-pairs [["b" 2] ["a" 1]]) (from-pairs []) (from-pairs null) (from-pairs [["a" 1] ["b" 2] ["a" 3]]) (from-pairs [["a" 1] ["a" null] ["b" false]]) (from-pairs [["" 0] ["/a" 1] ["a/b" 2]]) (from-pairs [["nested" {a 1}] ["items" [1 2]]]) (from-pairs (pairs {<!z> a null nested {b 2}})) (pairs (from-pairs [["z" 1] ["a" 2] ["z" 3]]))
{a 1 b 2} {} {} {a 3 b 2} {<!b> a null} {"" 0 /a 1 a/b 2} {items [1 2] nested {a 1}} {<!z> a null nested {b 2}} [["a" 2] ["z" 3]]
{empty-pair (from-pairs [[]]) extra (from-pairs [] []) later-invalid-pair (from-pairs [["a" 1] ["b"]]) list-key (from-pairs [[["a"] 1]]) long-pair (from-pairs [["a" 1 2]]) map (from-pairs {a 1}) map-pair (from-pairs [{a 1}]) missing (from-pairs) non-pair (from-pairs [1]) null-key (from-pairs [[null "a"]]) null-pair (from-pairs [null]) number-key (from-pairs [[1 "a"]]) short-pair (from-pairs [["a"]]) string (from-pairs "abc") string-pair (from-pairs ["ab"])}
#cases [{output #err <mismatch type> select "map"} {output #err <mismatch type> select "string"} {output #err <mismatch type> select "non-pair"} {output #err <mismatch type> select "map-pair"} {output #err <mismatch type> select "string-pair"} {output #err <invalid value> select "empty-pair"} {output #err <invalid value> select "null-pair"} {output #err <invalid value> select "short-pair"} {output #err <invalid value> select "long-pair"} {output #err <mismatch type> select "number-key"} {output #err <mismatch type> select "null-key"} {output #err <mismatch type> select "list-key"} {output #err <invalid value> select "later-invalid-pair"} {output #err <arity mismatch> select "missing"} {output #err <arity mismatch> select "extra"}]
3.5.1.18. pack
Macro(pack members) → map
Builds a map from locals that have the same names as its keys.
The argument is written as a map. A tag reads the local with the same name as its key,
thus (pack <name spice>) is {name name spice spice}.
Other members stay as written and are evaluated as in any map.
A tag group as a value is a literal map of true members. It does not read locals, and pack supplies that operation.
(let [name "Chani" spice 80] (pack <name spice>)) (let [name "Chani" spice 80 crew ["Stilgar"]] (pack {<name spice> count 1 first (first crew)})) (let [name "Chani"] (= (pack <name>) {name name})) (pack {}) (macroexpand-1 `(pack {<name spice> unit "kg"}))
{name "Chani" spice 80} {count 1 first "Stilgar" name "Chani" spice 80} true {} {name name spice spice unit "kg"}
A tag is a member whose value is true. Thus {<a> done true} is the same data as <a done>, and pack reads the local done.
Write a literal true in an ordinary map.
A let, fn or for binding with the name pack shadows the macro, as it does for every macro.
A top-level def with that name does not shadow it, as for the other core macros.
(let [pack (fn [m] (count m))] (pack <a b>)) (let [done 5 a 1] (pack <a done>))
2 {a 1 done 5}
A name with no binding gives that member #err <name unbound>, as a reference does in any map.
A negated tag, an argument that is not written as a map, and a wrong number of arguments are #err <invalid program>.
{list (pack [1 2]) negated (let [name 1] (pack <!name>)) none (pack) two (let [a 1] (pack <a> <a>))}
#cases [{output #err <invalid program> select "negated"} {output #err <invalid program> select "list"} {output #err <invalid program> select "none"} {output #err <invalid program> select "two"}]
3.6. Ordering
These core functions compare values, sort lists, remove duplicates, and group values by key. They are part of the core library; see DUST for source notation, evaluation, and special forms.
3.6.1. Ordering, uniqueness, and grouping
3.6.1.1. compare
Function(compare first second) → integer
Returns -1, 0, or 1 when first sorts before, ties with, or sorts after second, using sort ordering.
(compare 2 5) (compare 5 5) (compare 5 2) (compare "a" "b") (compare "猫" "é") (compare false true) (compare true false) (compare null null) (compare 1.5 2.5) (compare -0.0 0.0) (compare #link 2 #link 1) (compare 9007199254740992 9007199254740993)
-1 0 1 -1 1 -1 1 0 -1 0 1 -1
{extra-argument (compare 1 2 3) functions (compare (fn [x] x) (fn [x] x)) lists (compare [1] [1]) maps (compare {a 1} {a 1}) mixed-numbers (compare 1 1.0) mixed-scalars (compare "a" 1) no-arguments (compare) null-and-value (compare null 1) one-argument (compare 1)}
#cases [{output #err <mismatch type> select "mixed-numbers"} {output #err <mismatch type> select "mixed-scalars"} {output #err <mismatch type> select "null-and-value"} {output #err <mismatch type> select "lists"} {output #err <mismatch type> select "maps"} {output #err <mismatch type> select "functions"} {output #err <arity mismatch> select "no-arguments"} {output #err <arity mismatch> select "one-argument"} {output #err <arity mismatch> select "extra-argument"}]
3.6.1.2. sort
Function(sort list) → list
(sort comparator list) → list
Sorts list in place, stably, and returns the same list, without copying its elements.
The list's order changes only after all comparisons succeed.
list must be a list, not null or a pointer.
By default, sorts in ascending order and requires all elements to have the same kind.
Orderable kinds are null, boolean, integer, float, string, link, UTC, duration,
SHA-256, and pointer. Pointer segments compare lexicographically, with an
index before a key; a shorter prefix sorts before its extension. Integers and
nominal integer payloads compare exactly. Strings
compare by Unicode code point order, booleans put false before true, and
SHA-256 values compare their bytes. Null values tie.
Equal values keep their input order. With default ordering, compound values, functions, expression forms, and mixed kinds are errors, including in singleton lists.
A supplied comparator receives two elements and returns a negative integer, zero, or a positive integer when the first sorts before, ties with, or sorts after the second.
Custom comparators can order any element kinds.
A non-function comparator produces #err <expected function>. A non-integer result produces #err <mismatch type>.
Comparator errors stop sorting and are returned.
The comparator must define a consistent order and must not change the input list or the values being compared.
Its call order and call count are not guaranteed.
(sort [3 1 2]) (sort ["猫" "é" "a"]) (sort [false true false]) (sort [#link 2 #link 1]) (sort [null null])
[[1 2 3] ["a" "é" "猫"] [false false true] [#link 1 #link 2] [null null]]
(let [xs [3 1 2]] [(sort xs) xs]) (let [xs []] [(sort xs) xs]) (let [xs [2 1 2]] [(sort xs) xs])
[[[1 2 3] [1 2 3]] [[] []] [[1 2 2] [1 2 2]]]
(sort (fn [a b] (- b a)) [1 3 2]) (sort (fn [a b] (- (get a "rank") (get b "rank"))) [{id "a" rank 2} {id "b" rank 1} {id "c" rank 2}])
(sort (fn [a b] (- b a)) [1 3 2]) (sort (fn [a b] (- (get a "rank") (get b "rank"))) [{id "a" rank 2} {id "b" rank 1} {id "c" rank 2}])
[[3 2 1] [{id "b" rank 1} {id "a" rank 2} {id "c" rank 2}]]
3.6.1.3. distinct
Function(distinct list) → list
Returns a fresh list retaining the first occurrence of each distinct typed
value. Collections compare structurally, with map member order ignored.
Kinds remain distinct: integer 1 and float 1.0 are separate values.
Functions compare by identity. Positive and negative floating zero compare equal.
(distinct [1 1.0 1 1.0]) (distinct [{a 1 b 2} {a 1 b 2} ["a"] ["a"]]) (distinct [null false null false]) (let [f (fn [] 1) g (fn [] 1)] (count (distinct [f f g])))
[[1 1.0] [{a 1 b 2} ["a"]] [null false] 2]
3.6.2. Ordered comparisons
The ordered comparisons accept the same scalar kinds as sort and require
matching kinds. They require at least two arguments and validate every
argument's kind before comparing adjacent pairs from left to right. As ordinary
functions, all argument expressions evaluate before comparison begins.
3.6.2.1. <
Function(< first second more*) → boolean
Returns whether the arguments are strictly increasing.
3.6.2.2. <=
Function(<= first second more*) → boolean
Returns whether the arguments are nondecreasing.
3.6.2.3. >
Function(> first second more*) → boolean
Returns whether the arguments are strictly decreasing.
3.6.2.4. >=
Function(>= first second more*) → boolean
Returns whether the arguments are nonincreasing.
3.7. Types
These core functions test and convert values. They are part of the core library; see DUST for source notation, evaluation, and special forms.
3.7.1. Type Predicates
For structural validation, named definitions and generated checking, see Schemas and contracts.
3.7.1.1. error?
Function(error? value) → boolean
Returns true if value is an error and false otherwise. error? receives
an error argument; a call of most other functions returns it (see
Evaluation).
[(error? #err "app/oh-no") (error? (/ 1 0)) (error? (= 1 1.0)) (error? (=)) (let [inspect :error?] (inspect (/ 1 0))) (error? null) (error? false) (error? true) (error? 0) (error? 1.0) (error? "") (error? "dust/type-mismatch") (error? "#err dust/type-mismatch") (error? []) (error? {}) (error? {error "dust/type-mismatch"}) (error? (fn [] null)) (error? `name)]
(error? #err "app/oh-no") (error? (/ 1 0)) (error? (= 1 1.0)) (error? (=)) (let [inspect :error?] (inspect (/ 1 0))) (error? null) (error? false) (error? true) (error? 0) (error? 1.0) (error? "") (error? "dust/type-mismatch") (error? "#err dust/type-mismatch") (error? []) (error? {}) (error? {error "dust/type-mismatch"}) (error? (fn [] null)) (error? `name)
true true true true true false false false false false false false false false false false false false
3.7.1.2. null?
Function(null? x) → boolean
Returns true if x is null, otherwise false.
[(null? null) (null? "nil") (null? "null") (null? false)]
(null? null) (null? "nil") (null? "null") (null? false)
true false false false
3.7.1.3. string?
Function(string? s) → boolean
Returns true if s is a string, otherwise false.
[(string? "nil") (string? "") (string? "42") (string? null) (string? 42)]
(string? "nil") (string? "") (string? "42") (string? null) (string? 42)
true true true false false
3.7.1.5. bytes?
Function(bytes? value) → boolean
Returns true if value is a Bytes value, otherwise false.
(bytes? #b64 "aGk=") (bytes? #b64 "") (bytes? (bytes/concat)) (bytes? "aGk=") (bytes? [104 105]) (bytes? null) (bytes? #hash #xxh3-64 "78af5f94892f3950") (string? #b64 "aGk=") (list? #b64 "aGk=")
true true true false false false false false false
3.7.1.6. int?
Function(int? n) → boolean
Returns true if n is an integer, otherwise false.
A link scalar is not an integer.
[(int? 0) (int? -42) (int? 1.0) (int? 1e0) (int? "42") (int? (+ 1 2))]
(int? 0) (int? -42) (int? 1.0) (int? 1.0) (int? "42") (int? (+ 1 2))
true true false false false true
3.7.1.7. float?
Function(float? n) → boolean
Returns true if n is a floating-point number, otherwise false.
[(float? 1.0) (float? 1e0) (float? 1) (float? "1.0")]
(float? 1.0) (float? 1.0) (float? 1) (float? "1.0")
true true false false
3.7.1.8. number?
Function(number? n) → boolean
Returns true if n is an integer or a float, otherwise false.
A link scalar is not a number.
[(number? 1) (number? 1.5) (number? "1") (number? true) (number? null)]
(number? 1) (number? 1.5) (number? "1") (number? true) (number? null)
true true false false false
3.7.1.9. jsonptr?
Function(jsonptr? value) → boolean
Returns true for a pointer and false for other values. A pointer is not a
list, even though the list functions accept it.
(jsonptr? /a) ; true
(jsonptr? "/a") ; false
3.7.1.10. list?
Function(list? xs) → boolean
Returns true if xs is a list, otherwise false.
[(list? []) (list? [1]) (list? {}) (list? null)]
(list? []) (list? [1]) (list? {}) (list? null)
true true false false
3.7.1.11. map?
Function(map? m) → boolean
Returns true if m is a map, otherwise false.
[(map? {}) (map? {name "Ada"}) (map? []) (map? null)]
(map? {}) (map? {name "Ada"}) (map? []) (map? null)
true true false false
3.7.1.12. boolean?
Function(boolean? b) → boolean
Returns true if b is either true or false, otherwise false.
[(boolean? true) (boolean? false) (boolean? null) (boolean? "true") (boolean? 0)]
(boolean? true) (boolean? false) (boolean? null) (boolean? "true") (boolean? 0)
true true false false false
3.7.1.13. template?
Function(template? value) → boolean
Returns true if value is a string template, otherwise false.
(let [t (templates/from-parts {strings ["hello-" ""] values ["Ada"]})] [(template? t) (string? t) (template? "hello-Ada") (templates/parts t) (str t) (strings/starts-with? t "hello") (= t "hello-Ada") (count t) (strings/join [t "!"] "") (compare t "hello-Ada") (get {hello-Ada 42} t)]) (templates/render (templates/from-parts {strings ["hello-" ""] values ["<Ada>"]}) {escape (strings/escape "html-text")}) (let [name "Ada"] #template [["hello-" ""] [name]]) #template [["outer-" ""] [#template [["inner-" ""] ["Ada"]]]]
(let [t (templates/from-parts {strings ["hello-" ""] values ["Ada"]})] [(template? t) (string? t) (template? "hello-Ada") (templates/parts t) (str t) (strings/starts-with? t "hello") (= t "hello-Ada") (count t) (strings/join [t "!"] "") (compare t "hello-Ada") (get {hello-Ada 42} t)]) (templates/render (templates/from-parts {strings ["hello-" ""] values ["<Ada>"]}) {escape (strings/escape "html-text")}) (let [name "Ada"] ~"hello-,name") #template [["outer-" ""] [#template [["inner-" ""] ["Ada"]]]]
[[true true false {strings ["hello-" ""] values ["Ada"]} "hello-Ada" true true 9 "hello-Ada!" 0 42] "hello-<Ada>" "hello-Ada" "outer-inner-Ada"]
3.7.1.14. fn?
Function(fn? f) → boolean
Returns true if f is a function, otherwise false.
[(fn? (fn [] null)) (fn? :+) (fn? "+") (fn? [])]
(fn? (fn [] null)) (fn? :+) (fn? "+") (fn? [])
true true false false
3.7.1.15. local?
Function(local? v) → boolean
Returns true if v is a local reference, such as the quoted form
`name, otherwise false.
[(local? `name) (local? `:name) (local? ".name") (local? "name")]
(local? `name) (local? `:name) (local? ".name") (local? "name")
true false false false
3.7.1.16. const?
Function(const? v) → boolean
Returns true if v is a constant reference, such as the quoted form
`:name, otherwise false. A local and a constant with the same name are
not equal.
[(const? `:math/pi) (const? `math/pi) (const? :math/pi) (const? ":math/pi")]
(const? `:math/pi) (const? `math/pi) (const? :math/pi) (const? ":math/pi")
true false false false
3.7.1.17. uuid?
Function(uuid? value) → boolean
Returns true for a UUID, otherwise false. A string that spells a UUID is not one.
(uuid? #uuid "00000000-0000-4000-8000-00000000000c") (uuid? "00000000-0000-4000-8000-00000000000c") (uuid? #b64 "")
true false false
3.7.1.18. utc?
Function(utc? value) → boolean
Returns true for a UTC timestamp, otherwise false. It is the kind predicate that time/utc? also provides.
(utc? #utc "2026-01-01T00:00:00Z") (utc? #dur "PT10S") (utc? 1767225600)
true false false
3.7.1.19. duration?
Function(duration? value) → boolean
Returns true for a duration, otherwise false. It is the kind predicate that time/duration? also provides.
(duration? #dur "PT10S") (duration? #utc "2026-01-01T00:00:00Z") (duration? 10)
true false false
3.7.1.22. regex?
Function(regex? value) → boolean
Returns true for a regular expression, otherwise false. A compiled matcher is not a regular expression; see regex-matcher?.
(regex? #re "a+") (regex? (regexes/matcher #re "a+" "aaa")) (regex? "a+")
true false false
3.7.1.23. regex-matcher?
Function(regex-matcher? value) → boolean
Returns true for a compiled regular expression matcher, otherwise false.
(regex-matcher? (regexes/matcher #re "a+" "aaa")) (regex-matcher? #re "a+") (regex-matcher? "aaa")
true false false
3.7.1.25. invoke?
Function(invoke? value) → boolean
Returns true for an invocation form, such as `(f 1), otherwise false.
3.7.1.26. quote?
Function(quote? value) → boolean
Returns true for a quote form, such as the value of ``x, otherwise false.
3.7.1.27. quasiquote?
Function(quasiquote? value) → boolean
Returns true for a quasiquote form, such as the value of `~x, otherwise false.
3.7.1.28. unquote?
Function(unquote? value) → boolean
Returns true for an unquote form, such as the value of `,x, otherwise false.
3.7.1.29. unquote-splicing?
Function(unquote-splicing? value) → boolean
Returns true for an unquote-splicing form, such as the value of `,@x, otherwise false.
(unquote-splicing? `,@x) (unquote-splicing? `,x) (unquote-splicing? [x])
true false false
3.7.1.30. tagged?
Function(tagged? value) → boolean
Returns true for a tagged value, otherwise false. An error is not tagged data: error? tests for one.
3.7.2. Type Conversion
3.7.2.1. int
Function(int value) → integer
Returns an integer unchanged, truncates a float toward zero, or parses a signed decimal string exactly. String input accepts an optional ASCII sign followed by ASCII decimal digits, including leading zeros. Whitespace, decimal points, exponents, and hexadecimal notation are rejected. Values outside signed 64-bit range are errors. Booleans, null, and nominal types such as links are rejected.
(int "9007199254740993") (int -1.9) (int "+00042") (int "-9223372036854775808")
9007199254740993 -1 42 -9223372036854775808
3.7.2.2. float
Function(float value) → float
Converts an integer to a float, returns a float unchanged, or parses a signed
decimal string with an optional decimal point and exponent. Integer conversion
can lose precision; for example, integer 9007199254740993 converts to
9007199254740992.0. Whitespace, hexadecimal notation, NaN, and infinity are
rejected. Overflow is an error; underflow to zero is permitted. Booleans, null,
and nominal types such as links are rejected.
3.7.2.3. str
Function(str values*) → string
Converts zero or more values to strings and concatenates them in argument order.
It inserts no spaces or other separators.
With no arguments, returns the empty string.
Strings contribute their contents without added quotes or escaping.
A null argument contributes the empty string.
Numbers and booleans use their RON representations.
Lists, maps, and representable tagged values use canonical RON formatting.
RON has one canonical format; layout follows its normal formatting rules.
The formatter appends no terminal newline, and str uses those canonical bytes
unchanged. Line breaks in formatted collections are retained.
Collections are printed as complete values, not flattened into arguments.
Within collections, null is printed as null and strings are quoted when required to preserve their values.
str is an ordinary function.
Its arguments are evaluated before conversion.
String contents are text and are not interpreted as expressions.
(str) ; => ""
(str "a" null "b") ; => "ab"
(str "order-" 42 ".json") ; => "order-42.json"
(do [ (str [null "null" 1 true]) (str {z 2 a 1}) (str `name) (str #utc "2026-10-24T12:34:56Z") ])
(do [(str [null "null" 1 true]) (str {a 1 z 2}) (str `name) (str #utc "2026-10-24T12:34:56Z")])
""[null "null" 1 true]"" """ a 1 z 2 """ "#local name" "#utc 2026-10-24T12:34:56Z"
3.7.2.4. boolean
Function(boolean value) → boolean
Returns false if value is null or false, otherwise true.
3.7.2.5. format
Function(format template args*) → string
Returns a string by substituting args into the conversion specifications in template.
The syntax is printf-style. DUST supports %v for value conversion and
requires the argument types below.
A conversion has the form %[flags][width][.precision]conversion.
Each conversion consumes one argument in order, except %%, which consumes none.
Other text is copied unchanged.
The string template contains no embedded expressions.
| Conversion | Argument | Result |
|---|---|---|
s |
String | String contents |
v |
Any value | Text produced by str |
d, i |
Integer | Signed decimal |
o |
Integer | Unsigned octal |
x, X |
Integer | Unsigned hexadecimal, lowercase or uppercase |
f |
Float | Fixed-point decimal |
e, E |
Float | Scientific notation with e or E |
g, G |
Float | Compact decimal or scientific notation |
% |
None | A literal percent sign, written %% |
Width is a decimal minimum field width. Padding uses spaces on the left by default and never truncates a value. Width counts UTF-8 bytes, not code points or display columns.
| Flag | Applies to | Effect |
|---|---|---|
- |
All except % |
Left-align within the field |
+ |
Signed decimal and floats | Always include a sign |
| Space | Signed decimal and floats | Prefix nonnegative values with a space |
0 |
Numeric conversions | Pad with zeros after any sign or base prefix |
# |
o, x, X |
Alternate form with an octal or hexadecimal prefix |
# |
Floats | Keep the decimal point, and keep trailing zeros for g and G |
The + flag overrides the space flag, and - overrides 0.
Integer precision also overrides 0.
Flags not applicable to a conversion are errors.
Precision is a decimal count after ., with an omitted count meaning zero.
For integers it sets the minimum digit count.
For f, e, and E it sets the fractional digit count, defaulting to six.
For g and G it sets the significant digit count, defaulting to six, with zero treated as one.
These numeric conversions follow C printf formatting rules, including rounding and alternate forms.
Precision is not supported for s or v.
The %% escape accepts no flags, width, or precision.
Integer formatting preserves all 64 bits without conversion through a float.
Octal and hexadecimal conversions interpret negative integers modulo 2^64.
Floating-point formatting rounds the stored binary value, not an exact decimal value.
Numeric output uses . as the decimal point and no locale-specific grouping.
There is no implicit numeric conversion: %.2f requires a float, so integer 42 is an error.
The s conversion requires a string, while v accepts any value, including null as the empty string.
Dynamic width or precision (*), positional arguments ($), length modifiers,
and conversions not listed above are unsupported.
Invalid specifications produce #err <invalid value>.
An incompatible argument type, including a non-string template, produces #err <mismatch type>.
Missing or extra arguments produce #err <arity mismatch>.
Formatting, field widths, and precision are subject to the execution and output resource limits.
(format "Hello, %s!" "Ada") (format "Invoice %04d: %.2f EUR" 7 12.5) (format "Progress: %d%%" 75) (format "Result: %v" {count 3})
"Hello, Ada!" "Invoice 0007: 12.50 EUR" "Progress: 75%" "Result: {count 3}"
3.8. Arithmetic
These core functions provide arithmetic. They are part of the core library; see DUST for source notation, evaluation, and special forms.
3.8.1. Arithmetic
Arithmetic proceeds from left to right.
Links are not numbers and are rejected by numeric operations.
Numbers never convert implicitly: the numeric operands of one call must be all
integers or all floats, and an integer paired with a float is a type mismatch.
Convert explicitly with float or int.
Integer overflow and non-finite floating-point results are errors.
The shared operators also support the explicit temporal combinations below. UTC and duration values retain their nominal types and signed 100 ns tick precision. A number never becomes an implicit duration.
| Operation | Result |
|---|---|
| UTC + duration; duration + UTC | UTC |
| Duration + duration | Duration |
| UTC - duration | UTC |
| UTC - UTC; duration - duration | Duration |
| Duration * integer; integer * duration | Duration |
| Duration / integer | Duration, truncated toward zero |
| Duration / duration | Float ratio |
Other temporal combinations are type errors. See the Time library for temporal examples and bounds.
3.8.1.1. +
Function(+) → integer
(+ value) → value
(+ value other more*) → value
Returns the sum of its arguments.
With no arguments, returns 0.
With one argument, returns that numeric or temporal value unchanged.
[(+) (+ 7) (+ 1 2 3) (+ 1.0) (+ 1.0 2.5) (+ -2 2)]
(+) (+ 7) (+ 1 2 3) (+ 1.0) (+ 1.0 2.5) (+ -2 2)
0 7 6 1.0 3.5 0
3.8.1.2. -
Function(- value more*) → value
With one argument, returns its negation. With additional arguments, subtracts each from the running result in order. At least one argument is required. Numeric operands follow the arithmetic rules above; temporal operands use the combinations in the table. Integer overflow and non-finite floating-point results are errors, including when negating the minimum integer. Unary subtraction also negates durations; UTC timestamps cannot be negated.
(- 3) (- 10 3 2) (- 10.0 2.5) (- -9007199254740993) (- 9007199254740995 1 1) (- 0)
-3 5 7.5 9007199254740993 9007199254740993 0
3.8.1.3. *
Function(*) → integer
(* value) → value
(* value other more*) → value
Returns the product of its arguments.
With no arguments, returns 1.
With one argument, returns that number or duration unchanged.
[(*) (* 7) (* 2 3 4) (* 1.0) (* 2.0 1.5) (* -2 0)]
(*) (* 7) (* 2 3 4) (* 1.0) (* 2.0 1.5) (* -2 0)
1 7 24 1.0 3.0 0
3.8.1.4. /
Function(/ n) → float
(/ value divisor more*) → value
Returns n divided by d and each additional divisor in more, or the reciprocal of n when called with one argument.
Numeric operands must be all integers or all floats. Numeric division proceeds from left to right and always returns a float, even for integer operands. Duration division follows the temporal combinations in the table above. A zero divisor is an error. A duration requires a divisor; unary duration reciprocals are not defined.
[(/ 2) (/ 6 3) (/ 1 2) (/ 24 2 3) (/ -2) (/ 1 3) (/ 1.0 2.0) (/ 0 2)]
(/ 2) (/ 6 3) (/ 1 2) (/ 24 2 3) (/ -2) (/ 1 3) (/ 1.0 2.0) (/ 0 2)
0.5 2.0 0.5 4.0 -0.5 0.3333333333333333 0.5 0.0
3.8.1.5. rem
Function(rem dividend divisor) → number
Returns the remainder with the sign of the dividend. Two integers produce an
exact integer remainder; otherwise the result is a float. A zero divisor is an
error. The minimum integer divided by -1 has remainder zero.
04 Comparison Functions
The comparisons/ library provides additional equality and ordering operations.
4.1. Comparison functions
4.1.1. comparisons/not=
Function(comparisons/not= value more*) → boolean
Returns the negation of the corresponding equality call. This means that not all
arguments are equal, rather than requiring every pair to differ. One argument
returns false; no arguments is an error. Equality retains its matching-kind
checks and stops comparing after the first unequal pair.
(comparisons/not= 1 2) (comparisons/not= 1 1) (comparisons/not= 1) (comparisons/not= 1 2 "x")
true false false true
4.1.2. !=
Function(!= value more*) → boolean
Is another name for comparisons/not=. It takes the same arguments and returns the same results and errors.
4.1.3. comparisons/identical?
Function(comparisons/identical? a b) → boolean
Returns true if its operands refer to the same value, otherwise false.
Errors raised at the same place with the same tags and message may be the
same value.
(let [es (map (fn [i] (/ i 0)) [1 2])] (comparisons/identical? (first es) (lists/second es))) (let [es (map (fn [s] (int s)) ["x" "y"])] (comparisons/identical? (first es) (lists/second es))) (let [es (map (fn [v] (/ 1 v)) [0 "a"])] (comparisons/identical? (first es) (lists/second es))) (comparisons/identical? (/ 1 0) (/ 2 0)) (let [es (map (fn [i] (/ i 0)) [1 2])] (= (first es) (lists/second es))) (map (fn [i] (/ i 0)) [1 2])
#err {<division integer zero> message "division by zero"} #err {<invalid value> message "expected a decimal number string"} #err {<division integer zero> message "division by zero"} #err {<division integer zero> message "division by zero"} #err {<division integer zero> message "division by zero"} [#err {<division integer zero> message "division by zero"} #err {<division integer zero> message "division by zero"}]
(let [a {x 1} b {x 1} c a] (comparisons/identical? a b))
(let [a {x 1} b {x 1} c a] (comparisons/identical? a b))
false
(let [a {x 1} b {x 1} c a] (comparisons/identical? a c))
(let [a {x 1} b {x 1} c a] (comparisons/identical? a c))
true
(let [f (fn [x] x) g f h (fn [x] x)] (comparisons/identical? f g))
(let [f (fn [x] x) g f h (fn [x] x)] (comparisons/identical? f g))
true
(let [f (fn [x] x) g f h (fn [x] x)] (comparisons/identical? f h))
(let [f (fn [x] x) g f h (fn [x] x)] (comparisons/identical? f h))
false
05 Function Utilities
The functions/ library provides function composition and adaptation.
5.1. Function utilities
5.1.1. functions/partial
Function(functions/partial f args*) → function
Returns a function that calls f with args followed by its call-time arguments.
With no fixed arguments, returns f.
((functions/partial :+ 10) 1 2) ((functions/partial :- 10) 3) ((functions/partial :+ 1 2) 3) ((functions/partial :+ 1 2)) ((functions/partial :+) 1 2 3) ((functions/partial :+ 1 2 3 4) 5 6) ((functions/partial (fn [a b c] [a b c]) null) false "x") (= (functions/partial :functions/identity) :functions/identity)
13 7 6 3 6 21 [null false "x"] true
{function ((functions/partial 1 "a") "b") missing (functions/partial) too-few ((functions/partial :functions/identity)) too-many ((functions/partial :functions/identity "a") "b")}
#cases [{output #err <arity mismatch> select "missing"} {output #err <expected function> select "function"} {output #err <arity mismatch> select "too-few"} {output #err <arity mismatch> select "too-many"}]
5.1.2. functions/comp
Function(functions/comp) → function
(functions/comp f) → function
(functions/comp f g functions*) → function
Returns a function composing its inputs right to left, passing all call arguments to the rightmost function and each result to the next.
With no inputs, returns functions/identity.
With one, returns f.
((functions/comp :functions/identity :functions/identity) "hello") ((functions/comp :count :rest) ["a" "b" "c"]) ((functions/comp (fn [x] (* x 2)) (fn [x] (+ x 1))) 3) ((functions/comp) ["a" "b"]) ((functions/comp :+) 1 2 3) ((functions/comp :functions/identity :+)) ((functions/comp (fn [x] (* x 2)) :+) 1 2 3 4) ((functions/comp (fn [x] (* x 2)) (fn [x] (+ x 1)) (fn [x] (- x 3))) 5) (= (functions/comp) :functions/identity) (= (functions/comp :+) :+)
"hello" 2 8 ["a" "b"] 6 0 20 6 true true
{identity-extra ((functions/comp) "a" "b") identity-missing ((functions/comp)) inner-arity ((functions/comp :functions/identity :functions/identity) "a" "b") inner-function ((functions/comp :functions/identity 1) "a") outer-function ((functions/comp 1 :functions/identity) "a")}
#cases [{output #err <arity mismatch> select "identity-missing"} {output #err <arity mismatch> select "identity-extra"} {output #err <expected function> select "inner-function"} {output #err <expected function> select "outer-function"} {output #err <arity mismatch> select "inner-arity"}]
5.1.3. functions/identity
Function(functions/identity value) → value
Returns value unchanged.
(functions/identity null) (functions/identity false) (functions/identity ["a" "b"]) (functions/identity {a 1}) (functions/identity 0) (functions/identity "hello") (= (functions/identity :functions/identity) :functions/identity) (let [list ["a" "b"]] (comparisons/identical? (functions/identity list) list))
null false ["a" "b"] {a 1} 0 "hello" true true
{extra (functions/identity "a" "b") missing (functions/identity)}
#cases [{output #err <arity mismatch> select "missing"} {output #err <arity mismatch> select "extra"}]
5.1.4. functions/constantly
Function(functions/constantly value) → function
Returns a function that ignores its arguments and returns value.
((functions/constantly "a")) ((functions/constantly false) 1 2) ((functions/constantly null) "x") ((functions/constantly ["a" "b"]) 1 2 3 4 5) (let [value {a 1} f (functions/constantly value)] (comparisons/identical? (f) value)) (let [f (functions/constantly "x")] [(f) (f "a") (f "a" "b")])
"a" false null ["a" "b"] true ["x" "x" "x"]
{extra (functions/constantly "a" "b") missing (functions/constantly)}
#cases [{output #err <arity mismatch> select "missing"} {output #err <arity mismatch> select "extra"}]
5.1.5. functions/juxt
Function(functions/juxt f functions*) → function
Returns a function that applies f and functions to the same arguments and returns their results in order as a list.
((functions/juxt :first :lists/last) ["a" "b" "c"]) ((functions/juxt :count :first) ["x" "y"]) ((functions/juxt :functions/identity :functions/identity) null) ((functions/juxt :functions/identity) false) ((functions/juxt :+ :*)) ((functions/juxt :+ :- :*) 8 2) ((functions/juxt :+ :* :+ :*) 1 2 3 4) ((functions/juxt (fn [x] null) (fn [x] false)) "a")
[["a" "c"] [2 "x"] [null null] [false] [0 1] [10 6 16] [10 24 10 24] [null false]]
5.1.6. functions/complement
Function(functions/complement f) → function
Returns a function that calls f with its arguments and negates the result as a boolean.
((functions/complement :empty?) []) ((functions/complement :empty?) ["a"]) ((functions/complement :functions/identity) false) ((functions/complement :functions/identity) 1) ((functions/complement :functions/identity) null) ((functions/complement :functions/identity) 0) ((functions/complement :functions/identity) []) ((functions/complement :functions/identity) "") ((functions/complement (fn [] null))) ((functions/complement :=) 1 1) ((functions/complement :=) 1 1 1 2)
false true true false true false false false true false true
{extra (functions/complement :functions/identity :functions/identity) missing (functions/complement)}
#cases [{output #err <arity mismatch> select "missing"} {output #err <arity mismatch> select "extra"}]
5.1.7. functions/fnull
Function(functions/fnull f x) → function
(functions/fnull f x y) → function
(functions/fnull f x y z) → function
Returns a function that calls f, replacing null in its first three argument positions with the supplied defaults x, y, and z.
Preserves false and does not supply missing arguments.
((functions/fnull :+ 0) null 3) ((functions/fnull :+ 0 0) null null) ((functions/fnull :functions/identity true) false) ((functions/fnull (fn [a b c] [a b c]) "x" "y" "z") null null null) ((functions/fnull (fn [a b c] [a b c]) "x") null null false) ((functions/fnull (fn [a b] [a b]) "x" "y" "z") null null) ((functions/fnull :functions/identity null) null) ((functions/fnull (fn [a b c d] [a b c d]) "x" "y" "z") null false null null)
3 0 false ["x" "y" "z"] ["x" null false] ["x" "y"] null ["x" false "z" null]
{extra-default (functions/fnull :+ 0 0 0 0) missing (functions/fnull) missing-call-argument ((functions/fnull :+ 0)) missing-second-argument ((functions/fnull :+ 0 0) null) missing-second-of-three ((functions/fnull :+ 0 0 0) null) no-default (functions/fnull :functions/identity)}
#cases [{output #err <arity mismatch> select "missing"} {output #err <arity mismatch> select "no-default"} {output #err <arity mismatch> select "extra-default"} {output #err <arity mismatch> select "missing-call-argument"} {output #err <arity mismatch> select "missing-second-argument"} {output #err <arity mismatch> select "missing-second-of-three"}]
06 Boolean predicates
The core provides predicates for boolean values.
6.1. true?
Function(true? value) → boolean
Returns true if value is the boolean true, otherwise false.
6.2. false?
Function(false? value) → boolean
Returns true if value is the boolean false, otherwise false.
07 Collection Functions
The lists/ and maps/ namespaces provide operations for each collection type.
The collections/ namespace provides operations shared by lists and maps.
Functions that change a collection change it in place and return it; functions that make a new collection share nested values with their inputs. Unless stated otherwise, operations that make a new collection accept null as an empty collection, and operations that change a collection require a target of the stated type. Map keys are strings.
7.1. List functions: lists/
7.1.1. lists/mapcat
Function(lists/mapcat f list lists*) → list
Applies f to corresponding elements of list and any additional lists, then concatenates the result lists one level deep.
Stops at the shortest input list.
(lists/mapcat (fn [x] [x x]) ["a" "b"]) (lists/mapcat (fn [x] [x]) []) (lists/mapcat (fn [x] (if (= x 0) [] [x])) [0 1 0 2]) (lists/mapcat (fn [x] [x]) null) (lists/mapcat (fn [x] null) ["a" "b"]) (lists/mapcat (fn [a b] [a b]) [1 2] ["a"]) (lists/mapcat (fn [a b c] [a b c]) [1 2] ["a" "b"] [false null]) (lists/mapcat :functions/identity [[["a"]] [["b"]]]) (lists/mapcat :functions/identity [[null false] [] [0]])
[["a" "a" "b" "b"] [] [1 2] [] [] [1 "a"] [1 "a" false 2 "b" null] [["a"] ["b"]] [null false 0]]
{list (lists/mapcat :functions/identity "abc") missing (lists/mapcat) result (lists/mapcat :functions/identity [1]) transducer (lists/mapcat :functions/identity)}
#cases [{output #err <mismatch type> select "list"} {output #err <mismatch type> select "result"} {output #err <arity mismatch> select "missing"} {output #err <arity mismatch> select "transducer"}]
7.1.2. lists/keep
Function(lists/keep f list) → list
Returns the results of applying f to each element of list, excluding null but preserving false and input order.
(lists/keep (fn [x] (if (comparisons/identical? x 0) null x)) [0 1 false 2]) (lists/keep :functions/identity [null false 1]) (lists/keep :functions/identity []) (lists/keep :functions/identity null) (lists/keep :functions/identity [null null]) (lists/keep :functions/identity [false 0 "" [] {}]) (lists/keep (fn [x] (* x 2)) [1 2 3]) (lists/keep (fn [x] [x]) ["a" "b"])
[[1 false 2] [false 1] [] [] [] [false 0 "" [] {}] [2 4 6] [["a"] ["b"]]]
{extra (lists/keep :functions/identity ["a"] ["b"]) list (lists/keep :functions/identity "abc") missing (lists/keep) transducer (lists/keep :functions/identity)}
#cases [{output #err <mismatch type> select "list"} {output #err <arity mismatch> select "missing"} {output #err <arity mismatch> select "transducer"} {output #err <arity mismatch> select "extra"}]
7.1.3. lists/nth
Function(lists/nth list index default?) → value
Returns the element at the nonnegative, zero-based integer index.
An out-of-range index returns default if supplied; otherwise it is an error.
A negative index is an error even when a default is supplied.
(lists/nth ["a" "b" "c"] 0) (lists/nth ["a" "b" "c"] 2) (lists/nth [] 0 "missing")
"a" "c" "missing"
7.1.4. lists/second
Function(lists/second list) → value
Returns the second element of list, or null if list has fewer than two elements.
(lists/second ["a" "b" "c"]) (lists/second ["a"]) (lists/second []) (lists/second null) (lists/second ["a" false]) (lists/second ["a" null "c"]) (lists/second ["a" {name "Ada"}]) (lists/second ["a" ["b" "c"]])
"b" null null null false null {name "Ada"} ["b" "c"]
{boolean (lists/second false) extra (lists/second ["a" "b"] "fallback") map (lists/second {a 1 b 2}) missing (lists/second) number (lists/second 2) string (lists/second "ab")}
#cases [{output #err <mismatch type> select "string"} {output #err <mismatch type> select "map"} {output #err <mismatch type> select "number"} {output #err <mismatch type> select "boolean"} {output #err <arity mismatch> select "missing"} {output #err <arity mismatch> select "extra"}]
7.1.5. lists/last
Function(lists/last list) → value
Returns the last element, or null for an empty list.
7.1.6. lists/append
Function(lists/append list values*) → list
Appends values to list in place as individual elements and returns the same list.
Values are stored without copying. With no additional values, leaves list unchanged.
list must be a list, not null or a pointer.
(let [xs ["a"]] [(lists/append xs "b") xs]) (let [xs []] [(lists/append xs null false) xs]) (let [xs [1 2]] [(lists/append xs 3 4) xs])
[[["a" "b"] ["a" "b"]] [[null false] [null false]] [[1 2 3 4] [1 2 3 4]]]
(lists/append [1 2] 3 4) (lists/append [] null false) (let [xs ["a"]] [(lists/append (collections/copy xs) "b") xs])
[[1 2 3 4] [null false] [["a" "b"] ["a"]]]
7.1.7. lists/concat
Function(lists/concat lists*) → list
Returns a fresh list containing the elements of each input list, in order. With no inputs, returns an empty list.
(lists/concat [1] [2 3]) (lists/concat) (lists/concat null ["a"] [])
[[1 2 3] [] ["a"]]
7.1.8. lists/interpose
Function(lists/interpose separator list) → list
Returns a fresh list with separator between adjacent elements of list.
(lists/interpose "x" ["a" "b" "c"]) (lists/interpose "x" ["a"]) (lists/interpose "x" []) (lists/interpose "x" null) (lists/interpose null ["a" "b"]) (lists/interpose false ["a" "b"]) (lists/interpose ["x" "y"] [["a"] ["b"]]) (let [list ["a" "b"]] [(lists/interpose "x" list) list])
[["a" "x" "b" "x" "c"] ["a"] [] [] ["a" null "b"] ["a" false "b"] [["a"] ["x" "y"] ["b"]] [["a" "x" "b"] ["a" "b"]]]
{boolean (lists/interpose "x" false) extra-argument (lists/interpose "x" ["a" "b"] ["c"]) map (lists/interpose "x" {a 1}) missing-list (lists/interpose "x") no-arguments (lists/interpose) string (lists/interpose "x" "abc")}
#cases [{output #err <mismatch type> select "string"} {output #err <mismatch type> select "map"} {output #err <mismatch type> select "boolean"} {output #err <arity mismatch> select "no-arguments"} {output #err <arity mismatch> select "missing-list"} {output #err <arity mismatch> select "extra-argument"}]
7.1.9. lists/interleave
Function(lists/interleave) → list
(lists/interleave list) → list
(lists/interleave list1 list2) → list
(lists/interleave list1 list2 lists*) → list
Returns a fresh list taking one element from each input list in turn, stopping at the shortest list.
Returns [] with no inputs and a shallow copy with one.
(lists/interleave ["a" "b"] [1 2]) (lists/interleave ["a" "b" "c"] [1]) (lists/interleave ["a" "b"] [1 2] ["x" "y"]) (lists/interleave [] [1 2]) (lists/interleave) (lists/interleave ["a" "b"]) (lists/interleave []) (lists/interleave null) (lists/interleave ["a" "b"] null) (lists/interleave ["a"] [1 2]) (lists/interleave ["a" "b"] [1 2] ["x"]) (lists/interleave ["a" "b"] [1 2] ["x" "y"] [true false]) (lists/interleave [null false] [["a"] {b 2}]) (let [list ["a" "b"]] [(lists/interleave list) list])
[["a" 1 "b" 2] ["a" 1] ["a" 1 "x" "b" 2 "y"] [] [] ["a" "b"] [] [] [] ["a" 1] ["a" 1 "x"] ["a" 1 "x" true "b" 2 "y" false] [null ["a"] false {b 2}] [["a" "b"] ["a" "b"]]]
{additional (lists/interleave [1] [2] "abc") boolean (lists/interleave false) first (lists/interleave "abc" [1]) map (lists/interleave {a 1}) number (lists/interleave 1) second (lists/interleave [1] "abc") string (lists/interleave "abc")}
#cases [{output #err <mismatch type> select "string"} {output #err <mismatch type> select "map"} {output #err <mismatch type> select "number"} {output #err <mismatch type> select "boolean"} {output #err <mismatch type> select "first"} {output #err <mismatch type> select "second"} {output #err <mismatch type> select "additional"}]
7.1.10. lists/flatten
Function(lists/flatten list) → list
Returns a list of the non-list elements in list, recursively expanding nested lists in order.
Empty lists contribute no elements.
Non-list elements, including maps, strings, and null, are kept unchanged.
list must be a list, otherwise produces #err <mismatch type>.
Missing or extra arguments produce #err <arity mismatch>.
(lists/flatten [1 [2 [3]] [] 4]) (lists/flatten [1 null [2]]) (lists/flatten []) (lists/flatten [[] [[]] []]) (lists/flatten [1 2 3]) (lists/flatten [["a" "a"] [false [true]]]) (lists/flatten [{items [1 [2]]} [ "hello world" #custom [3 [4]]] null])
[[1 2 3 4] [1 null 2] [] [] [1 2 3] ["a" "a" false true] [ {items [1 [2]]} "hello world" #custom [3 [4]] null]]
{boolean-input (lists/flatten false) cyclic-input (let [x [1] appended (lists/append x x)] (lists/flatten x)) cyclic-nested-input (let [x [1] y [2 x] appended (lists/append x y)] (lists/flatten y)) extra-argument (lists/flatten [1] [2]) integer-input (lists/flatten 42) map-input (lists/flatten {items [1 2]}) missing-argument (lists/flatten) null-input (lists/flatten null) string-input (lists/flatten "abc") tagged-input (lists/flatten #custom [1 2])}
#cases [{output #err <mismatch type> select "null-input"} {output #err <mismatch type> select "string-input"} {output #err <mismatch type> select "map-input"} {output #err <mismatch type> select "integer-input"} {output #err <mismatch type> select "boolean-input"} {output #err <mismatch type> select "tagged-input"} {output #err <arity mismatch> select "missing-argument"} {output #err {<invalid value> message "cyclic list cannot be flattened"} select "cyclic-input"} {output #err {<invalid value> message "cyclic list cannot be flattened"} select "cyclic-nested-input"} {output #err <arity mismatch> select "extra-argument"}]
7.1.11. lists/slice
Function(lists/slice list start end?) → list
Returns a fresh list from start up to, but excluding, end.
Indexes are nonnegative, zero-based integers. An omitted end means the list's
length. Indexes beyond the length are clamped, and an end before the start
produces an empty list.
(lists/slice ["a" "b" "c"] 1 3) (lists/slice ["a" "b" "c"] 1) (lists/slice ["a" "b"] 1 0) (lists/slice ["a" "b"] 0 9)
[["b" "c"] ["b" "c"] [] ["a" "b"]]
7.1.12. lists/take
Function(lists/take n list) → list
Returns a fresh list of the first n elements of list, or all elements if fewer are available.
(lists/take 2 ["a" "b" "c" "d"]) (lists/take 5 ["a" "b"]) (lists/take 0 ["a" "b"]) (lists/take 2 []) (lists/take -1 ["a" "b"]) (lists/take 2 null) (lists/take 1.5 ["a" "b" "c"]) (lists/take -1.5 ["a" "b"]) (lists/take 2 [null false "c"]) (let [list ["a" "b" "c"]] [(lists/take 2 list) list])
[["a" "b"] ["a" "b"] [] [] [] [] ["a" "b"] [] [null false] [["a" "b"] ["a" "b" "c"]]]
{count (lists/take "two" ["a" "b"]) extra (lists/take 1 ["a"] ["b"]) list (lists/take 1 "abc") missing (lists/take) transducer (lists/take 1)}
#cases [{output #err <mismatch type> select "count"} {output #err <mismatch type> select "list"} {output #err <arity mismatch> select "missing"} {output #err <arity mismatch> select "transducer"} {output #err <arity mismatch> select "extra"}]
7.1.13. lists/take-while
Function(lists/take-while predicate list) → list
Returns the leading elements of list for which predicate is truthy, stopping at the first falsey result.
(lists/take-while (fn [x] (< x 3)) [1 2 3 1]) (lists/take-while :functions/identity [1 false 2]) (lists/take-while :functions/identity []) (lists/take-while :functions/identity null) (lists/take-while :functions/identity [false 1]) (lists/take-while :functions/identity [0 "" [] null 1]) (lists/take-while (fn [x] true) [null false]) (lists/take-while (fn [x] (< x 3)) [1 2 3 "invalid"])
[[1 2] [1] [] [] [] [0 "" []] [null false] [1 2]]
{extra (lists/take-while :functions/identity ["a"] ["b"]) list (lists/take-while :functions/identity "abc") missing (lists/take-while) predicate (lists/take-while 1 ["a"]) transducer (lists/take-while :functions/identity)}
#cases [{output #err <expected function> select "predicate"} {output #err <mismatch type> select "list"} {output #err <arity mismatch> select "missing"} {output #err <arity mismatch> select "transducer"} {output #err <arity mismatch> select "extra"}]
7.1.14. lists/drop
Function(lists/drop n list) → list
Returns a fresh list excluding the first n elements of list.
(lists/drop 2 ["a" "b" "c" "d"]) (lists/drop 5 ["a" "b"]) (lists/drop 0 ["a" "b"]) (lists/drop 2 []) (lists/drop -1 ["a" "b"]) (lists/drop 2 null) (lists/drop 1.5 ["a" "b" "c"]) (lists/drop -1.5 ["a" "b"]) (lists/drop 1 ["a" null false]) (let [list ["a" "b" "c"]] [(lists/drop 1 list) list])
[["c" "d"] [] ["a" "b"] [] ["a" "b"] [] ["c"] ["a" "b"] [null false] [["b" "c"] ["a" "b" "c"]]]
{count (lists/drop "two" ["a" "b"]) extra (lists/drop 1 ["a"] ["b"]) list (lists/drop 1 "abc") missing (lists/drop) transducer (lists/drop 1)}
#cases [{output #err <mismatch type> select "count"} {output #err <mismatch type> select "list"} {output #err <arity mismatch> select "missing"} {output #err <arity mismatch> select "transducer"} {output #err <arity mismatch> select "extra"}]
7.1.15. lists/drop-while
Function(lists/drop-while predicate list) → list
Returns list from the first element for which predicate is falsey, skipping the preceding elements.
(lists/drop-while (fn [x] (< x 3)) [1 2 3 1]) (lists/drop-while :functions/identity [1 false 2]) (lists/drop-while :functions/identity []) (lists/drop-while :functions/identity null) (lists/drop-while :functions/identity [false 1]) (lists/drop-while :functions/identity [0 "" [] null 1]) (lists/drop-while (fn [x] true) [null false]) (lists/drop-while (fn [x] (< x 3)) [1 2 3 "invalid"])
[[3 1] [false 2] [] [] [false 1] [null 1] [] [3 "invalid"]]
{extra (lists/drop-while :functions/identity ["a"] ["b"]) list (lists/drop-while :functions/identity "abc") missing (lists/drop-while) predicate (lists/drop-while 1 ["a"]) transducer (lists/drop-while :functions/identity)}
#cases [{output #err <expected function> select "predicate"} {output #err <mismatch type> select "list"} {output #err <arity mismatch> select "missing"} {output #err <arity mismatch> select "transducer"} {output #err <arity mismatch> select "extra"}]
7.1.16. lists/partition
Function(lists/partition n list) → list
(lists/partition n step list) → list
Returns groups of up to n elements from list, starting step elements apart and including short trailing groups.
step defaults to n.
(lists/partition 2 ["a" "b" "c" "d" "e"]) (lists/partition 2 1 ["a" "b" "c"]) (lists/partition 3 []) (lists/partition 3 ["a"]) (lists/partition 2 3 ["a" "b" "c" "d" "e" "f" "g"]) (lists/partition 3 1 ["a" "b" "c" "d"]) (lists/partition 1 [null false ["a"]]) (lists/partition 2 null) (lists/partition 2 1 null) (lists/partition 9223372036854775807 ["a" "b"]) (lists/partition 2 9223372036854775807 ["a" "b" "c"])
[[["a" "b"] ["c" "d"] ["e"]] [["a" "b"] ["b" "c"] ["c"]] [] [["a"]] [["a" "b"] ["d" "e"] ["g"]] [["a" "b" "c"] ["b" "c" "d"] ["c" "d"] ["d"]] [[null] [false] [["a"]]] [] [] [["a" "b"]] [["a" "b"]]]
{empty-zero (lists/partition 0 []) extra (lists/partition 2 1 [] []) fractional-size (lists/partition 1.5 ["a"]) fractional-step (lists/partition 2 1.5 ["a"]) list (lists/partition 2 "abc") missing (lists/partition) negative-size (lists/partition -1 ["a"]) negative-step (lists/partition 2 -1 ["a"]) transducer (lists/partition 2) zero-size (lists/partition 0 ["a"]) zero-step (lists/partition 2 0 ["a"])}
#cases [{output #err <invalid value> select "zero-size"} {output #err <invalid value> select "negative-size"} {output #err <invalid value> select "zero-step"} {output #err <invalid value> select "negative-step"} {output #err <invalid value> select "empty-zero"} {output #err <mismatch type> select "fractional-size"} {output #err <mismatch type> select "fractional-step"} {output #err <mismatch type> select "list"} {output #err <arity mismatch> select "missing"} {output #err <arity mismatch> select "transducer"} {output #err <arity mismatch> select "extra"}]
7.1.17. lists/reverse
Function(lists/reverse list) → list
Reverses list in place and returns the same list, without copying the elements.
list must be a list, not null or a pointer.
(let [xs ["a" "b" "c"]] [(lists/reverse xs) xs]) (let [xs []] [(lists/reverse xs) xs]) (let [xs ["a"]] [(lists/reverse xs) xs])
[[["c" "b" "a"] ["c" "b" "a"]] [[] []] [["a"] ["a"]]]
(lists/reverse ["a" "b" "c"]) (lists/reverse []) (lists/reverse [null false])
[["c" "b" "a"] [] [false null]]
7.1.18. lists/filter
Function(lists/filter predicate list) → list
Calls predicate on each element, from left to right, and returns the elements
whose results are truthy. Retains their input order.
(lists/filter :boolean [null false 0 "a"]) (lists/filter (fn [x] (= x 2)) [1 2 2 3]) (lists/filter :boolean [])
[[0 "a"] [2 2] []]
7.1.19. lists/any?
Function(lists/any? predicate list) → boolean
Returns true at the first truthy predicate result without visiting later
elements. Returns false for an empty list.
(lists/any? :boolean [null false "a"]) (lists/any? :boolean []) (lists/any? (fn [x] (if x true (/ 1 0))) [true false])
true false true
7.1.20. lists/every?
Function(lists/every? predicate list) → boolean
Returns false at the first falsey predicate result without visiting later
elements. Returns true for an empty list.
(lists/every? :boolean [0 "a"]) (lists/every? :boolean []) (lists/every? (fn [x] (if x (/ 1 0) false)) [false true])
true true false
7.1.21. lists/some
Function(lists/some f list) → value
Returns the first truthy result of applying f to elements of list, without visiting later elements, or null if none matches.
(lists/some (fn [x] (get x "name")) [{} {name "Ada"} {name "Bea"}]) (lists/some :functions/identity [false null 0 7]) (lists/some :functions/identity [false null]) (lists/some :functions/identity []) (lists/some :functions/identity null) (lists/some :functions/identity [null false [] "a"]) (lists/some :functions/identity [false "" "a"]) (lists/some (fn [x] (if (> x 1) {found x} null)) [0 1 2 3]) (lists/some (fn [x] (if (= x 2) "yes" null)) [1 2 "invalid"])
"Ada" 0 null null null [] "" {found 2} "yes"
{extra (lists/some :functions/identity ["a"] ["b"]) function (lists/some 1 ["a"]) list (lists/some :functions/identity "abc") missing (lists/some) missing-list (lists/some :functions/identity)}
#cases [{output #err <expected function> select "function"} {output #err <mismatch type> select "list"} {output #err <arity mismatch> select "missing"} {output #err <arity mismatch> select "missing-list"} {output #err <arity mismatch> select "extra"}]
7.1.22. lists/find-first
Function(lists/find-first predicate list) → value
(lists/find-first predicate list default) → value
Returns the first element of list for which predicate is truthy, or default if none matches.
The default is null.
(lists/find-first (fn [x] (get x "name")) [{} {name "Ada"} {name "Bea"}]) (lists/find-first (fn [x] (comparisons/identical? x false)) [null false true]) (lists/find-first :functions/identity [null false]) (lists/find-first :functions/identity [] "fallback") (lists/find-first :functions/identity null) (lists/find-first :functions/identity null "fallback") (lists/find-first :functions/identity [0 1]) (lists/find-first (fn [x] true) [null] "fallback") (lists/find-first (fn [x] false) ["a" "b"] false)
{name "Ada"} false null "fallback" null "fallback" 0 null false
{extra (lists/find-first :functions/identity [] "fallback" "extra") list (lists/find-first :functions/identity "abc") missing (lists/find-first) missing-list (lists/find-first :functions/identity)}
#cases [{output #err <mismatch type> select "list"} {output #err <arity mismatch> select "missing"} {output #err <arity mismatch> select "missing-list"} {output #err <arity mismatch> select "extra"}]
7.1.23. lists/range
Function(lists/range end) → list
(lists/range start end step?) → list
Returns integers from start up to, but excluding, end, incrementing by
step. The defaults are zero for start and one for step. A negative step
produces a descending range. A zero step is an error. All arguments must be integers.
(lists/range 3) (lists/range 1 6 2) (lists/range 3 0 -1) (lists/range 3 0)
[[0 1 2] [1 3 5] [3 2 1] []]
7.1.24. lists/repeat
Function(lists/repeat count value) → list
Returns a list containing value the specified number of times. count must
be a nonnegative integer. Values are reused rather than deep copied.
(lists/repeat 3 "x") (lists/repeat 0 "x") (lists/repeat 2 null)
[["x" "x" "x"] [] [null null]]
7.1.25. lists/sort-by
Function(lists/sort-by f list) → list
(lists/sort-by f comparator list) → list
Sorts list in place, stably, by the keys returned by f, and returns the same list.
The list's order changes only after key extraction and all comparisons succeed.
list must be a list, not null or a pointer.
Calls f once per element, from left to right, before making comparisons.
The key function must be an ordinary function and must not change the input list or its elements.
Uses sort ordering, or the supplied comparator applied to the keys.
Equal keys keep their input order. Elements are shared without copying.
Key-function errors stop processing and are returned.
(lists/sort-by :first [["b" 1] ["a" 2] ["b" 3]]) (lists/sort-by :count ["abc" "a" "ab"]) (lists/sort-by :first []) (let [m {seen []}] [(lists/sort-by (fn [x] (patch m {seen (lists/append (get m "seen") x)}) x) [3 2 1]) (get m "seen")])
(lists/sort-by :first [["b" 1] ["a" 2] ["b" 3]]) (lists/sort-by :count ["abc" "a" "ab"]) (lists/sort-by :first []) (let [m {seen []}] [(lists/sort-by (fn [x] (patch m {seen (lists/append (get m "seen") x)}) x) [3 2 1]) (get m "seen")])
[[["a" 2] ["b" 1] ["b" 3]] ["a" "ab" "abc"] [] [[1 2 3] [3 2 1]]]
(let [xs ["ab" "c" "def"]] [(lists/sort-by :count xs) xs]) (let [xs []] [(lists/sort-by :count xs) xs]) (let [xs ["ab" "cd" "e"]] [(lists/sort-by :count xs) xs])
[[["c" "ab" "def"] ["c" "ab" "def"]] [[] []] [["e" "ab" "cd"] ["e" "ab" "cd"]]]
7.1.26. lists/partition-by
Function(lists/partition-by f list) → list
Returns consecutive groups from list, starting a new group whenever f returns a different value.
(lists/partition-by :functions/identity ["a" "a" "b" "a"]) (lists/partition-by :functions/identity []) (lists/partition-by (fn [x] (math/zero? x)) [0 0 1 2 0]) (lists/partition-by :functions/identity null) (lists/partition-by :functions/identity [null null false false null]) (lists/partition-by :functions/identity [["a"] ["a"] ["b"]]) (lists/partition-by (fn [x] "same") ["a" "b" "c"]) (lists/partition-by :functions/identity [1 1.0 1]) (lists/partition-by :functions/identity ["a" "b" "c"])
[[["a" "a"] ["b"] ["a"]] [] [[0 0] [1 2] [0]] [] [[null null] [false false] [null]] [[["a"] ["a"]] [["b"]]] [["a" "b" "c"]] [[1] [1.0] [1]] [["a"] ["b"] ["c"]]]
{extra (lists/partition-by :functions/identity ["a"] ["b"]) function (lists/partition-by 1 ["a"]) list (lists/partition-by :functions/identity "abc") missing (lists/partition-by) transducer (lists/partition-by :functions/identity)}
#cases [{output #err <expected function> select "function"} {output #err <mismatch type> select "list"} {output #err <arity mismatch> select "missing"} {output #err <arity mismatch> select "transducer"} {output #err <arity mismatch> select "extra"}]
7.1.27. lists/group-by
Function(lists/group-by function list) → map
Calls function on each element, from left to right. Each result must be a
string and becomes a map key. Each map value is the list of input elements
with that key, preserving their input order. Non-string keys are errors.
(lists/group-by :first [["a" 1] ["b" 2] ["a" 3]]) (lists/group-by (fn [x] (strings/case "upper" x)) ["a" "A" "b"]) (lists/group-by :first [])
{a [["a" 1] ["a" 3]] b [["b" 2]]} {A ["a" "A"] B ["b"]} {}
7.1.28. lists/frequencies
Function(lists/frequencies strings) → map
Counts each string in the input list and returns a map from strings to integer
counts. Non-string elements are errors; integer 1 is never coerced to string "1".
(lists/frequencies ["a" "b" "a"]) (lists/frequencies []) (lists/frequencies ["é" "猫" "é"])
{a 2 b 1} {} {é 2 猫 1}
7.2. Map functions: maps/
7.2.1. maps/zipmap
Function(maps/zipmap keys values) → map
Returns a fresh map pairing string keys with values, stopping at the shorter list.
Later duplicate keys win.
(maps/zipmap ["a" "b"] [1 2]) (maps/zipmap ["a" "b" "c"] [1]) (maps/zipmap ["a" "a"] [1 2]) (maps/zipmap [] [1]) (maps/zipmap ["a"] [1 2]) (maps/zipmap ["a"] []) (maps/zipmap null [1]) (maps/zipmap ["a"] null) (maps/zipmap ["a" "b" "c"] [null false [1 2]]) (maps/zipmap ["a" "a"] [1 null]) (maps/zipmap ["" "/a" "a/b"] [1 2 3])
{a 1 b 2} {a 1} {a 2} {} {a 1} {} {} {} {<!b> a null c [1 2]} {a null} {"" 1 /a 2 a/b 3}
{extra-argument (maps/zipmap ["a"] [1] [2]) integer-key (maps/zipmap [1] ["a"]) keys-not-list (maps/zipmap "a" [1]) missing-values (maps/zipmap ["a"]) no-arguments (maps/zipmap) null-key (maps/zipmap [null] ["a"]) values-not-list (maps/zipmap ["a"] 1)}
#cases [{output #err <mismatch type> select "keys-not-list"} {output #err <mismatch type> select "values-not-list"} {output #err <mismatch type> select "integer-key"} {output #err <mismatch type> select "null-key"} {output #err <arity mismatch> select "no-arguments"} {output #err <arity mismatch> select "missing-values"} {output #err <arity mismatch> select "extra-argument"}]
7.2.2. maps/select-keys
Function(maps/select-keys map keys) → map
Returns a fresh map containing the literal top-level keys in keys that are present in map.
(maps/select-keys {a 1 b 2} ["b" "missing"]) (maps/select-keys {a null} ["a" "a"]) (maps/select-keys null ["a"])
{b 2} {a null} {}
(maps/select-keys {a 1 b 2 c 3} ["a" "c"]) (maps/select-keys {/a 1 b 2} ["/a"]) (maps/select-keys {a 1} ["missing" "a"]) (maps/select-keys {/a/b 2 a {b 1}} ["/a/b"]) (maps/select-keys {<!b> a null c 3} ["b" "a" "a"]) (maps/select-keys null ["a"]) (maps/select-keys {a 1} []) (maps/select-keys {a 1} null)
{a 1 c 3} {/a 1} {a 1} {/a/b 2} {<!b> a null} {} {} {}
{extra (maps/select-keys {} [] []) key-type (maps/select-keys {a 1} [0]) keys (maps/select-keys {a 1} "a") map (maps/select-keys ["a"] ["a"]) missing (maps/select-keys) missing-keys (maps/select-keys {}) path-list (maps/select-keys {a {b 1}} [["a" "b"]])}
#cases [{output #err <mismatch type> select "map"} {output #err <mismatch type> select "keys"} {output #err <mismatch type> select "key-type"} {output #err <mismatch type> select "path-list"} {output #err <arity mismatch> select "missing"} {output #err <arity mismatch> select "missing-keys"} {output #err <arity mismatch> select "extra"}]
7.3. Collection paths: collections/
7.3.1. collections/update
Function(collections/update root path f args*) → collection
Replaces the value at path in root with the result of calling f on that value and args, in place, and returns the same root collection.
Stores the result as put does, including container creation and list growth.
A missing entry supplies null to f.
Validates the destination before calling f once, and again before storing the result.
The callback must be an ordinary function, otherwise produces #err <expected function>.
A callback error is returned without storing a replacement.
The callback receives the existing value without copying, and its side effects are not undone.
The root must be a map or list, not null.
An empty path produces #err <invalid value>.
(let [record {score 2}] (collections/update record "score" :+ 3) record) (let [record {user {score 2}}] (collections/update record ["user" "score"] :+ 3) record) (let [record {tags ["old"]}] (collections/update record "tags" :lists/append "new") record)
{score 5} {user {score 5}} {tags ["old" "new"]}
(let [record {score 2} updated (collections/update (collections/copy record) "score" :+ 3)] [record updated]) (let [record {user {score 2}} updated (collections/update (collections/copy record) ["user" "score"] :+ 3)] [record updated]) (let [record {user {score 2}} updated (collections/update (collections/copy record "shallow") ["user" "score"] :+ 3)] [record updated])
(let [record {score 2} updated (collections/update (collections/copy record) "score" :+ 3)] [record updated]) (let [record {user {score 2}} updated (collections/update (collections/copy record) ["user" "score"] :+ 3)] [record updated]) (let [record {user {score 2}} updated (collections/update (collections/copy record "shallow") ["user" "score"] :+ 3)] [record updated])
[[{score 2} {score 5}] [{user {score 2}} {user {score 5}}] [{user {score 5}} {user {score 5}}]]
7.3.2. collections/copy
Function(collections/copy value) → value
(collections/copy value shallow) → value
Returns a copy of value that changes to either leave the other unchanged.
Copies every list and map reachable from value. A list or map reached more than once is copied once, so collections shared within value stay shared within the copy, and cycles stay cycles.
With the mode shallow, copies only the top-level list or map; its members are shared.
Other values do not change and are returned as they are.
A mode other than shallow produces #err <invalid value>, and a mode that is not a string #err <mismatch type>.
A value of any depth is copied.
(let [m {a {b 1}} c (collections/copy m)] (put c ["a" "b"] 2) [m c]) (let [m {a {b 1}} c (collections/copy m "shallow")] (put c ["a" "b"] 2) (put c "x" 3) [m c]) (let [l [1 [2]] c (collections/copy l)] (lists/append c 3) (lists/append (get c 1) 4) [l c]) (let [s {n 1} m {a s b s} c (collections/copy m)] (put c ["a" "n"] 2) [(get c ["b" "n"]) (get m ["a" "n"])]) [(collections/copy 5) (collections/copy "x") (collections/copy null)] (collections/copy {a 1} "deep") (collections/copy {a 1} 5) (let [m {a 1}] (put m "self" m) (let [c (collections/copy m)] [(comparisons/identical? (get c "self") c) (comparisons/identical? (get c "self") m)]))
(let [m {a {b 1}} c (collections/copy m)] (put c ["a" "b"] 2) [m c]) (let [m {a {b 1}} c (collections/copy m "shallow")] (put c ["a" "b"] 2) (put c "x" 3) [m c]) (let [l [1 [2]] c (collections/copy l)] (lists/append c 3) (lists/append (get c 1) 4) [l c]) (let [s {n 1} m {a s b s} c (collections/copy m)] (put c ["a" "n"] 2) [(get c ["b" "n"]) (get m ["a" "n"])]) [(collections/copy 5) (collections/copy "x") (collections/copy null)] (collections/copy {a 1} "deep") (collections/copy {a 1} 5) (let [m {a 1}] (put m "self" m) (let [c (collections/copy m)] [(comparisons/identical? (get c "self") c) (comparisons/identical? (get c "self") m)]))
[[{a {b 1}} {a {b 2}}] [{a {b 2}} {a {b 2} x 3}] [[1 [2]] [1 [2 4] 3]] [2 1] [5 "x" null] #err {<invalid value> message "unknown copy mode"} #err {<mismatch type> message "copy mode must be a string"} [true false]]
08 Database query functions
8.1. defquery
Macro(defquery name [params*] query-map) → name
Defines a named function that queries the database snapshot attached to its evaluation. A result contract may follow the parameter list. Calling the function returns a list of maps unless the query requests positional tuples.
A host can subscribe to an exported query. The subscription delivers the
query's result, then a new result after each commit that changes a field that
the query reads. The ABI's queries/subscribe request and the generated SDK's
SubscribeTo methods do this. An evaluation returns one value, so DUST code
cannot subscribe.
To evaluate a file against an existing database, name the database in a
configuration file such as {plugins {stdlib true database {path "app.db"}}}:
stardust eval --config app.dust query.dust
Top-level locals persist between the file's forms. Each evaluation reads a fresh
snapshot. Plugin selection enables the same services as ordinary evaluation.
Returned values remain usable after the database
closes. Without database storage, a query returns #err <database no>. Open
the database with the database plugin and its path or temporary setting.
The query executor chooses a default clause order. The optional planner
plugin may choose a different order as it learns. Row order is defined only
by order-by. Queries with one field pattern, a limit or offset without
order-by, a window call, an each expansion, or a schema clause are not
reordered. The ABI's plans/explain request reports the chosen order without
running the query.
The examples below read the illustrative Dune database.
8.1.1. Example database
These illustrative records use Dune characters; ages, assignments and transactions are sample data.
The id identifies an entity, tags describe membership, and #link refers to another entity.
The steps lists contain patrol steps in execution order.
[
{<atreides mentor> id 1 name "Duncan Idaho" age 37 station "Arrakeen" commander #link 2 steps ["scout" "patrol" "report"]}
{<atreides> id 2 name "Leto Atreides" age 45 station "Arrakeen" steps ["patrol" "report"]}
{<fremen> id 3 name "Stilgar" age 29 station "Sietch Tabr" steps ["travel" "watch"]}
]
Unless stated otherwise, the examples read this initial snapshot. Every input and result below is checked by the query conformance tests.
8.1.2. Select fields
Return the name, age and commander of each Atreides member.
[?e <atreides>] binds ?e to each matching entity.
project {?e <name age commander>} selects those fields from the entity bound to ?e.
The map key names the query binding; its value describes the result.
(defquery example [] {where [[?e <atreides>]]
project {?e <name age commander>}})
(example)
Result:
[{name "Duncan Idaho" age 37 commander #link 2}
{name "Leto Atreides" age 45 commander null}]
Leto Atreides has no commander, so the projected commander field is null.
8.1.3. Match tags
Return the names of Atreides members:
(defquery example [] {where [[?e <atreides>]]
project {?e <name>}})
(example)
Result:
[{name "Duncan Idaho"} {name "Leto Atreides"}]
Require both atreides and mentor membership:
(defquery example [] {where [[?e <atreides mentor>]]
project {?e <name>}})
(example)
Result:
[{name "Duncan Idaho"}]
Require atreides membership and the absence of the mentor tag:
(defquery example [] {where [[?e <atreides !mentor>]]
project {?e <name>}})
(example)
Result:
[{name "Leto Atreides"}]
Select everyone without a mentor tag:
(defquery example [] {where [[?e <!mentor>]]
project {?e <name>}})
(example)
Result:
[{name "Leto Atreides"} {name "Stilgar"}]
Negated tags test absence, not a stored false value. A tag that has never been assigned is absent from every entity:
(defquery example [] {where [[?e <!unassigned>]]
project {?e <name>}})
(example)
Result:
[{name "Duncan Idaho"} {name "Leto Atreides"} {name "Stilgar"}]
Requiring that same tag selects no entities:
(defquery example [] {where [[?e <unassigned>]]
project {?e <name>}})
(example)
Result:
[]
8.1.4. Match field values
Return the names of people stationed in Arrakeen.
A field pattern is [?entity field value]:
(defquery example [] {where [[?e station "Arrakeen"]]
project {?e <name>}})
(example)
Result:
[{name "Duncan Idaho"} {name "Leto Atreides"}]
The middle slot always names a literal field: station and "station" select the same field.
It does not read a local named station.
Strings in the value slot must be quoted.
A symbol such as ?name is a query variable; "?name" is literal text.
To select people aged at least 40, bind the stored age and compare it:
(defquery example [] {where [[?e age ?age] (>= ?age 40)]
project {?e <name age>}})
(example)
Result:
[{name "Leto Atreides" age 45}]
The repeated ?e makes both clauses refer to the same entity.
Numeric comparisons require operands of the same numeric kind.
A where item that is not a field pattern, negated pattern, optional,
schema or each clause is a predicate. It can call pure functions with
query variables, declared inputs, literals and captured locals. A predicate
cannot call a host-effect function. A row is kept when the result is truthy;
an #err result fails the query. Two-operand = and comparisons/not= inside
predicates return false and true, respectively, when operand kinds differ.
Only a simple first predicate can use an index.
8.1.5. Select complete entities with a schema
Use [schema schema-value ?entity] to check each complete entity document.
The clause can enumerate entities or check an entity bound by another clause.
Each schema target listed in in is restricted to its supplied entity, including
queries with several targets. For example, ?a and ?b are both bound here:
{find [?a ?b] <tuples>
in [?schema ?a ?b]
where [[?a active ?state] [?b active ?state]
[schema ?schema ?a] [schema ?schema ?b]]
order-by [?a ?b]}
Open shapes permit fields that the schema does not name.
(defquery example [] {where [[schema {name string? age int?} ?e]]
project {?e <name>}})
(example)
Result:
[{name "Duncan Idaho"} {name "Leto Atreides"} {name "Stilgar"}]
Grouping, ordering, and paging run after the schema filter.
A missing schema value is an error, including when another clause selects no rows.
A schema value that is an error, such as an invalid schema, is the query's error:
[schema {name <nope>} ?e] fails with #err <invalid schema> and the message
"<nope> has no nope? predicate".
8.1.6. Follow a link
Return each Atreides member's name and their commander's name.
The nested commander <name> selection follows the commander link:
(defquery example [] {where [[?e <atreides>]]
project {?e {<name> commander <name>}}})
(example)
Result:
[{name "Duncan Idaho" commander {name "Leto Atreides"}}
{name "Leto Atreides" commander {name null}}]
When the link is absent, the nested name is null.
Nested pointers are relative to that linked entity: commander {label /name} names its field label.
8.1.7. Rename a returned field
Return the mentor's commander name under commander-name.
A JSON Pointer supplies the source path:
(defquery example [] {where [[?e <mentor>]]
project {?e {commander-name /commander/name}}})
(example)
Result:
[{commander-name "Leto Atreides"}]
The JSON Pointer /commander/name follows the link.
A quoted "/commander/name" would return that literal string.
Selection tags can be mixed with aliases: project {?e {<name> commander-name /commander/name}}.
8.1.8. Read an ordered list
Return the first patrol step for the mentor. JSON Pointer list indexes start at zero:
(defquery example [] {where [[?e <mentor>]]
project {?e {first-step /steps/0}}})
(example)
Result:
[{first-step "scout"}]
To return every step as a separate row, use [each ?step] in the value slot.
It binds ?step to each element of the stored list. The each symbol marks list expansion in this pattern slot.
find returns the matched variables; their names become result keys.
Sorting by person name retains each person's step order:
(defquery example [] {find [?name ?step]
where [[?e name ?name] [?e steps [each ?step]]]
order-by [?name]})
(example)
Result:
[{name "Duncan Idaho" step "scout"}
{name "Duncan Idaho" step "patrol"}
{name "Duncan Idaho" step "report"}
{name "Leto Atreides" step "patrol"}
{name "Leto Atreides" step "report"}
{name "Stilgar" step "travel"}
{name "Stilgar" step "watch"}]
Each step contributes a row, including repeated steps.
8.1.9. Sort and paginate
Return all names in alphabetical order.
The field pattern binds the name so order-by can sort on it:
(defquery example [] {where [[?e name ?name]]
order-by [?name]
project {?e <name>}})
(example)
Result:
[{name "Duncan Idaho"} {name "Leto Atreides"} {name "Stilgar"}]
To sort from highest to lowest, tag the order term with #desc: order-by [#desc ?value].
For example, return the oldest person first:
(defquery example [] {where [[?e age ?age]]
order-by [#desc ?age]
project {?e <name age>}})
(example)
Result:
[{name "Leto Atreides" age 45}
{name "Duncan Idaho" age 37}
{name "Stilgar" age 29}]
To request the second name only, skip one row and return one row. Use the entity ID to break ties between equal names:
(defquery example [] {where [[?e name ?name]]
order-by [?name ?e]
offset 1 limit 1
project {?e <name>}})
(example)
Result:
[{name "Leto Atreides"}]
offset and limit apply before projection.
Use order-by when the result order matters.
8.1.10. Supply a threshold
Use a lexical local when the surrounding expression supplies the minimum age.
minimum is that local; ?age is the matched database value:
(defquery example [minimum]
{where [[?e age ?age] (>= ?age minimum)]
project {?e <name age>}})
(example 40)
Result:
[{name "Leto Atreides" age 45}]
When the caller supplies the threshold as an evaluation binding, use :minimum.
With these bindings:
{minimum 40}
(defquery example [] {where [[?e age ?age] (>= ?age :minimum)]
project {?e <name age>}})
(example)
Result:
[{name "Leto Atreides" age 45}]
8.1.11. Count matching entities
Count people who are both Atreides members and mentors:
(defquery example [] {find [(count ?e)]
where [[?e <atreides mentor>]]})
(example)
Result:
[{count 1}]
(count ?e) produces the result key count.
Without grouping, an empty match returns [{count 0}].
8.1.12. Count by station
Return a count for each station.
Including ?station alongside the aggregate makes it the group key:
(defquery example [] {find [?station (count ?e)]
where [[?e station ?station]]
order-by [?station]})
(example)
Result:
[{station "Arrakeen" count 2} {station "Sietch Tabr" count 1}]
To keep only stations with more than one person, filter the completed counts with having:
(defquery example [] {find [?station (count ?e)]
where [[?e station ?station]]
having [(> ?count 1)]})
(example)
Result:
[{station "Arrakeen" count 2}]
The aggregate result is available to having as ?count.
8.1.13. Count people with and without a commander
Count people by commander, including those who have none.
Here the commander participates in grouping before projection.
optional preserves people whose commander field is absent and binds their commander to null:
(defquery example [] {find [?commander (count ?e)]
where [[?e name ?name] (optional [?e commander ?commander])]})
(example)
Result:
[{commander #link 2 count 1} {commander null count 2}]
Without optional, the commander pattern would exclude Leto Atreides and Stilgar before they could be counted.
To return fields without grouping or filtering on them, use project as in the first example.
8.1.14. Rank rows inside a group
A window call in find computes one value per row from the rows around it.
It is a function call whose last argument is an options map: (rank {partition-by [?station] order-by [#desc ?age]}).
A known function name with a trailing map is a window call only when the map is empty or holds only as, partition-by, order-by and frame.
Any other map leaves an ordinary call: (first {a 1}) calls first on the map, and the misspelled (rank {partiton-by [?t]}) reports rank as a call to a function that does not exist.
partition-by groups the rows; order-by sorts each group; the result key is the function name.
Return each person's age rank within their station, oldest first:
(defquery example [] {find [?name ?station (rank {partition-by [?station] order-by [#desc ?age]})]
where [[?e name ?name] [?e station ?station] [?e age ?age]]
order-by [?station ?name]})
(example)
Result:
[{name "Duncan Idaho" station "Arrakeen" rank 2}
{name "Leto Atreides" station "Arrakeen" rank 1}
{name "Stilgar" station "Sietch Tabr" rank 1}]
Without partition-by, one partition holds every row.
An order term is ?age (ascending) or #desc ?age; no other spelling is accepted, here or in the query's order-by.
Equal order values share a rank; dense-rank numbers distinct values; row-number numbers every row.
A frame bounds the rows a fold reads.
With order-by, the default frame runs from the partition's start to the current row.
Without order-by, the frame is the whole partition.
Return a running total of ages in name order:
(defquery example [] {find [?name ?age (sum ?age {order-by [?name]})]
where [[?e name ?name] [?e age ?age]]
order-by [?name]})
(example)
Result:
[{name "Duncan Idaho" age 37 sum 37}
{name "Leto Atreides" age 45 sum 82}
{name "Stilgar" age 29 sum 111}]
frame {rows {from unbounded-preceding to unbounded-following}} reads the whole partition despite an order-by; frame {rows {from unbounded-preceding to current-row}} spells the running frame.
lag and lead read a value from an earlier or later row of the partition.
The second argument is the row distance (default 1); the third is the value for rows that have no such neighbor (default null):
(defquery example [] {find [?name ?age (lag ?age 1 0 {order-by [?name]})]
where [[?e name ?name] [?e age ?age]]
order-by [?name]})
(example)
Result:
[{name "Duncan Idaho" age 37 lag 0}
{name "Leto Atreides" age 45 lag 37}
{name "Stilgar" age 29 lag 45}]
Folds without order-by read their whole partition.
Return the size and mean age of each person's station beside the person:
(defquery example [] {find [?name (count ?e {partition-by [?station]}) (mean ?age {partition-by [?station]})]
where [[?e name ?name] [?e station ?station] [?e age ?age]]
order-by [?name]})
(example)
Result:
[{name "Duncan Idaho" count 2 mean 41.0}
{name "Leto Atreides" count 2 mean 41.0}
{name "Stilgar" count 1 mean 29.0}]
The window functions:
| Function | Value per row |
|---|---|
(row-number {...}) |
Position in the partition, from 1. |
(rank {...}) |
Position of the first row with equal order values. |
(dense-rank {...}) |
Count of distinct order values up to this row. |
(percent-rank {...}) |
(rank - 1) / (rows - 1); 0.0 for one row. |
(cume-dist {...}) |
Rows with order values at or before this one, divided by the partition size. |
(lag ?v [n [default]] {...}) |
?v from n rows earlier. |
(lead ?v [n [default]] {...}) |
?v from n rows later. |
(first ?v {...}), (last ?v {...}) |
?v from the frame's first or last row. |
(nth ?v n {...}) |
?v from the frame's n-th row, or null. |
(count ?v {...}) |
Rows in the frame. |
(sum ?v {...}), (mean ?v {...}), (min ?v {...}), (max ?v {...}) |
Folds over the frame, with the aggregate rules. |
The rank family, lag, lead, first, last and nth require order-by; so does the running frame.
Rows with equal order values keep entity order.
Arguments are bound variables, inputs or expressions over them: (sum (* ?age 2) {order-by [?name]}).
Use as ?age-rank in the options to name a window result. It sets the result key to age-rank and binds ?age-rank for later stages.
Without as, a unique call keeps its function name: (rank {...}) binds ?rank.
Repeated implicit names require <tuples> and do not introduce a binding. Use distinct as names to reuse those values.
A window name cannot shadow a row binding, aggregate alias or input.
where selects input rows before ranking. having filters completed window results without renumbering them.
Return the two oldest people, with reusable ranks:
(defquery example [] {find [?name (rank {as ?age-rank order-by [#desc ?age]})]
where [[?e name ?name] [?e age ?age]]
having [(<= ?age-rank 2)]
order-by [?age-rank]})
(example)
Result:
[{name "Leto Atreides" age-rank 1} {name "Duncan Idaho" age-rank 2}]
Other result expressions and query order-by can read these bindings, for example, (+ ?age-rank 10) and order-by [?age-rank].
Window calls run in find order. A later window can read an earlier result, for example (lag ?age-rank {as ?previous-rank order-by [?name]}). Self-references and forward references are errors.
All windows run before having, including when its predicates read only aggregate values.
With aggregates, windows read the grouped rows. Count the people at each station, then rank those counts:
(defquery example [] {find [?station (count ?e) (rank {as ?size-rank order-by [#desc ?count]})]
where [[?e station ?station]]
order-by [?size-rank]})
(example)
Result:
[{station "Arrakeen" count 2 size-rank 1} {station "Sietch Tabr" count 1 size-rank 2}]
Only grouping variables and aggregate aliases remain available after aggregation.
Windows also compose with project. Projection determines the entire result shape. Include window bindings explicitly among its fields:
(defquery example [] {find [(rank {as ?age-rank order-by [#desc ?age]})]
where [[?e name ?name] [?e age ?age]]
order-by [?age-rank]
project {?e {<name> commander <name> age-rank ?age-rank}}})
(example)
Result:
[{name "Leto Atreides" commander {name null} age-rank 1}
{name "Duncan Idaho" commander {name "Leto Atreides"} age-rank 2}
{name "Stilgar" commander {name null} age-rank 3}]
Windows over a join see every matched pair. Count how many people share each person's station, including that person:
(defquery example [] {find [?name (count ?b {as ?neighbors partition-by [?name]})]
<distinct>
where [[?a name ?name] [?a station ?station] [?b station ?station]]
order-by [?name]})
(example)
Result:
[{name "Duncan Idaho" neighbors 2} {name "Leto Atreides" neighbors 2} {name "Stilgar" neighbors 1}]
The query runs where, aggregation when present, windows, having, final ordering, distinct/offset/limit and projection in that order.
Window calls, partition variables and order variables have no fixed count. The evaluation's CPU and memory budget bounds their cost.
A query too large to compile fails with #err <invalid program> and the message query is too large to compile; a query with 500 window calls is one example, and 260 runs.
8.1.15. Match an optional group
Use one optional form when related fields must match together.
This query binds both the commander link and the commander's name, or neither:
(defquery example [] {find [?name ?commander ?commander-name]
where [[?e name ?name]
(optional [?e commander ?commander]
[?commander name ?commander-name])]
order-by [?name]})
(example)
Result:
[{name "Duncan Idaho" commander #link 2 commander-name "Leto Atreides"}
{name "Leto Atreides" commander null commander-name null}
{name "Stilgar" commander null commander-name null}]
optional accepts one or more field patterns. Each pattern's entity must already
be bound by a required pattern or an earlier optional field.
Optional patterns cannot yet depend on bindings introduced by [each ?item].
If any pattern fails, the incoming row remains and all bindings introduced by that
group become null. Bindings from outside the group retain their values.
For example, require both a commander and that commander's superior:
(defquery example [] {find [?name ?commander ?superior]
where [[?e name ?name]
(optional [?e commander ?commander]
[?commander commander ?superior])]
order-by [?name]})
(example)
Result:
[{name "Duncan Idaho" commander null superior null}
{name "Leto Atreides" commander null superior null}
{name "Stilgar" commander null superior null}]
Duncan has a commander, but Leto has no commander field. The second pattern fails, so neither link is returned for Duncan.
Separate optional forms preserve partial matches:
(defquery example [] {find [?name ?commander ?superior]
where [[?e name ?name]
(optional [?e commander ?commander])
(optional [?commander commander ?superior])]
order-by [?name]})
(example)
Result:
[{name "Duncan Idaho" commander #link 2 superior null}
{name "Leto Atreides" commander null superior null}
{name "Stilgar" commander null superior null}]
Here Duncan's first optional group succeeds. Failure in the second group leaves
his commander link intact. Use this distinction when these bindings participate
in filtering, grouping or ordering. To only return nested fields, use project.
8.1.16. Select either of two tags
Return the names of people with the Atreides or Fremen tag.
This form tests two possibly absent tag fields.
The optional reads retain people who have only one tag, and or requires at least one:
(defquery example [] {find [?name]
where [[?e name ?name]
(optional [?e atreides ?atreides])
(optional [?e fremen ?fremen])
(or ?atreides ?fremen)]
order-by [?name]})
(example)
Result:
[{name "Duncan Idaho"}
{name "Leto Atreides"}
{name "Stilgar"}]
Two required tag patterns would instead require both tags.
8.1.17. Select an absent field
Return the names of people without a commander field.
not rejects an entity when its enclosed field pattern matches:
(defquery example [] {where [[?e name ?name] (not [?e commander ?commander])]
project {?e <name>}})
(example)
Result:
[{name "Leto Atreides"} {name "Stilgar"}]
Use negated tags for tag membership and not for an arbitrary field pattern.
8.1.18. Read an earlier snapshot
The initial data is transaction 1, recorded at #utc "2026-01-01T00:00:00Z".
Transaction 2, recorded one day later, changes Duncan Idaho's age, removes his mentor tag and creates Chani:
[{<!mentor> id 1 age 38} {id 4 name "Chani"}]
Writing a false tag retracts it, just as writing null retracts a field.
Read Duncan Idaho's age at transaction 1 with as-of:
(defquery example [] {where [[?e name "Duncan Idaho"]]
as-of 1
project {?e <age>}})
(example)
Result:
[{age 37}]
Read it at the second commit's UTC time:
(defquery example [] {where [[?e name "Duncan Idaho"]]
as-of #utc "2026-01-02T00:00:00Z"
project {?e <age>}})
(example)
Result:
[{age 38}]
The tag removal changes which Atreides members are not mentors:
(defquery example [] {where [[?e <atreides !mentor>]]
as-of 2
project {?e <name>}})
(example)
Result:
[{name "Duncan Idaho"} {name "Leto Atreides"}]
A projection reads the same snapshot. A retracted tag projects as null, the
same as a tag that was never written:
(defquery example [] {where [[?e <atreides>]]
as-of 2
project {?e <name mentor>}})
(example)
Result:
[{name "Duncan Idaho" mentor null} {name "Leto Atreides" mentor null}]
Before the removal, Duncan Idaho's projection has the tag:
(defquery example [] {where [[?e <atreides>]]
as-of 1
project {?e <name mentor>}})
(example)
Result:
[{<mentor> name "Duncan Idaho"} {name "Leto Atreides" mentor null}]
At transaction 2, the absence-only query also includes Chani:
(defquery example [] {where [[?e <!mentor>]]
as-of 2
project {?e <name>}})
(example)
Result:
[{name "Duncan Idaho"} {name "Leto Atreides"} {name "Stilgar"} {name "Chani"}]
All linked projection reads use the same snapshot.
A time before the first commit sees an empty database.
With the retention plugin, the database removes old versions, and a read
before the oldest kept version of a fact reads that version
(History retention).
8.1.19. Several versions of a fact
Every write adds a version of a fact. A query reads the version current at its snapshot. A retraction hides the fact until the next write. Exact-value patterns match current values only.
This database has five transactions, recorded one day apart from
#utc "2026-02-01T00:00:00Z".
Transaction 1 creates three people:
[
{id 1 name "Duncan Idaho" status "active" rank "swordmaster"}
{id 2 name "Gurney Halleck" status "active" rank "troubadour"}
{id 3 name "Thufir Hawat" status "active" rank "mentat"}
]
Transaction 2 changes two statuses:
[{id 1 status "missing"} {id 2 status "exiled"}]
Transaction 3 retracts Duncan Idaho's status, captures Thufir Hawat and creates Chani:
[{id 1 status null} {id 3 status "captured"} {id 4 name "Chani" status "active" rank "sayyadina"}]
Transaction 4 writes Duncan Idaho's status again and returns Gurney Halleck to active:
[{id 1 status "ghola"} {id 2 status "active"}]
Transaction 5 retracts Thufir Hawat's status:
[{id 3 status null}]
Gurney Halleck's status has three versions.
A query without as-of reads the latest one:
(defquery example [] {where [[?e name "Gurney Halleck"]]
project {?e <status>}})
(example)
Result:
[{status "active"}]
A transaction ID between two versions reads the earlier one:
(defquery example [] {where [[?e name "Gurney Halleck"]]
as-of 2
project {?e <status>}})
(example)
Result:
[{status "exiled"}]
A UTC time between two commits reads the version current at that time:
(defquery example [] {where [[?e name "Gurney Halleck"]]
as-of #utc "2026-02-03T12:00:00Z"
project {?e <status>}})
(example)
Result:
[{status "exiled"}]
At transaction 3, Duncan Idaho's status is retracted.
The field pattern does not match him:
(defquery example [] {where [[?e name ?name] [?e status ?status]]
as-of 3
order-by [?name]
project {?e <name status>}})
(example)
Result:
[{name "Chani" status "active"} {name "Gurney Halleck" status "exiled"} {name "Thufir Hawat" status "captured"}]
A projection does not filter rows. It reads a retracted field as null:
(defquery example [] {where [[?e name ?name]]
as-of 3
order-by [?name]
project {?e <name status>}})
(example)
Result:
[{name "Chani" status "active"} {name "Duncan Idaho" status null} {name "Gurney Halleck" status "exiled"} {name "Thufir Hawat" status "captured"}]
At transaction 2, before the retraction, the projection has his status:
(defquery example [] {where [[?e name ?name]]
as-of 2
order-by [?name]
project {?e <name status>}})
(example)
Result:
[{name "Duncan Idaho" status "missing"} {name "Gurney Halleck" status "exiled"} {name "Thufir Hawat" status "active"}]
Transaction 4 writes his status again, and the fact is visible:
(defquery example [] {where [[?e name "Duncan Idaho"]]
as-of 4
project {?e <status>}})
(example)
Result:
[{status "ghola"}]
At the latest snapshot, Duncan Idaho has a status again and Thufir Hawat's status is retracted:
(defquery example [] {where [[?e name ?name]]
order-by [?name]
project {?e <name status>}})
(example)
Result:
[{name "Chani" status "active"} {name "Duncan Idaho" status "ghola"} {name "Gurney Halleck" status "active"} {name "Thufir Hawat" status null}]
An exact-value pattern matches entities whose current value is that value.
Duncan Idaho and Gurney Halleck were active at transaction 1, and are not at transaction 3:
(defquery example [] {where [[?e status "active"] [?e name ?name]]
as-of 3
order-by [?name]
project {?e <name>}})
(example)
Result:
[{name "Chani"}]
At the latest snapshot, Gurney Halleck is active again and Thufir Hawat has no status:
(defquery example [] {where [[?e status "active"] [?e name ?name]]
order-by [?name]
project {?e <name>}})
(example)
Result:
[{name "Chani"} {name "Gurney Halleck"}]
Two field patterns on one entity read the same snapshot.
At transaction 2, every rank is still its first version and two statuses have changed:
(defquery example [] {where [[?e rank ?rank] [?e status ?status]]
as-of 2
order-by [?rank]
project {?e <rank status>}})
(example)
Result:
[{rank "mentat" status "active"} {rank "swordmaster" status "missing"} {rank "troubadour" status "exiled"}]
Aggregates count current values only. Superseded and retracted versions are not counted:
(defquery example [] {find [?status (count ?e)]
where [[?e status ?status]]
order-by [?status]})
(example)
Result:
[{status "active" count 2} {status "ghola" count 1}]
A time before the first commit sees no versions:
(defquery example [] {where [[?e name ?name]]
as-of #utc "2026-01-31T00:00:00Z"
project {?e <name>}})
(example)
Result:
[]
8.1.20. Return positional tuples
Use <tuples> when the consumer needs positional values instead of named fields.
find determines their positions:
(defquery example [] {<tuples>
find [?name]
where [[?e name ?name]]
order-by [?name]})
(example)
Result:
[["Duncan Idaho"] ["Leto Atreides"] ["Stilgar"]]
8.1.21. Compute a value in find
A function call in find computes one value per row.
Without <tuples>, the result key is the called function's name:
(defquery example [] {find [?name (+ ?age 1) (strings/case "upper" ?name)]
where [[?e name ?name] [?e age ?age]]
order-by [?name]})
(example)
Result:
[{name "Duncan Idaho" + 38 strings/case "DUNCAN IDAHO"}
{name "Leto Atreides" + 46 strings/case "LETO ATREIDES"}
{name "Stilgar" + 30 strings/case "STILGAR"}]
Two terms that would produce one key are refused with duplicate result key in find; <tuples> allows them.
A term without a function name, such as [?age 1], needs a call around it: (list ?age 1).
A term that fails ends the query with its #err.
A computed term cannot be combined with aggregates, group-by or having.
Queries with project reject computed terms and window calls.
Aggregate projections can use grouping variables and aggregate aliases.
A call whose head is a variable, such as (?s ?v), is refused with a find call needs a function name.
8.1.22. Store a query as data
A query definition can take a query map as a parameter. Quote a query when storing it in a local, so its contents are preserved:
(defquery example [q] q)
(let [q `{where [[?e <atreides>]]
project {?e <name>}}]
(example q))
Result:
[{name "Duncan Idaho"} {name "Leto Atreides"}]
8.1.23. Query members and limits
| Member | Purpose |
|---|---|
where |
Match field patterns and predicates. |
project |
Select fields and nested linked entities. |
find |
Return matched variables, computed values, aggregates or window calls. |
order-by |
Sort results; #desc ?value sorts descending. |
offset / limit |
Skip rows and cap the returned count. |
<tuples> |
Return positional lists instead of maps. |
group-by |
Set explicit aggregate group keys. |
having |
Filter completed groups. |
<distinct> |
Remove repeated selected rows. |
in |
Declare caller-supplied query inputs. |
as-of |
Select a transaction ID or UTC snapshot. |
project requires exactly one query-binding entry.
When find is omitted, it is inferred from that binding.
Negated projection tags such as <!name> are unsupported.
Queries use the evaluator's CPU and memory budgets and cancellation signal.
There are no separate query row or cost quotas.
Unsupported query shapes and incompatible value kinds return errors.
limit 0 returns no rows.
8.2. Transactions
A transaction is a mutation value with a patch member.
It can also have if, query, schema and on members.
The database request transact runs one mutation
value from params.code and publishes it as one transaction; see
database requests. The examples below
run in order against a new database. Every request and response is checked by
the transaction conformance tests.
8.2.1. defmutation
Macro(defmutation name [params*] mutation-map) → name
Define a mutation with defmutation and call it with an open database. The
result contains tx and ids. These examples run in order against a separate new database.
(defmutation example [] {patch {_paul {name "Paul" spice 100}}})
(example)
This returns {tx 4 ids {_paul #link 1}}. A mutation can use local values and
compute a patch for each selected row:
(defmutation example [extra]
{query {find [?e ?spice] where [[?e name "Paul"] [?e spice ?spice]]}
patch {?e {spice (+ ?spice extra)}}})
(example 25)
This returns {tx 5 ids {}}. A subsequent query sees the committed value:
(defquery example [] {<tuples> find [?spice] where [[?e name "Paul"] [?e spice ?spice]]})
(example)
The result is [[125]]. Writing the same value publishes nothing:
(defmutation example [] {patch {1 {spice 125}}})
(example)
The result is {tx null ids {}}. A failed condition or conflicting proposals
returns an error and writes nothing for that call.
A mutation without a query can name its target with a parameter. In
(defmutation touch [e] {patch {?e {seen true}}}), the key ?e reads the
parameter e, which holds an entity ID such as 2 or a link such as
#link 2. A ?name key or value reads a parameter or a local of that name:
a let, fn or for binding, or a top-level def. In code that eval
runs, when no local has that name, it reads the binding of that name that the
host supplies. Code in a saved namespace does not read host bindings. When no
value is found, the call returns an unbound name error and writes nothing. A map key
is always a string, so {e {seen true}} does not name an entity: it is an
invalid patch target. With a query, ?e is a variable of the query.
Add schema beside patch to check every addressed entity:
(defmutation example [] {schema {name string? spice int?}
patch {1 {spice 130}}})
(example)
The check uses each complete post-patch entity.
Every call of the mutation checks it: a call in eval, a saved namespace
function, a defreactor called by name and a transact request.
A schema that contains a name, such as {name string?}, is evaluated where the
mutation runs, so a bare kind name is its builtin and a user predicate or a
closure applies as written. A call in eval checks with the functions that
the evaluation holds.
Temporary links use their final entity IDs during checking, including links inside lists.
The transaction stages all proposals before validation.
One failed entity rejects all facts, identifiers, and log entries.
An entirely unchanged patch resolves its schema but skips candidate validation.
Unscoped patches remain available when the mutation has no schema member.
A query schema clause also constrains its corresponding mutation target.
The constraint remains attached through grouping, ordering, and paging.
Different selected rows can carry different schemas.
Add on to run code after the call's write commits or rolls back; see
Run code after a write.
8.2.2. Save a mutation function
Save this source as shipments.dust:
(defmutation record-shipment [amount]
{patch {_shipment {amount amount}}})
(export record-shipment)
Install it in the database:
stardust namespace save arrakis/shipments shipments.dust --config arrakis.dust
Saving validates the definition without running its body. Import it in
run.dust and call it:
(import <arrakis/shipments>)
(shipments/record-shipment 50)
(shipments/record-shipment 75)
(defquery shipment-amounts []
{<tuples> find [?amount] where [[?e amount ?amount]] order-by [?amount]})
(shipment-amounts)
Run stardust eval run.dust --config arrakis.dust. Each call allocates its own
shipment; the final query returns [[50] [75]]. Loading the namespace after
reopening the database preserves this behavior. A top-level initializer that
calls a mutation is refused.
8.2.3. Transaction boundaries
Each mutation call is atomic. An evaluation with several calls can commit
several transactions. A later error does not undo an earlier call: its error
reports outcome "committed" and transaction {tx … ids …}, with the original
failure under cause when available. Read the data before retrying an evaluation
that has already committed.
Selection and expressions use a consistent snapshot. If a selected field
changes before publication, the call recomputes within its original CPU and
memory limits. A changed loaded namespace reports a conflict; invoke it again
to use the new definition. Mutation expressions cannot perform external effects
or change captured shared values. Use built-ins or saved namespace helpers in
mutation expressions; other captured functions can be refused with script denied.
Historical contexts cannot write.
Cancellation or exhaustion before commit leaves that call unpublished. A storage
error with outcome "unknown" requires reopening and reading the data before
retrying.
8.2.4. Run code after a write
Some work must wait until a write is final. A program can publish an event,
call another service or record a failure, but it must not do so for a write
that rolls back. The on member of a mutation map holds this work. It is a
map with an optional commit body and an optional rollback body, and each
body is ordinary DUST:
(defmutation pay [invoice]
{if {?invoice {status "open"}}
patch {?invoice {status "paid"}}
on {commit (record (str "paid " invoice " in " tx))
rollback (record (str "not paid " invoice ": " (errors/message error)))}})
defmutation, defreactor and the code map of a transact request accept
on. The commit body runs after the transaction commits, and the rollback
body runs after it rolls back. Each body runs once for each run of its
mutation, reactor or request, and it sees these names:
| Name | Value |
|---|---|
| the parameters | The mutation's parameters, or the bindings of a transact request |
rows |
The rows that the query selected, as a list of maps from each variable's name to its value; one empty map without a query |
tx |
The transaction ID, in commit |
error |
The #err value that the call returns, in rollback |
A literal mutation map in defmutation accepts ordinary handler bodies.
The bodies see the definition's parameters and captured local bindings.
The bodies run after the write releases the write lock and before the
request responds. Within one request they run in the order of the commits
and rollbacks that queued them: a request that calls a and then b runs
a's body, then b's, then the bodies of the writes that a's body made.
Requests that run at the same time run their bodies independently, with no
order between them. A body can run any DUST, also mutations. The handlers of
those writes run after it, so a chain of writes runs one handler at a time.
A chain has no limit on its length. The request's CPU and memory limits
apply to it, and a cancel of the request stops it. When a body is
cancelled or runs out of CPU or memory, the bodies after it do not run.
Nothing that a body does changes the commit or the rollback.
A mutation map computed as a value, including a map bound with def,
holds its handlers as functions. The commit handler takes rows and tx.
The rollback handler takes rows and a map whose error member holds
the #err value. A function called with an #err argument returns that
argument without running. The runtime returns #err <invalid program> if
a computed map's handler value is not a function:
(def finish {patch {_d {done true}}
on {commit (fn [rows tx] (record (str "done in " tx)))}})
(defmutation close [] finish)
A write that publishes nothing, such as a patch that changes no value, runs
neither body. A dry run runs no body. When a storage error leaves the outcome
unknown, no body runs.
This namespace records each payment, and flags large invoices for review:
{id 1 method "namespaces/save"
params {changes [{path "billing/payments"
forms [(defmutation record [text] {patch {_entry {log text}}})
(defmutation pay [invoice]
{if {?invoice {status "open"}}
patch {?invoice {status "paid"}}
on {commit (record (str "paid " invoice " in " tx))
rollback (record (str "not paid " invoice ": "
(errors/message error)))}})
(defmutation settle [invoice]
{patch {?invoice {settled true}}
on {commit (pay invoice)}})
(defreactor flag-large
{query {find [?invoice] where [[?invoice amount ?a] (> ?a 1000)]}
patch {?invoice {review true}}
on {commit (record (str "review " rows))}})
(export pay settle)]}]}}
[{id 1 result {tx 4 namespaces [{path "billing/payments" entity #link 1 revision 4 deleted false}]}}]
The next write adds two invoices. flag-large reviews the large one in the
same transaction, and its commit body runs after that transaction commits:
{id 2 method "transact"
params {code {patch {_small {amount 40 status "open"}
_large {amount 5000 status "open"}}}}}
[{id 2 result {tx 11 ids {_large #link 5 _small #link 6}}}]
pay closes the small invoice, and its commit body records the payment:
{id 3 method "eval"
params {forms true code [(import <billing/payments>) (payments/pay 6)]}}
[{id 3 result [null {tx 15 ids {}}]}]
settle marks the invoice settled. Its commit body calls pay again, and
that call fails, because the invoice is no longer open. pay rolls back, so
its rollback body records the failure. The commit body of settle
returns the #err value of pay. The response reports that failure in its
on member: one entry for each failed body, with the definition's name,
the key of the body and its error. The request returns its normal
result, and the other bodies still run:
{id 4 method "eval"
params {forms true code [(import <billing/payments>) (payments/settle 6)]}}
[{id 4 result [null {tx 19 ids {}}]
on [{name "settle" key "commit"
error #err {code <conflict> message "patch proposals or conditions conflict"}}]}]
The log shows each body's work in commit order:
{id 5 method "query"
params {query {find [?text] <tuples> where [[?entry log ?text]]}}}
[{<more> id 5 page 0 result [["review [{invoice 5}]"]
["paid 6 in 15"]
["not paid 6: patch proposals or conditions conflict"]]}]
An entry has name when its body belongs to a defmutation or a
defreactor. Only a reactor's entry also has namespace: the entry of a
defmutation, even one in a saved namespace, has no namespace, and the
entry of a transact request has neither. A failure is the
#err value that the body returns, or the error that stopped it: when the
request is cancelled or runs out of CPU, each body that did not run is
reported with that error.
Some functions have effects that must not escape a rollback. Such a function
refuses to run while a write transaction is open, for example in a computed
patch value or in a reactor, and points to on {commit …}. In an on body
and outside a transaction it runs normally.
8.2.5. Create entities
patch maps each entity to its changed fields. A key that starts with _ is a
temporary name for a new entity. Inside the patch, _paul and #link _paul
refer to that entity, so partner stores a link to it. Ordinary strings stay
strings.
{id 1 method "transact"
params {code {patch {_paul {name "Paul" spice 100}
_chani {name "Chani" partner _paul}}}}}
Response:
[{id 1 result {tx 6 ids {_chani #link 1 _paul #link 2}}}]
tx is the transaction ID, which is a valid as-of bound for queries. ids
maps each temporary name to the entity allocated for it. Names are allocated in
name order; new fields follow, and the transaction ID comes last.
8.2.6. Change an entity
A key spelled as a decimal ID names an existing entity. A nested map merges into the entity the field links to, or into a new entity when the field is empty. A list replaces the whole value. A tag asserts membership.
{id 2 method "transact"
params {code {patch {2 {<fremen> home {city "Arrakeen"} steps ["scout" "patrol"]}}}}}
Response:
[{id 2 result {tx 12 ids {}}}]
8.2.7. Write one patch per query row
A query selects rows, and the patch is filled once for each row. Each row has
its own scope, so _note names a new entity for every row, and #link "_note"
reaches the entity of that row. ids then maps each name to the list of its
entities in row order.
{id 3 method "transact"
params {code {query {find [?e ?n] where [[?e name ?n]] order-by [?e]}
patch {_note {about #link ?e text ?n}
?e {note #link "_note"}}}}}
Response:
[{id 3 result {tx 18 ids {_note [#link 13 #link 14]}}}]
Expressions in a patch, such as (+ ?v 10), are computed from the row. A row
whose filled body for a name holds no fact allocates no entity for that name
and adds nothing to its list; a transaction in which every row is empty
publishes nothing. Here only Paul's row gets a badge:
{id 8 method "transact"
params {code {query {find [?e ?n] where [[?e name ?n]] order-by [?e]}
patch {_badge (if (= ?n "Paul") {<fremen> who #link ?e} {})}}}}
Response:
[{id 8 result {tx 21 ids {_badge [#link 19]}}}]
A link to a name that allocated nothing in its row names no entity, and the
transaction is refused. A quoted form or a function is refused: a patch holds
data. A refused form reports its position in the request, as an evaluation
error does, with a span when the request was decoded with spans.
8.2.8. Check a condition
An if map compares current values before anything is written. The whole
transaction publishes only when every condition holds.
{id 4 method "transact"
params {code {if {2 {spice 100}} patch {2 {spice 80}}}}}
Response:
[{id 4 result {tx 22 ids {}}}]
A condition that does not hold is #err {code <conflict> …}, and nothing is
written. Two rows that propose different values for one field conflict in the
same way.
{id 5 method "transact"
params {code {if {2 {spice 100}} patch {2 {spice 60}}}}}
Response:
[{id 5 result #err {code <conflict> message "patch proposals or conditions conflict"}}]
8.2.9. Unchanged values and retractions
A patch that changes nothing publishes no transaction:
{id 6 method "transact" params {code {patch {2 {spice 80}}}}}
Response:
[{id 6 result {tx null ids {}}}]
A negative tag, null or false at a field retracts it. Inside a list or a
nested value, null and false stay data.
{id 7 method "transact" params {code {patch {2 {<!fremen> steps null}}}}}
Response:
[{id 7 result {tx 23 ids {}}}]
null as the value of an entity retracts the entity: the patch retracts each
field that the entity has before the transaction. Entity 13 is Chani's note
from the rows example:
{id 10 method "transact" params {code {patch {13 null}}}}
Response:
[{id 10 result {tx 24 ids {}}}]
The result is the same as null at each field of the entity. History keeps
the old values, so a query with as-of 23 still finds the note. Links from
other entities do not change: Chani's note field still links to entity 13,
and a query through that link finds no fields. In a mutation, a key such as
?e can also take null, and so can a computed value. The value of ?e is
an ID or a #link. A mutation parameter supplies that target too:
(defmutation drop [e] {patch {?e null}}) accepts (drop 2) or
(drop #link 2). A lexical local can supply the target as well; when
there is no local, the target reads its host binding.
The proposals of the retraction are the same as other proposals. A different
value for one of the fields at the same priority is a conflict. A field that
the entity does not have can get a value in the same transaction. A reactor
sees the retraction as it sees other writes, and a dry run shows each field
with the action "retract". A schema checks the empty entity. Each plugin
claim applies to each field, so a patch cannot retract an objects tree
node.
null for an entity that has no fields, for example an entity that is
retracted already, changes nothing. A reactor that retracts the entities it
finds through a link thus finds them again in its next round, and the rounds
end.
These patches are refused, and nothing is written:
nullfor an ID that is not an entity, and for a namespace entity. The error is#err {code <invalid value>}.nullfor a temporary name such as_x, because a new entity has no fields. The error is#err {code <invalid program>}.falseas the value of an entity, andnullin anifcondition.
Transactions run under the request's CPU and memory limits. A transaction that is cancelled or runs out of budget before it commits writes nothing.
8.2.10. Dry run
Add dry-run true to the transact parameters to see the changes of a
mutation before you commit it. The dry run does all the steps of a real run,
and then it rolls back the transaction. It writes nothing and gives the same
errors as a real run. Its result has tx null, the ids that a real run
would allocate, and a changes list. Each item of the list is an entity that
the mutation would change, with the before and after values of each
changed field. Here entity 2 would get a new spice value, and _leto would
be a new entity:
{id 9 method "transact"
params {dry-run true
code {patch {2 {spice 60} _leto {name "Leto"}}}}}
Response:
[{id 9 result {tx null ids {_leto #link 24} dry-run true
changes [{entity #link 2 created false
fields {spice {action "assert" before 80 after 60}}}
{entity #link 24 created true name "_leto"
fields {name {action "assert" after "Leto"}}}]}}]
The action of a field is "assert", "retract" or "merge". A merge is a
map at a field that merges into the linked entity. The changes of that entity
are in its own item. Named mutation calls in eval have no dry run. A dry run
runs no on body.
8.2.11. Keep less history of an entity
With the retention plugin, a patch can give an entity a history policy in
the stardust/history field. The plugin removes the older history in the
background (History retention). The patch
of this request keeps the newest 5 transactions that wrote a field of the
order:
{method "transact"
params {code {patch {_order {status "placed" stardust/history {retain 5}}}}}}
retain is one of these values:
retain |
Kept history of each field of the entity |
|---|---|
| An integer N, 1 or more | The facts of the newest N transactions of the entity, and the value before them |
A positive #dur |
The facts written within that time before now, and the value before them |
A #utc |
The facts written at or after that time, and the value before them |
With cascade true, the policy also applies to the descendants of the entity
through stardust/path/parent, such as the files and directories of an
objects tree. A descendant with a policy of its own uses its own policy. An
own policy without cascade applies to that entity only, so its children
still use the cascading policy above it:
{method "transact"
params {code {patch {7 {stardust/history {retain #dur "P30D" cascade true}}}}}}
A policy has retain and an optional boolean cascade, and no other key.
Other values are refused with #err {code <invalid value>}. The policy map
merges into an entity that stardust/history links to, as each map in a
patch does. Thus a later patch that gives only retain keeps the earlier
cascade. null removes the policy. Without the retention plugin, a patch
that writes stardust/history fails with #err {code <plugin required>}.
If a direct edit makes the linked policy invalid, pruning stops and
retention/status reports last-error until the policy is repaired.
A fact can have a field setting of the plugin and an entity policy. Then the
one that keeps more history applies. For example, with the field setting
{fields {status {retain 3}}} and the entity policy {retain 1}, the status
of the entity keeps its newest 3 values and the value before them. The
other fields of the entity keep only its newest transaction and the values
before it.
Another plugin can hold history back with a history floor. Then a removal keeps every fact that a read at or after the floor needs, and it removes the rest after the floor moves.
8.2.12. defreactor
Macro(defreactor name doc? options? mutation-map) → name
A reactor is a mutation that the database runs. Save it in a namespace. Each later write that changes a field that the reactor reads or writes then runs the reactor before the write commits. The facts that the reactor writes commit in the same transaction as the facts that caused them, so a query at that transaction sees both.
This namespace flags the invoices of customers on hold and gives each user an access level:
{id 1 method "namespaces/save"
params {changes [{path "billing/review"
forms [(defreactor flag-held
"Flag the invoices of customers on hold."
{query {find [?invoice]
where [[?invoice customer ?customer]
[?customer hold true]]}
patch {?invoice {review true}}})
(defreactor grant-admins {priority 10}
{query {find [?user] where [[?user admin true]]}
patch {?user {access "all"}}})
(defreactor default-access
{query {find [?user] where [[?user member true]]}
patch {?user {access "none"}}})]}]}}
The write below adds a customer on hold, an invoice and two users. It does
not write review or access:
{id 2 method "transact"
params {code {patch {_acme {name "Acme" hold true}
_invoice {amount 100 customer #link _acme}
_ada {name "Ada" member true admin true}
_bob {name "Bob" member true}}}}}
Response:
[{id 2 result {tx 18 ids {_acme #link 5 _ada #link 6 _bob #link 7 _invoice #link 8}}}]
The reactors wrote both fields in that transaction. The invoice has a review flag:
{id 3 method "query"
params {query {find [?amount ?review] <tuples>
where [[?invoice amount ?amount] [?invoice review ?review]]}}}
[{id 3 page 0 more true result [[100 true]]}]
Ada is an admin and a member, so grant-admins and default-access both
propose her access. The database keeps the priority 10 value. Bob is only a
member:
{id 4 method "query"
params {query {find [?name ?access] <tuples>
where [[?user name ?name] [?user access ?access]]
order-by [?name]}}}
[{id 4 page 0 more true result [["Ada" "all"] ["Bob" "none"]]}]
8.2.12.1. Rounds
Reactors run in rounds inside the write transaction:
- A round selects each reactor whose query reads a changed field or whose patch writes one. Reactors that can write the same field run together, so a lower priority value can replace a value that a higher priority reactor no longer proposes. A reactor with a computed patch value can write any field, so a change of any field runs it.
- All selected reactors read the same state: the write and the earlier rounds. A reactor does not see the proposals of its own round.
- The proposals of the round merge. Identical values agree. For different values at one field, the database keeps the value of the higher priority. The default priority is 0.
- The merged patch joins the transaction. The next round uses the fields it changed. The transaction commits after a round that changes nothing.
A later round can replace a value that the write or an earlier round wrote. The transaction then records only the final value.
The transaction ID is higher than every ID that the write and its reactors create. When a round creates a field or an entity, the transaction takes its ID after the last round. The ID that the write took before the rounds is then not used.
These conditions reject the whole write, and nothing commits:
- Two reactors of equal priority propose different values for one field.
- A reactor fails, for example on a schema. Each schema of a reactor applies to the final state of its entity.
- Each of 64 rounds changes a value.
The error message names the reactor when one reactor causes the failure.
8.2.12.2. Reactor rules
- A reactor takes no parameters. Its query selects the entities to change, so
a reactor has no
ifmember. - The options map accepts
priority, an integer. - Saving a namespace checks each reactor and refuses an invalid one. A saved reactor applies to later writes. Saving it does not run it on the current facts.
- The
transactrequest and mutation calls inevalrun reactors. A saved namespace is stored as facts, and a bulk import needs a database without facts, so a bulk import never runs a reactor. defreactoralso defines a function without parameters that runs the reactor as a mutation, for example to apply it to existing facts.- A reactor can have an
onmember (Run code after a write). Itscommitbody runs only when a value that the reactor proposed changed the state that the write commits. A reactor that a higher priority fully overrides does not run it, and neither does a reactor that only proposes values its fields already have. Itsrowsare the rows whose values made such a change. Itsrollbackbody runs when the write rolls back after the reactor's rounds, with the rows of those rounds. The bodies run in the reactor's namespace, after the handlers of the write itself, in the order of the definitions.
8.2.13. db/reactors
Function(db/reactors) → map
(db/reactors) returns the saved reactors and their work since the database
opened. Each entry has these members:
| Member | Value |
|---|---|
namespace, name |
The namespace path and the reactor name |
priority |
The priority of the reactor's values |
writes |
The fields that the patch writes |
any-write |
true when a computed value can write other fields |
runs |
The rounds that evaluated the reactor |
changes |
The fields of entities that its values changed in writes whose reactors all succeeded |
last-tx |
The last transaction that it changed, or null |
failures |
The writes that it caused to fail |
last-failure |
The message of the last failure, or null |
The counters start at zero when the database opens. Without database
storage, (db/reactors) returns #err <database no>. The reactors/status
request of the ABI returns the same map. After the example above, each
reactor ran in two rounds, and the second round changed nothing. The
grant-admins reactor changed Ada's access, and default-access changed
Bob's:
{id 5 method "reactors/status"}
[{id 5
result {reactors [{namespace "billing/review" name "flag-held" priority 0
writes ["review"] any-write false runs 2 changes 1
last-tx 18 failures 0 last-failure null}
{namespace "billing/review" name "grant-admins" priority 10
writes ["access"] any-write false runs 2 changes 1
last-tx 18 failures 0 last-failure null}
{namespace "billing/review" name "default-access" priority 0
writes ["access"] any-write false runs 2 changes 1
last-tx 18 failures 0 last-failure null}]}}]
When the database has saved defcron forms or runs a scheduler, the map
also has a scheduled member (Scheduled reactor
status).
8.2.14. defcron
Macro(defcron name doc? map) → name
A scheduled reactor is a mutation that the database runs at UTC times. Save
it in a namespace. When the root configuration has the tag
<scheduled-reactors>, the database runs the mutation at each minute that
its schedule selects. Each run is a separate write transaction.
The map has one schedule member. Its value is a cron expression string
(Cron expressions). The other members are a mutation
map, as in defmutation. The mutation can use the name scheduled-at. Its
value is the minute that the schedule selected, as a #utc value. A run
that starts at 09:00:20 receives 09:00:00. The mutation members, such as
query, patch and schema, cannot bind the name scheduled-at again.
This configuration enables scheduled reactors. No evaluation can read the clock or the filesystem:
{plugins {<stdlib> database <temporary> io <!clock>}
<scheduled-reactors>
capabilities <!filesystem>}
This namespace queues the expired sessions at 09:00 UTC on each weekday:
{id 1 method "namespaces/save"
params {changes [{path "app/sessions"
forms [(defcron queue-expired-sessions
"Queue expired sessions for cleanup."
{schedule "0 9 * * MON-FRI"
query {find [?session]
where [[?session session-status "expired"]]}
patch {?session {session-status "cleanup-pending"
queued-at scheduled-at}}})]}]}}
This write adds an expired session and an active session:
{id 2 method "transact"
params {code {patch {_old {session-status "expired"}
_new {session-status "active"}}}}}
At 09:00 UTC on Monday 7 January 2030, the database runs the reactor. The
expired session now waits for cleanup, and queued-at has the minute of the
run:
{id 3 method "query"
params {query {find [?status ?queued] <tuples>
where [[?session session-status ?status]
[?session queued-at ?queued]]}}}
[{id 3 page 0 <more> result [["cleanup-pending" #utc "2030-01-07T09:00:00Z"]]}]
8.2.14.1. Settings
| Setting | Tags | Default | Effect |
|---|---|---|---|
scheduled-reactors, in the root configuration |
<scheduled-reactors> |
Absent | Runs the saved defcron forms. It requires the database plugin. |
clock, in the settings of the io plugin |
<clock> or <!clock> |
Absent | Controls the calls to time/now, as the next table shows. |
Without <scheduled-reactors>, the database starts no scheduler. It
still checks and saves defcron forms. A database without storage has no
saved forms and starts no scheduler. The scheduler operates without the io
plugin. It reads the host clock itself and gives no access to the
evaluations that it starts.
io settings |
time/now in other evaluations |
time/now in a scheduled reactor |
|---|---|---|
No clock tag |
Returns the time | Returns #err <clock denied> |
<clock> |
Returns the time | Returns the time |
<!clock> |
Returns #err <clock denied> |
Returns #err <clock denied> |
The clock setting does not change the time functions that do not read the
clock, such as time/parts.
The body of a scheduled reactor cannot call time/now, also with
<clock>. Mutation expressions have no host effects, in every mutation.
namespaces/save accepts such a body, but each run of it fails, and the
status shows last-failure <script denied> namespace initialization
attempted an effect. Use
scheduled-at in the body. Read the clock in an on handler, which runs
after the write, or in a reactor that the write runs:
(defmutation record-run [clock] {patch {_run {clock clock}}})
(defcron stamp {schedule "* * * * *"
patch {_t {at scheduled-at}}
on {commit (record-run (time/now))}})
With <clock>, the handler records the time. Without it, (time/now)
returns #err <clock denied>, and record-run returns that error without a
write. A handler body is code of its own: it can bind scheduled-at as its
own local name.
8.2.14.2. Cron expressions
A cron expression has five fields. Whitespace, such as spaces, tabs or line ends, separates the fields. The fields are in this order:
| Field | Values |
|---|---|
| Minute | 0 through 59 |
| Hour | 0 through 23 |
| Day of month | 1 through 31 |
| Month | 1 through 12, or JAN through DEC |
| Day of week | 0 through 7, or SUN through SAT. 0 and 7 are both Sunday. |
Each field is a list of one or more items. These operators make an item:
| Operator | Meaning | Example | Example meaning |
|---|---|---|---|
* |
Each value of the field | * * * * * |
Each minute |
, |
A list of items | 0,30 * * * * |
At minutes 0 and 30 of each hour |
- |
A range that includes its two ends | 0 9-17 * * * |
At the start of each hour from 09:00 through 17:00 |
/ |
A step after * or after a range |
*/15 * * * * |
At minutes 0, 15, 30 and 45 of each hour |
A step starts at the first value of its field or range. It does not continue
into the next hour, day or month. Thus */40 * * * * selects minutes 0 and
40 of each hour. The names of months and days of the week can have uppercase
or lowercase letters.
A minute matches when its minute, hour and month match. For the day, the two day fields operate together:
- When both day fields are
*, each day matches. - When one day field is
*, the other field selects the days. - When neither day field is
*, a day matches when either field matches it. Thus0 9 1 * MONselects 09:00 on each Monday and on the first day of each month.
A day field such as 1-31 or */1 is not *, so the other day field can
also select days.
| UTC schedule | Expression |
|---|---|
| Every 15 minutes | */15 * * * * |
| At the start of every hour | 0 * * * * |
| At 02:30 each day | 30 2 * * * |
| At 09:00 on weekdays | 0 9 * * MON-FRI |
| At midnight on the first day of each month | 0 0 1 * * |
| At 09:00 on Mondays and on the first day of each month | 0 9 1 * MON |
The database refuses these expressions:
- An expression with fewer or more than five fields, and a name such as
@dailyin place of the fields. - A time zone, such as
CRON_TZ=UTC. The fields are always in UTC. - An empty list item, or a range without an end.
- A range that ends before it starts, such as
SAT-SUN. - A value outside its field, or a name that is not a month or a day of the week.
- A step that is
0, that is not a number, or that follows a single value, such as5/10. - The extensions
?,L,Wand#, such asLin the day of month,15WorMON#2.
8.2.14.3. Run rules
- Only saved namespaces have scheduled reactors. A form in an evaluation, a
namespaces/checkrequest, an unsaved session source and a historical read do not schedule a run. A write of data does not run a scheduled reactor. namespaces/checkandnamespaces/saverefuse an invalid form, also without<scheduled-reactors>. The diagnostic gives the namespace path and the form index. A refused save keeps the current schedule.- No other form of the namespace can define the name of a scheduled reactor. A run calls the definition by that name.
- When the database opens, the first minute is the first minute after the open. After a save, the first minute is the first minute after the save commits.
- The database examines each UTC minute one time. When the host stops or the clock moves forward, the database does not run the minutes that it did not examine. After the clock moves forward, it examines only the current minute. After the clock moves back, it does not examine a minute again.
- A reactor has a maximum of one run that waits or runs. When its next
minute comes before that run ends, the database does not run the reactor
for that minute. The status counts that minute as
skipped. - When a save changes or deletes the namespace that holds the definition, a run that waits does nothing. The next minute of the reactor is the first minute after that save commits. A run that started continues as a normal write.
- A run uses the mutation path of the database: its limits, schemas,
reactors,
onhandlers and subscriptions. A failed run rolls back. The status records the failure, and the next matching minute runs again. - A run gets no access to the host. The filesystem and the other host
capabilities are off for the run and its
onhandlers, also when the configuration gives them to other evaluations. - When the database closes, it starts no new run. It waits until each active run ends or stops before it closes the storage.
defcronalso defines a function with one parameter,scheduled-at. The function runs the mutation. A call to the function is an ordinary evaluation with the access of the database:
(queue-expired-sessions #utc "2030-01-07T09:00:00Z")
8.2.14.4. Scheduled reactor status
(db/reactors) and the reactors/status request also return a
scheduled member: a list with an entry for each saved defcron form, in
the order of the definitions. When the database runs a scheduler, the status
map always has this member. Without a scheduler, as without
<scheduled-reactors>, the status map has the member only when the
namespaces have saved defcron forms. Each of those entries has the tag <disabled>.
| Member | Value |
|---|---|
<disabled> |
The tag of an entry that no scheduler runs; absent otherwise |
namespace, name |
The namespace path and the reactor name |
schedule |
The cron expression |
runs |
The runs that committed |
failures |
The runs that failed, including runs that the database could not start |
skipped |
The minutes that came while a run waited or ran |
last-scheduled |
The last minute that the schedule selected, as a #utc value, or null |
next-scheduled |
The next minute that the schedule selects and the scheduler can still consider, as a #utc value, or null |
last-tx |
The transaction of the last run that committed, or null |
last-failure |
The message of the last failure, or null |
last-failure-at |
The minute that the schedule selected for the last failed run, as a #utc value, or null |
next-scheduled is the first minute at or after the current minute that
the schedule selects, and that the scheduler did not consider for the
reactor before. After the clock moves back, it stays after the newest minute
considered. A run that still waits or runs at that minute makes the minute a
skip. next-scheduled is null for a disabled entry, and for a schedule
that selects no day, such as 0 0 30 2 *.
The counters start at zero when the database opens. A disabled entry has
zero counters and null minutes. After the run above:
{id 4 method "reactors/status"}
[{id 4
result {reactors []
scheduled [{namespace "app/sessions" name "queue-expired-sessions"
schedule "0 9 * * MON-FRI" runs 1 failures 0 skipped 0
last-scheduled #utc "2030-01-07T09:00:00Z"
next-scheduled #utc "2030-01-08T09:00:00Z" last-tx 10
last-failure null last-failure-at null}]}}]
A check of an invalid expression gives the namespace and the form index:
{id 5 method "namespaces/check"
params {changes [{path "app/sessions"
forms [(defcron queue-expired-sessions
{schedule "0 9 * * MON-FRY"
query {find [?session]
where [[?session session-status "expired"]]}
patch {?session {session-status "cleanup-pending"}}})]}]}}
[{id 5
result {<!valid>
diagnostics [{code "invalid_source" path "app/sessions"
message "scheduled reactor app/sessions/queue-expired-sessions: the day-of-week field accepts 0 through 7 or SUN through SAT"
position {form-index 0}}]}}]
09 Error Functions
The errors/ functions read an error. An error is an #err tagged value.
Its payload can be any value, including text, a list, or a map.
Unlike most functions, these receive an error argument (see
Evaluation). Any other argument gives
#err <mismatch type>. Use error? first when a value
may not be an error.
9.1. errors/message
Function(errors/message error) → string
null
Returns the error's message: the message member of its payload when that is
text, the payload itself when the payload is text, and otherwise null. Use it
to log an error, since str of an error is the error.
[(errors/message (/ 1 0)) (errors/message missing) (errors/message #err "app/oh-no") (errors/message #err {<app> code 7}) (let [read :errors/message] (read (/ 1 0))) (map :errors/message [(/ 1 0) missing])]
(errors/message (/ 1 0)) (errors/message missing) (errors/message #err "app/oh-no") (errors/message #err {<app> code 7}) (let [read :errors/message] (read (/ 1 0))) (map :errors/message [(/ 1 0) missing])
"division by zero" "unbound name: missing" "app/oh-no" null "division by zero" [ "division by zero" "unbound name: missing"]
(let [result (/ 1 0)] [(str "failed: " (errors/message result)) (str "failed: " result) (if (error? result) (str "failed: " (errors/message result)) result)])
(let [result (/ 1 0)] [(str "failed: " (errors/message result)) (str "failed: " result) (if (error? result) (str "failed: " (errors/message result)) result)])
"failed: division by zero" #err {<division integer zero> message "division by zero"} "failed: division by zero"
[(errors/message "division by zero") (errors/message null) (errors/message {message "m"})]
(errors/message "division by zero") (errors/message null) (errors/message {message "m"})
#err {<mismatch type> message "expected an #err value"} #err {<mismatch type> message "expected an #err value"} #err {<mismatch type> message "expected an #err value"}
9.3. errors/data
Function(errors/data error) → value
Returns the error's payload. For a map payload, returns a new map with the same keys and member values. Nested values remain shared. Other payloads are returned unchanged.
[(errors/data (/ 1 0)) (errors/data #err "app/oh-no") (errors/data #err {<app> code 7 message "m"}) (get (errors/data #err {<app> code 7}) "code") (errors/data 5) (errors/data #err 7) (errors/data #err [1 2]) (let [error #err {<app> code 7} payload (errors/data error)] [(put payload "code" 9) (errors/data error)])]
(errors/data (/ 1 0)) (errors/data #err "app/oh-no") (errors/data #err {<app> code 7 message "m"}) (get (errors/data #err {<app> code 7}) "code") (errors/data 5) (errors/data #err 7) (errors/data #err [1 2]) (let [error #err {<app> code 7} payload (errors/data error)] [(put payload "code" 9) (errors/data error)])
{<division integer zero> message "division by zero"} "app/oh-no" {<app> code 7 message "m"} 7 #err {<mismatch type> message "expected an #err value"} 7 [1 2] [{<app> code 9} {<app> code 7}]
10 Hash Functions
The hashes/ library computes digests of DUST values.
10.1. Events
The events plugin carries temporary messages between the requests of one
open database: publications that reach every matching subscription, and calls
that one responder or worker answers. Nothing is stored or replayed. Record
facts first when an event must survive, then publish. The requests, the
exchange modes and the page formats are in the
ABI reference. Without the plugin, a namespace
that contains defsubscription or defresponder cannot be saved or loaded:
the macros are unknown.
The events functions are host effects, so a patch expression cannot call
them, and a function that publishes or sends refuses with
#err <denied events> whenever it runs while a write transaction is open:
the write can still roll back, and a message cannot. Publish in an
on {commit …} body instead, which runs after the write commits. A subject is non-empty UTF-8 of
slash-separated segments, and a pattern is a regular expression that must
match the whole subject.
(ns app/billing)
(defmutation note [invoice] {patch {_n {kind "notice" invoice invoice}}})
(defsubscription notify-paid "billing/paid"
(fn [{data <invoice>}] (note invoice)))
(defmutation pay [invoice]
{patch {?invoice {status "paid"}}
on {commit (events/publish "billing/paid" {invoice invoice})}})
10.1.1. defsubscription
Macro(defsubscription name pattern fn) → name
Defines a subscription in a saved namespace. For each publication whose
subject pattern matches, the database calls fn with {subject data}
before the publish returns, in publication order. fn may write, publish and
call; its writes run their own on handlers. A publication that the body
makes runs its subscriptions after the current ones, so a chain runs in order
without a limit on its length. A failed body never undoes the publication: the
publish result lists it under failures. name is also bound to fn.
10.1.2. defresponder
Macro(defresponder name pattern fn) → name
Defines a responder in a saved namespace. A request call on a subject that
pattern matches calls fn with {subject data}, and its value is the
reply. A responder answers before any host worker. A save that defines a
responder with the pattern of another saved responder, written the same,
fails with #err <conflict name>, with a message such as
"math/add already answered by app/math/add". Different patterns that match one subject make the call fail
with #err <conflict>, which names both responders. name is also bound to
fn.
(ns app/math)
(defresponder add "math/add" (fn [{data <a b>}] (+ a b)))
; (events/call "math/add" {a 1 b 2}) is 3.
10.1.3. events/publish
Function(events/publish subject data) → map
Publishes data on subject and returns {delivered dropped}: the
subscriptions it reached, saved ones included, and those whose queue
allocation failed. The saved subscriptions run before it
returns; a failed body adds an entry {namespace name subject error} to
failures.
10.1.4. events/call
Function(events/call subject data) → value
Sends data as a request on subject and returns the reply. A saved
responder that matches answers at once. Otherwise a host worker
(events/accept) must answer: the call waits, and the wait counts against
the evaluation's CPU budget and ends when the evaluation is cancelled. While
it waits, plugin requests run on the database's other workers, so a call that
needs a host worker fails with #err <denied events> when the database has
one worker. Without a worker, it fails with no_worker.
10.1.5. events/send
Function(events/send handle data) → map
Sends data to the other side of the exchange behind handle, as the
events/send request does.
10.1.6. events/finish
Function(events/finish handle) → map
Ends this side's stream of the exchange behind handle.
10.1.7. events/cancel
Function(events/cancel handle) → map
Ends the exchange behind handle; the other side reads cancel.
10.1.8. events/status
Function(events/status) → map
Returns {subscriptions registrations rpcs queued runs failures}: the open
subscriptions, workers and exchanges, the queued notices, and the saved
handler runs and failures since the database opened.
10.2. Blackholes
The blackholes plugin erases or replaces selected values in every version of
history, current values included. An operator previews the change, then
executes it with the preview's digest. Each execute writes an audit. The
requests and their results are in the ABI reference.
Without the plugin, a namespace that contains defblackhole cannot be saved
or loaded: the macro is unknown.
10.2.1. defblackhole
Macro(defblackhole name doc? [params*] {query patch links?}) → name
Defines a blackhole in a saved namespace. The parameters are locals in the
query and in the expressions. query is a query map without as-of: a saved
query cannot select an earlier snapshot. A blackhole rewrites every earlier
version of a selected field, also when its current value is retracted. A
distinct query keeps its own tuples: the variables that the patch reads do
not make more rows. patch maps query variables that
bind entities to null, which erases every field of the entity, or to a map
of fields. A field's null erases each version; an expression computes a
replacement for each version. links {incoming remove} removes links to
erased entities from other fields.
(defblackhole erase-keys
"Erase the API keys of one owner."
[owner]
{query {find [?e] where [[?e kind "apiKey"] [?e owner ?o] (= ?o owner)]}
patch {?e {secret null
token (hashes/digest "sha256" [?seed ?value])
note "redacted"}}})
An expression can read ?value (the version's value), ?entity, ?field,
?transaction, ?seed and the variables of its row. ?seed is 64
hexadecimal digits, new for each preview and each execute, and never stored.
An expression that reads a variable that the query does not bind, a field in
stardust/, and a member other than query, patch and links refuse the
namespace save. When a row does not bind a variable that an expression reads,
the preview or the execute fails with unbound_variable and changes nothing.
Only an optional group that does not match leaves a variable unbound. A
null that the row binds, such as the default of lag, is a value.
A blackhole rewrites earlier versions in place: an as-of read of an earlier
transaction sees the changed value. A session that opened with as-of before
the execute reads one snapshot, so it reads the old values until it closes. A replaced version stays a version, so a
second execute of the same definition rewrites it again.
10.2.2. blackholes/preview
Function(blackholes/preview invocation) → map
Plans a blackhole and changes nothing. invocation is the map
{namespace name args}; args is optional. The result has digest, targets,
matched, replacements, removals, confirm, affected and samples.
10.2.3. blackholes/execute
Function(blackholes/execute approval) → map
Applies a previewed blackhole. approval is the preview's invocation map with
digest, confirm, actor and reason added. digest is the preview's digest and confirm
is its confirmation text. A commit after the preview gives an error with the
conflict code. Execute is refused inside a mutation or a reactor.
(let [invocation {namespace "secrets/keys" name "erase-keys" args ["ada"]}
plan (blackholes/preview invocation)]
(blackholes/execute {namespace "secrets/keys" name "erase-keys" args ["ada"]
digest (get plan "digest") confirm (get plan "confirm")
actor "ops" reason "Erasure request 2291"}))
10.2.4. blackholes/audit
Function(blackholes/audit options?) → list
Returns the audits in transaction order. options is a map with optional
after (a transaction) and limit (a positive integer). Without limit, the
list has every audit after after. Each audit is also the value of a
stardust/blackhole fact that queries can read.
10.2.5. blackholes/status
Function(blackholes/status) → map
Returns {enabled audits recovering backups}.
10.3. Hash values
#hash holds a digest together with the algorithm that produced it. It uses
RON's #prefix value notation, and its payload is itself a tagged element: the
tag names the algorithm and its value is the digest in lowercase hexadecimal.
#hash #sha256 "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
{"#hash": {"#sha256": "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"}}
Import validates the payload: the algorithm tag must name one hashes/digest defines,
and the digest must be lowercase hexadecimal of that algorithm's length.
An invalid payload produces the parse error invalid tag at the tag.
#hash #sha256 "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
#hash #sha256 e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
#hash #sha256 "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
Two #hash values are equal when both the algorithm and the digest are equal,
so digests of the same input under different algorithms are unequal rather
than a type mismatch. A #hash value never equals a string.
10.4. hashes/digest
Function(hashes/digest algorithm value) → hash
Returns a #hash of value under algorithm, a name from this table:
| Algorithm | Digest | Kind |
|---|---|---|
sha256 |
32 bytes | SHA-2, cryptographic |
sha512 |
64 bytes | SHA-2, cryptographic |
sha3-256 |
32 bytes | SHA-3, cryptographic |
sha3-512 |
64 bytes | SHA-3, cryptographic |
xxh3-64 |
8 bytes | XXH3 64-bit, non-cryptographic |
xxh3-128 |
16 bytes | XXH3 128-bit, non-cryptographic |
Every DUST value can be hashed. The digest covers the value's canonical DUST form: the bytes the DUST formatter writes for it, encoded as UTF-8, without the single terminal file newline. All other newlines, including those inside string contents, are kept. Arguments evaluate before hashing, and a quoted form hashes its resulting data. The canonical form follows the formatter exactly:
- A top-level list of two or more forms omits its brackets, so
(hashes/digest "sha256" [1 2])digests the bytes of1and2on separate lines; a one-element list keeps its brackets, and an empty list is empty. - Maps keep their braces and sort their keys, so maps with the same members hash identically regardless of member order.
- Integer
1and float1.0have different forms and digests. #utcand#durpayloads use their canonical spelling, so every spelling of the same instant or duration hashes identically.- Comments are excluded: documenting a form never changes its digest.
- A function hashes as its canonical form: a closure as its
fnsource, and a library function as its quoted name, such as"strings/case". Values captured by a closure are not part of its form. - Unicode text is not normalized.
A form whose known tag has an invalid payload, such as #link true, is
rejected when it is read, so it cannot reach hashes/digest.
The string "abc" has canonical form "abc", including the two quote
characters. Its digests therefore cover five bytes. The empty string has
canonical form "":
| Call | Result |
|---|---|
(hashes/digest "sha256" "abc") |
#hash #sha256 "6cc43f858fbb763301637b5af970e2a46b46f461f27e5a0f41e009c59b827b25" |
(hashes/digest "sha3-256" "abc") |
#hash #sha3-256 "460c09e673f81da9d6604954002d01498dd56bf136c5813e5a5ae2d4c3f2873b" |
(hashes/digest "xxh3-64" "abc") |
#hash #xxh3-64 "236ac2698e6b6688" |
The XXH3 variants are for keys, bucketing, deduplication, and change detection,
never for integrity against an adversary. xxh3-128 makes accidental
collisions negligible where 64 bits are too few, such as content addressing. An unknown algorithm produces
#err <algorithm hash unknown>.
(hashes/digest "sha256" null) (hashes/digest "sha256" "abc") (hashes/digest "sha256" "") (hashes/digest "sha256" 1) (hashes/digest "sha256" 1.0) (hashes/digest "sha256" ["é" "猫"]) (hashes/digest "sha256" `name) (hashes/digest "sha256" ``1) (hashes/digest "sha256" #link 1) (hashes/digest "sha256" #utc "1970-01-01T00:00:00Z") (hashes/digest "sha256" #dur "PT1S") (hashes/digest "sha256" []) (hashes/digest "sha256" {a 1 b 2}) (hashes/digest "sha256" #utc "1970-01-01T00:00:00.0000001Z") (hashes/digest "sha256" #dur "PT0.0000001S")
#hash #sha256 "74234e98afe7498fb5daf1f36ac2d78acc339464f950703b8c019892f982b90b" #hash #sha256 "6cc43f858fbb763301637b5af970e2a46b46f461f27e5a0f41e009c59b827b25" #hash #sha256 "12ae32cb1ec02d01eda3581b127c1fee3b0dc53572ed6baf239721a03d82e126" #hash #sha256 "6b86b273ff34fce19d6b804eff5a3f5747ada4eaa22f1d49c01e52ddb7875b4b" #hash #sha256 "d0ff5974b6aa52cf562bea5921840c032a860a91a3512f7fe8f768f6bbe005f6" #hash #sha256 "8abc6af09be09c055f677c0b9be90c456d450c3afa7fa83fdcf3e0f0326bdd18" #hash #sha256 "82a3537ff0dbce7eec35d69edc3a189ee6f17d82f353a553f9aa96cb0be3ce89" #hash #sha256 "d135669e0056d96659a6969caa40dad4576a10121eaad744521e9a09cdca6a83" #hash #sha256 "e64ae69a6b69823b59a98efc4eee9036bfd5dd2b4c171bd6b040bb649cd6d5e3" #hash #sha256 "c9adbba78bb05b960634a1b7347af953d205ac92212de174e0e3ea8eaacffb0b" #hash #sha256 "5c341cf9f25684580f1ac2fa23afce874bd5134de4bd473176c46ade2e371ab0" #hash #sha256 "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" #hash #sha256 "53a6fbfea11bafdfe07457e9d925dedda5ca93811d422d4af322379990194d45" #hash #sha256 "fac9f162216b9ab80bb07b09c082e2e31eb0d56672ba2227536803ab8e0f10e6" #hash #sha256 "9254d233474e59e0a36a9b6b822a667209b52b755152dbacd409b40ad32b81d0"
(hashes/digest "sha512" "abc") (hashes/digest "sha3-256" "abc") (hashes/digest "sha3-512" "abc") (hashes/digest "xxh3-64" "abc") (hashes/digest "xxh3-128" "abc")
#hash #sha512 "60b7e079eb5dbdb674156850d75d3eae2dc16e08a70aeeb9a658fa5a7546fbc8c5f14328cf5d5321451fec7deba5258a56d81c1ac70b064facba8127da5c18e8" #hash #sha3-256 "460c09e673f81da9d6604954002d01498dd56bf136c5813e5a5ae2d4c3f2873b" #hash #sha3-512 "47070e8f45799540c361c6d92c2df5b2a54f25ff2a19bc8d2da1ef70ddcff117137baf4e206e56528e9eca14aea6a3ea24e4dfa942447d4a92dce09078f93128" #hash #xxh3-64 "236ac2698e6b6688" #hash #xxh3-128 "590cff53cfd1122698f832b385c169a4"
(= (hashes/digest "sha256" {a 1 b 2}) (hashes/digest "sha256" {a 1 b 2})) (comparisons/not= (hashes/digest "sha256" 1) (hashes/digest "sha256" 1.0)) (comparisons/not= (hashes/digest "sha256" "é") (hashes/digest "sha256" "é"))
true true true
(comparisons/not= (hashes/digest "sha256" "abc") (hashes/digest "sha3-256" "abc")) (comparisons/not= (hashes/digest "xxh3-64" "abc") (hashes/digest "xxh3-128" "abc")) (= (hashes/digest "xxh3-64" "abc") #hash #xxh3-64 "236ac2698e6b6688")
true true true
(hashes/digest "sha256" (fn [] 1))
#hash #sha256 "06d0dff99f70155bfd64b168de5c36cede11e9c14ddf87358cbb89ea9f08ce69"
(hashes/digest "sha256" [(fn [] 1)])
#hash #sha256 "b6ca49a321d2250ae8533a020a3fbf07d9942b3af2e67728b342ed4b73f86d0e"
11 Bitset Functions
A Bitset is an immutable set of integers from 0 through 253−1. Members
iterate in ascending order. DUST, RON and EDN spell the set as
#bitset [1 5 [100 200] 1000000]. Each maximal run of at least three
members is a half-open [start end] pair; shorter runs are individual
members. The empty set is #bitset []. Input may repeat or reorder members
and overlap ranges. Encoders normalize these to the same canonical form.
JSON uses {"#bitset": [1, 5, [100, 200], 1000000]}. TRON uses the bitset
tag around binary data containing portable roaring64 bytes.
Equal sets have equal portable bytes and compare equal.
Bitsets support count, empty?, seq, map and reduce. Their sequence
contains members in ascending order. Default ordering is undefined: sort
and < reject Bitsets with #err <mismatch type>. A custom comparator can
supply an order. Every edit and set operation returns a new value.
Invalid member types give #err <mismatch type>; negative or excessive
members and reversed bounds give #err <invalid value>. Literal malformed
payloads are invalid tags. A half-open range's end may be 253 to include the
largest member. Constructors take any number of items, a range can span any
number of members, and a sequence expands every member. Portable input and
output have no size limit. Operations that exceed available resources,
such as the runtime's memory budget, produce #err <limit resource>; an
excessive literal is an invalid tag.
11.1. bitsets/of
Function(bitsets/of values) → bitset
Build a set from a list of integer members. Duplicate members appear once.
(bitsets/of [5 1 5 3]) (bitsets/of []) (bitsets/of [9007199254740991 0 4294967296])
#bitset [1 3 5] #bitset [] #bitset [0 4294967296 9007199254740991]
11.2. bitsets/range
Function(bitsets/range start end) → bitset
Build the half-open interval from start through end−1. Equal bounds make an empty set.
(bitsets/range 100 200) (bitsets/range 0 0) (bitsets/range 9007199254740991 9007199254740992)
#bitset [[100 200]] #bitset [] #bitset [9007199254740991]
11.3. bitsets/contains?
Function(bitsets/contains? set member) → boolean
Test whether the set contains member.
11.6. bitsets/xor
Function(bitsets/xor a b ... more) → bitset
Take the symmetric difference of two or more sets, from left to right.
11.7. bitsets/and-not
Function(bitsets/and-not a b ... more) → bitset
Remove every member of b and the later sets from a.
11.8. bitsets/min
Function(bitsets/min set) → integer or null
Return the smallest member, or null for an empty set.
11.9. bitsets/max
Function(bitsets/max set) → integer or null
Return the largest member, or null for an empty set.
(bitsets/max #bitset []) (bitsets/max #bitset [1 9007199254740991])
null 9007199254740991
11.10. bitsets/rank
Function(bitsets/rank set member) → integer
Count members less than or equal to member.
11.11. bitsets/select
Function(bitsets/select set index) → integer or null
Return the member at a zero-based index, or null when the index is outside the set.
(bitsets/select #bitset [1 5] 1) (bitsets/select #bitset [1 5] 2) (bitsets/select #bitset [] 0)
5 null null
11.12. bitsets/subset?
Function(bitsets/subset? a b) → boolean
Test whether every member of a belongs to b.
(bitsets/subset? #bitset [1 2] #bitset [[0 10]]) (bitsets/subset? #bitset [1] #bitset [])
true false
11.13. bitsets/intersects?
Function(bitsets/intersects? a b) → boolean
Test whether a and b share any member.
(bitsets/intersects? #bitset [1 5] #bitset [5]) (bitsets/intersects? #bitset [] #bitset [1])
true false
11.14. bitsets/and-count
Function(bitsets/and-count a b) → integer
Count the intersection without constructing a result set.
11.15. bitsets/add
Function(bitsets/add set member ... more) → bitset
Add one or more members. Adding a present member has no effect.
11.16. bitsets/remove
Function(bitsets/remove set member ... more) → bitset
Remove one or more members. Removing an absent member has no effect.
11.17. bitsets/slice
Function(bitsets/slice set start end) → bitset
Keep only members in the half-open interval [start, end).
(bitsets/slice #bitset [[1 100]] 10 20) (bitsets/slice #bitset [1] 0 0)
#bitset [[10 20]] #bitset []
11.18. Validation
(bitsets/of [-1])
(bitsets/of [9007199254740992])
(bitsets/of [1.0])
(bitsets/range 10 0)
(bitsets/contains? [] 1)
(bitsets/contains? #bitset [] -1)
(bitsets/select #bitset [1] -1)
(bitsets/select #bitset [1] 9223372036854775807)
(bitsets/add #bitset [] -1)
(bitsets/remove #bitset [] 1.0)
(bitsets/slice #bitset [] 2 1)
(bitsets/and #bitset [] [])
(bitsets/of null)
(= #bitset [] #bitset [])
(sort [#bitset [2] #bitset [1]])
(map (fn [x] (+ x 1)) #bitset [])
#err <invalid value>
#err <invalid value>
#err <mismatch type>
#err <invalid value>
#err <mismatch type>
#err <invalid value>
null
null
#err <invalid value>
#err <mismatch type>
#err <invalid value>
#err <mismatch type>
#bitset []
true
#err <mismatch type>
[]
(count (seq (bitsets/range 0 1000001)))
(= (seq (bitsets/range 0 2097153)) (lists/range 2097153))
(reduce
(fn [total member] (+ total member))
0
(seq (bitsets/or (bitsets/range 0 1048577) (bitsets/range 4294967296 4294967299))))
(bitsets/range 0 4295032832)
(count (bitsets/range 0 4295032832))
1000001
true
562641240067
#bitset [[0 4295032832]]
4295032832
11.19. Predicates and sequences
bitset? tests the kind without converting it. count reports the number
of distinct members; empty? tests whether that count is zero. seq
materializes the ascending list. map and reduce visit the same order.
12 Bytes Functions
The bytes/ library builds, searches, and combines binary values.
12.1. Bytes values
A Bytes value is a sequence of bytes of any length. In DUST, RON, and EDN it
uses the #b64 prefix with its bytes in base64 text. TRON stores the bytes
directly as a bin value.
#b64 "F8gHWw=="
{"#b64": "F8gHWw=="}
The payload is canonical padded standard base64 (RFC 4648 section 4): a
multiple of four characters from A-Z, a-z, 0-9, +, and /, with = only
as the last one or two characters, and with the unused bits of the last
character zero. Each byte sequence thus has exactly one spelling. The empty
value is #b64 "". Any other payload produces the parse error invalid tag at the tag.
{a #b64 "aGk=" l [#b64 "" #b64 "AQID"]}
a #b64 aGk= l [#b64 "" #b64 AQID]
{a #b64 "aGk=" l [#b64 "" #b64 "AQID"]}
Two Bytes values are equal when they have the same bytes. A Bytes value never equals a string, and comparing the two is a type mismatch. Bytes order by their byte values from the first byte, and a prefix sorts before a longer value.
(= #b64 "aGk=" #b64 "aGk=") (= #b64 "aGk=" #b64 "aGo=") (= #b64 "" #b64 "") (= #b64 "" (bytes/slice #b64 "aGk=" 1 1)) (= [#b64 "aGk="] [#b64 "aGk="]) (= {a #b64 "aGk="} {a #b64 "aGo="}) (comparisons/not= #b64 "aGk=" #b64 "aGk=") (= #b64 "aGk=" "aGk=")
true false true true true false false #err {<mismatch type> message "equality requires matching types"}
(compare #b64 "AA==" #b64 "AQ==") (compare #b64 "AQ==" #b64 "AA==") (compare #b64 "AA==" #b64 "AA==") (compare #b64 "" #b64 "AA==") (compare #b64 "AA==" #b64 "AAA=") (compare #b64 "/w==" #b64 "AAA=") (< #b64 "fw==" #b64 "gA==") (<= #b64 "gA==" #b64 "gA==") (> #b64 "AA==" #b64 "") (sort [#b64 "/w==" #b64 "AAA=" #b64 "" #b64 "AA=="]) (distinct [#b64 "aGk=" #b64 "aGk=" #b64 ""]) (compare #b64 "AA==" "AA==")
-1 1 0 -1 -1 1 true true true [#b64 "" #b64 "AA==" #b64 "AAA=" #b64 "/w=="] [#b64 "aGk=" #b64 ""] #err {<mismatch type> message "ordering requires matching types"}
Core functions read a Bytes value as its byte values, the integers 0 to 255:
count and empty? use the number of bytes,
get selects one byte, and the functions that read a list or a pointer,
such as map, reduce, first, and lists/filter, read the bytes
in order. Their results are lists, because a function can return a value that
is not a byte; bytes/of makes a list of byte values into Bytes again.
Functions that change a list in place do not accept Bytes.
An empty result is #b64 "". null means that a value is absent, such as a
search that finds nothing. The bitwise operators and the codecs reject null.
12.2. bytes/of
Function(bytes/of values) → bytes
Returns Bytes with one byte for each integer in the list values. null is an
empty list. Each element must be an integer from 0 to 255; any other element
is an error, and no value is truncated. An element is a byte value, not a
number to store: (bytes/of [1.5]) is an error. The
encoding library writes a number as its 8 bytes.
(bytes/of [104 105]) (bytes/of []) (bytes/of null) (bytes/of [0 255]) (bytes/of (map (fn [x] (+ x 1)) #b64 "AAEC")) (bytes/of [256]) (bytes/of [-1]) (bytes/of [1.5]) (bytes/of ["a"]) (bytes/of [null]) (bytes/of #b64 "aGk=") (bytes/of "hi")
#b64 "aGk=" #b64 "" #b64 "" #b64 "AP8=" #b64 "AQID" #err {<invalid value> message "byte values must be 0 to 255"} #err {<invalid value> message "byte values must be 0 to 255"} #err {<mismatch type> message "byte values must be integers"} #err {<mismatch type> message "byte values must be integers"} #err {<mismatch type> message "byte values must be integers"} #err {<mismatch type> message "expected a list or null"} #err {<mismatch type> message "expected a list or null"}
12.3. bytes/concat
Function(bytes/concat buffers*) → bytes
Returns the bytes of every argument joined in order. Without arguments it
returns #b64 "". A null argument adds no bytes.
(bytes/concat) (bytes/concat #b64 "aGk=") (bytes/concat #b64 "aGk=" #b64 "IQ==") (bytes/concat #b64 "aGk=" null #b64 "" #b64 "IQ==") (bytes/concat null) (bytes/concat null null) (= (bytes/concat) #b64 "") (bytes/concat #b64 "aGk=" "hi") (bytes/concat [104 105])
#b64 "" #b64 "aGk=" #b64 "aGkh" #b64 "aGkh" #b64 "" #b64 "" true #err {<mismatch type> message "expected bytes"} #err {<mismatch type> message "expected bytes"}
12.4. bytes/slice
Function(bytes/slice b start) → bytes
(bytes/slice b start end) → bytes
Returns the bytes from index start up to, but not including, index end.
end defaults to the byte count. The bounds must be integers with
0 ≤ start ≤ end ≤ (count b). Any other bounds produce
#err <bounds index>; a slice never returns fewer bytes than its bounds name.
(bytes/slice #b64 "F8gHWw==" 1 3) (bytes/slice #b64 "F8gHWw==" 1) (bytes/slice #b64 "F8gHWw==" 0) (bytes/slice #b64 "F8gHWw==" 0 4) (bytes/slice #b64 "F8gHWw==" 4) (bytes/slice #b64 "F8gHWw==" 2 2) (bytes/slice #b64 "" 0 0) (bytes/slice #b64 "F8gHWw==" 1 99) (bytes/slice #b64 "F8gHWw==" 5) (bytes/slice #b64 "F8gHWw==" 3 1) (bytes/slice #b64 "F8gHWw==" -1 2) (bytes/slice #b64 "F8gHWw==" 0 9223372036854775807) (bytes/slice #b64 "F8gHWw==" 1.0 2) (bytes/slice #b64 "F8gHWw==" 0 null) (bytes/slice null 0) (bytes/slice "text" 0 1)
#b64 "yAc=" #b64 "yAdb" #b64 "F8gHWw==" #b64 "F8gHWw==" #b64 "" #b64 "" #b64 "" #err {<bounds index> message "slice bound outside bytes"} #err {<bounds index> message "slice bound outside bytes"} #err {<bounds index> message "slice start after its end"} #err {<bounds index> message "slice bound outside bytes"} #err {<bounds index> message "slice bound outside bytes"} #err {<mismatch type> message "slice bounds must be integers"} #err {<mismatch type> message "slice bounds must be integers"} #err {<mismatch type> message "expected bytes"} #err {<mismatch type> message "expected bytes"}
12.5. bytes/index-of
Function(bytes/index-of b needle) → integer
null
(bytes/index-of b needle start) → integer
null
Returns the index of the first occurrence of the Bytes needle in b at or
after start, or null if there is none. start defaults to zero and is
limited to the range from zero to the byte count, as in
strings/index-of. An empty needle is found at the limited start.
(bytes/index-of #b64 "F8gHWw==" #b64 "Bw==") (bytes/index-of #b64 "F8gHWw==" #b64 "yAc=") (bytes/index-of #b64 "F8gHWw==" #b64 "Bw==" 2) (bytes/index-of #b64 "F8gHWw==" #b64 "Bw==" 3) (bytes/index-of #b64 "F8gHWw==" #b64 "Bw==" -5) (bytes/index-of #b64 "F8gHWw==" #b64 "Bw==" 99) (bytes/index-of #b64 "F8gHWw==" #b64 "/w==") (bytes/index-of #b64 "YWFh" #b64 "YWE=" 1) (bytes/index-of #b64 "F8gHWw==" #b64 "") (bytes/index-of #b64 "F8gHWw==" #b64 "" 3) (bytes/index-of #b64 "F8gHWw==" #b64 "" 99) (bytes/index-of #b64 "F8gHWw==" #b64 "" -9) (bytes/index-of #b64 "" #b64 "") (bytes/index-of #b64 "" #b64 "AA==") (bytes/index-of #b64 "AAAB" #b64 "AAE=") (bytes/index-of #b64 "F8gHWw==" #b64 "Bw==" 9223372036854775807) (bytes/index-of #b64 "F8gHWw==" #b64 "Bw==" 1.0) (bytes/index-of #b64 "F8gHWw==" #b64 "Bw==" null) (bytes/index-of #b64 "F8gHWw==" 7) (bytes/index-of null #b64 "Bw==") (bytes/index-of #b64 "F8gHWw==" null)
2 1 2 null 2 null null 1 0 3 4 0 0 null 1 null #err {<mismatch type> message "search start must be an integer"} #err {<mismatch type> message "search start must be an integer"} #err {<mismatch type> message "expected bytes"} #err {<mismatch type> message "expected bytes"} #err {<mismatch type> message "expected bytes"}
12.6. bytes/and
Function(bytes/and a b more*) → bytes
Returns the bitwise AND of two or more Bytes values of equal length. Values of different lengths are an error.
(bytes/and #b64 "/w==" #b64 "Dw==") (bytes/and #b64 "/w8=" #b64 "D/8=" #b64 "AwM=") (bytes/and #b64 "" #b64 "") (bytes/and #b64 "/w==" #b64 "Dw8=") (bytes/and #b64 "/w==") (bytes/and #b64 "/w==" null) (bytes/and null #b64 "/w==") (bytes/and #b64 "/w==" 15)
#b64 "Dw==" #b64 "AwM=" #b64 "" #err {<invalid value> message "bytes/and requires bytes of equal length"} #err {<arity mismatch> message "wrong number of arguments"} #err {<mismatch type> message "expected bytes"} #err {<mismatch type> message "expected bytes"} #err {<mismatch type> message "expected bytes"}
12.7. bytes/or
Function(bytes/or a b more*) → bytes
Returns the bitwise OR of two or more Bytes values of equal length. Values of different lengths are an error.
(bytes/or #b64 "8A==" #b64 "Dw==") (bytes/or #b64 "AQA=" #b64 "AAI=" #b64 "BAA=") (bytes/or #b64 "" #b64 "") (bytes/or #b64 "/w==" #b64 "Dw8=") (bytes/or #b64 "/w==") (bytes/or #b64 "/w==" null)
#b64 "/w==" #b64 "BQI=" #b64 "" #err {<invalid value> message "bytes/or requires bytes of equal length"} #err {<arity mismatch> message "wrong number of arguments"} #err {<mismatch type> message "expected bytes"}
12.8. bytes/xor
Function(bytes/xor a b more*) → bytes
Returns the bitwise exclusive OR of two or more Bytes values of equal length. Values of different lengths are an error.
(bytes/xor #b64 "/w==" #b64 "Dw==") (bytes/xor #b64 "F8gHWw==" #b64 "F8gHWw==") (bytes/xor #b64 "AQI=" #b64 "AwQ=" #b64 "BQY=") (= #b64 "F8gHWw==" (bytes/xor (bytes/xor #b64 "F8gHWw==" #b64 "qlWqVQ==") #b64 "qlWqVQ==")) (bytes/xor #b64 "" #b64 "") (bytes/xor #b64 "/w==" #b64 "Dw8=") (bytes/xor #b64 "/w==") (bytes/xor null #b64 "/w==")
#b64 "8A==" #b64 "AAAAAA==" #b64 "BwA=" true #b64 "" #err {<invalid value> message "bytes/xor requires bytes of equal length"} #err {<arity mismatch> message "wrong number of arguments"} #err {<mismatch type> message "expected bytes"}
12.9. bytes/not
Function(bytes/not b) → bytes
Returns b with every bit inverted.
(bytes/not #b64 "AP8=") (bytes/not #b64 "") (= #b64 "F8gHWw==" (bytes/not (bytes/not #b64 "F8gHWw=="))) (bytes/not null) (bytes/not "AP8=") (bytes/not #b64 "AA==" #b64 "AA==")
#b64 "/wA=" #b64 "" true #err {<mismatch type> message "expected bytes"} #err {<mismatch type> message "expected bytes"} #err {<arity mismatch> message "wrong number of arguments"}
12.10. bytes/shift-left
Function(bytes/shift-left b n) → bytes
Returns b shifted left by n bits as one number, with the first byte most
significant. The byte count stays the same. Bits shifted past the first byte
are lost, and the vacated bits are zero. n must be a nonnegative integer. A
shift of the bit length or more returns all zero bytes, and a shift of zero
returns equal Bytes.
(bytes/shift-left #b64 "AQI=" 4) (bytes/shift-left #b64 "AQI=" 8) (bytes/shift-left #b64 "AQI=" 9) (bytes/shift-left #b64 "AQI=" 15) (bytes/shift-left #b64 "AQI=" 16) (bytes/shift-left #b64 "AQI=" 9223372036854775807) (bytes/shift-left #b64 "AQI=" 0) (bytes/shift-left #b64 "" 3) (bytes/shift-left #b64 "gA==" 1) (bytes/shift-left #b64 "AQI=" -1) (bytes/shift-left #b64 "AQI=" 1.0) (bytes/shift-left #b64 "AQI=" null) (bytes/shift-left null 1)
#b64 "ECA=" #b64 "AgA=" #b64 "BAA=" #b64 "AAA=" #b64 "AAA=" #b64 "AAA=" #b64 "AQI=" #b64 "" #b64 "AA==" #err {<invalid value> message "shift count must be nonnegative"} #err {<mismatch type> message "shift count must be an integer"} #err {<mismatch type> message "shift count must be an integer"} #err {<mismatch type> message "expected bytes"}
12.11. bytes/shift-right
Function(bytes/shift-right b n) → bytes
Returns b shifted right by n bits as one number, with the first byte most
significant. The shift is logical: the vacated bits are zero. The byte count
stays the same, and bits shifted past the last byte are lost. n must be a
nonnegative integer. A shift of the bit length or more returns all zero bytes.
(bytes/shift-right #b64 "AQI=" 4) (bytes/shift-right #b64 "AQI=" 8) (bytes/shift-right #b64 "gAA=" 15) (bytes/shift-right #b64 "gAA=" 16) (bytes/shift-right #b64 "AQI=" 9223372036854775807) (bytes/shift-right #b64 "AQI=" 0) (bytes/shift-right #b64 "" 3) (bytes/shift-right #b64 "AQ==" 1) (= #b64 "AAI=" (bytes/shift-right (bytes/shift-left #b64 "AQI=" 8) 8)) (bytes/shift-right #b64 "AQI=" -1) (bytes/shift-right null 1)
#b64 "ABA=" #b64 "AAE=" #b64 "AAE=" #b64 "AAA=" #b64 "AAA=" #b64 "AQI=" #b64 "" #b64 "AA==" true #err {<invalid value> message "shift count must be nonnegative"} #err {<mismatch type> message "expected bytes"}
13 Encoding Functions
The encoding/ library converts between Bytes and strings, numbers or collections
with a named codec. The codec is always given; there is no default.
| Codec | encoding/encode |
encoding/decode |
|---|---|---|
hex |
Bytes to lowercase hexadecimal text | Hexadecimal text of either case to Bytes |
utf8 |
A string to its UTF-8 bytes | UTF-8 bytes to a string |
i64le, i64be |
An integer to its 8 bytes | 8 bytes to an integer |
f64le, f64be |
A number to the 8 bytes of its float | 8 bytes to a float |
bencode |
Integers, strings, Bytes, lists and maps to Bytes | Bytes to integers, Bytes, lists and maps |
A number codec names its byte order: le writes the least significant byte
first (little-endian) and be the most significant byte first (big-endian).
Options are supplied as the final argument, after the value. An option that
the codec does not define is an error. null is not a valid value for a codec.
13.1. encoding/encode
Function(encoding/encode codec value) → string
bytes
(encoding/encode codec value options) → string
bytes
Encodes value with codec. hex takes Bytes and returns two lowercase
hexadecimal digits for each byte. utf8 takes a string and returns its bytes.
No codec defines an option for encoding.
(encoding/encode "hex" #b64 "F8gHWw==") (encoding/encode "hex" #b64 "") (encoding/encode "hex" #b64 "AP8=" {}) (encoding/encode "utf8" "hi") (encoding/encode "utf8" "") (encoding/encode "utf8" "hé") (encoding/encode "utf8" ~"a,(+ 1 2)") (map (functions/partial :encoding/encode "hex") [#b64 "AA==" #b64 "/w=="]) (encoding/encode "hex" null) (encoding/encode "hex" "text") (encoding/encode "utf8" null) (encoding/encode "utf8" #b64 "aGk=") (encoding/encode "hex" #b64 "AA==" {errors "replace"}) (encoding/encode "utf8" "hi" {errors "replace"}) (encoding/encode "hex" #b64 "AA==" "opts") (encoding/encode "base32" #b64 "AA==") (encoding/encode null #b64 "AA==") (encoding/encode "hex")
"17c8075b" "" "00ff" #b64 "aGk=" #b64 "" #b64 "aMOp" #b64 "YTM=" ["00" "ff"] #err {<mismatch type> message "expected bytes"} #err {<mismatch type> message "expected bytes"} #err {<mismatch type> message "expected a string"} #err {<mismatch type> message "expected a string"} #err {<invalid value> message "unsupported codec option"} #err {<invalid value> message "unsupported codec option"} #err {<mismatch type> message "codec options must be a map"} #err {<invalid value> message "unknown codec"} #err {<mismatch type> message "expected a string"} #err {<arity mismatch> message "wrong number of arguments"}
i64le and i64be take an integer and return its 8 bytes in two's
complement. f64le and f64be take a float and return the 8 bytes of its
IEEE 754 binary64 form. They also take an integer, as the float equal to it; an
integer beyond 253 in magnitude, which a float might not hold exactly, is an
error. To make a list of numbers into Bytes, encode each number and join the
results with bytes/concat.
(encoding/encode "f64le" 1.5) (encoding/encode "f64be" 1.5) (encoding/encode "f64le" 1) (encoding/encode "f64be" -0.0) (encoding/encode "i64le" 1) (encoding/encode "i64be" 258) (encoding/encode "i64le" -9223372036854775808) (encoding/encode "i64be" 9223372036854775807) (bytes/concat (encoding/encode "i64be" 1) (encoding/encode "f64be" 2.5)) (map (functions/partial :encoding/encode "i64be") [0 -1]) (encoding/encode "i64le" 1 {}) (encoding/encode "f64le" 9007199254740993) (encoding/encode "i64le" 1.5) (encoding/encode "f64le" "1.5") (encoding/encode "f64le" null) (encoding/encode "i64le" 1 {errors "replace"}) (encoding/encode "f64" 1.5) (encoding/encode "f32le" 1.5)
#b64 "AAAAAAAA+D8=" #b64 "P/gAAAAAAAA=" #b64 "AAAAAAAA8D8=" #b64 "gAAAAAAAAAA=" #b64 "AQAAAAAAAAA=" #b64 "AAAAAAAAAQI=" #b64 "AAAAAAAAAIA=" #b64 "f/////////8=" #b64 "AAAAAAAAAAFABAAAAAAAAA==" [#b64 "AAAAAAAAAAA=" #b64 "//////////8="] #b64 "AQAAAAAAAAA=" #err {<invalid value> message "integer is not exact as a float"} #err {<mismatch type> message "codec requires an integer"} #err {<mismatch type> message "codec requires a number"} #err {<mismatch type> message "codec requires a number"} #err {<invalid value> message "unsupported codec option"} #err {<invalid value> message "unknown codec"} #err {<invalid value> message "unknown codec"}
13.2. encoding/decode
Function(encoding/decode codec value) → value
(encoding/decode codec value options) → value
Reverses encoding/encode for codec. hex takes a string of hexadecimal
digit pairs of either case and returns Bytes; an odd length or any other
character is an error. utf8 takes Bytes and returns a string.
UTF-8 decoding is strict: bytes that are not well-formed UTF-8 are an error.
With the option {errors "replace"}, each byte of a malformed sequence becomes
U+FFFD instead. {errors "strict"} names the default.
(encoding/decode "hex" "17c8075b") (encoding/decode "hex" "17C8075B") (encoding/decode "hex" "") (encoding/decode "utf8" #b64 "aGk=") (encoding/decode "utf8" #b64 "") (encoding/decode "utf8" #b64 "aMOp") (encoding/decode "utf8" #b64 "aGk=" {errors "strict"}) (encoding/decode "utf8" #b64 "/2hp" {errors "replace"}) (encoding/decode "utf8" #b64 "aP/+aQ==" {errors "replace"}) (encoding/decode "utf8" #b64 "4oI=" {errors "replace"}) (encoding/decode "utf8" #b64 "aGk=" {}) (map (fn [value] (encoding/decode "utf8" value {errors "replace"})) [#b64 "aGk=" #b64 "/w=="]) (= #b64 "F8gHWw==" (encoding/decode "hex" (encoding/encode "hex" #b64 "F8gHWw=="))) (= "hé" (encoding/decode "utf8" (encoding/encode "utf8" "hé"))) (encoding/decode "hex" "17c") (encoding/decode "hex" "zz") (encoding/decode "hex" "0x17") (encoding/decode "hex" #b64 "AA==") (encoding/decode "hex" null) (encoding/decode "utf8" #b64 "/2hp") (encoding/decode "utf8" #b64 "/2hp" {errors "strict"}) (encoding/decode "utf8" #b64 "7aCA") (encoding/decode "utf8" #b64 "wIA=") (encoding/decode "utf8" "hi") (encoding/decode "utf8" null) (encoding/decode "utf8" #b64 "aGk=" {errors "ignore"}) (encoding/decode "utf8" #b64 "aGk=" {errors 1}) (encoding/decode "utf8" #b64 "aGk=" {mode "x"}) (encoding/decode "hex" "00" {errors "replace"}) (encoding/decode "latin1" #b64 "aGk=")
#b64 "F8gHWw==" #b64 "F8gHWw==" #b64 "" "hi" "" "hé" "hi" "�hi" "h��i" "��" "hi" ["hi" "�"] true true #err {<invalid value> message "hex text must have an even length"} #err {<invalid value> message "invalid hex text"} #err {<invalid value> message "invalid hex text"} #err {<mismatch type> message "expected a string"} #err {<mismatch type> message "expected a string"} #err {<invalid value> message "invalid UTF-8"} #err {<invalid value> message "invalid UTF-8"} #err {<invalid value> message "invalid UTF-8"} #err {<invalid value> message "invalid UTF-8"} #err {<mismatch type> message "expected bytes"} #err {<mismatch type> message "expected bytes"} #err {<invalid value> message "errors must be strict or replace"} #err {<mismatch type> message "expected a string"} #err {<invalid value> message "unsupported codec option"} #err {<invalid value> message "unsupported codec option"} #err {<invalid value> message "unknown codec"}
The number codecs take Bytes of exactly 8 bytes; any other count is an
error. i64le and i64be return an integer. f64le and f64be return a
float; bytes that spell an infinity or a NaN are an error, because DUST
floats are finite.
(encoding/decode "f64le" #b64 "AAAAAAAA+D8=") (encoding/decode "f64be" #b64 "P/gAAAAAAAA=") (encoding/decode "f64le" (encoding/encode "f64le" 2.0)) (encoding/decode "i64be" #b64 "AAAAAAAAAQI=") (encoding/decode "i64le" #b64 "AQIAAAAAAAA=") (encoding/decode "i64le" (encoding/encode "i64le" -9223372036854775808)) (encoding/decode "i64be" #b64 "//////////8=") (= 12345.678 (encoding/decode "f64be" (encoding/encode "f64be" 12345.678))) (encoding/decode "f64le" #b64 "AAAAAAAA8H8=") (encoding/decode "f64le" #b64 "AAAAAAAA+H8=") (encoding/decode "i64le" #b64 "AQI=") (encoding/decode "f64be" #b64 "") (encoding/decode "f64le" "AAAAAAAA+D8=") (encoding/decode "i64le" null) (encoding/decode "i64le" 258)
1.5 1.5 2.0 258 513 -9223372036854775808 -1 true #err {<float overflow> message "floating-point overflow"} #err {<float overflow> message "floating-point overflow"} #err {<invalid value> message "codec requires 8 bytes"} #err {<invalid value> message "codec requires 8 bytes"} #err {<mismatch type> message "expected bytes"} #err {<mismatch type> message "expected bytes"} #err {<mismatch type> message "expected bytes"}
13.3. Bencode
encoding/encode "bencode" accepts signed i64 integers, text, Bytes, lists
and maps. Text is encoded as UTF-8. Dictionaries have text keys and are written
in raw byte order. Floats, booleans, null, functions and cyclic collections
cannot be represented. Decoding returns DUST values directly, without an
intermediate Document. Byte-string values remain Bytes by default; <utf8>
decodes them as strict UTF-8 text. Dictionary keys must always be valid UTF-8.
Decoding rejects truncated values, duplicate keys, noncanonical integer/length
spellings, integers outside i64, and trailing bytes. Unsorted dictionaries are
accepted for protocol interoperability. Add <canonical> to require sorted
keys; combine it with text decoding as <canonical utf8>. Collections nest
to any depth, and allocations count toward the memory budget.
(def message {op "eval" code "(+ 1 2 3)"})
(def wire (encoding/encode "bencode" message))
(tests/equal "d4:code9:(+ 1 2 3)2:op4:evale" (encoding/decode "utf8" wire))
(tests/equal message (encoding/decode "bencode" wire <utf8>))
(tests/equal #b64 "AP8=" (encoding/decode "bencode" #b64 "MjoA/w=="))
(io/stdout/println "Bencode checks passed")
| Signature | Result |
|---|---|
(encoding/bencode/encode value [options]) |
Same as encoding/encode "bencode"; no encoding options |
(encoding/bencode/decode bytes [options]) |
One decoded value; options utf8 and canonical |
(encoding/bencode/read reader [options]) |
One value, or null at clean EOF |
(encoding/bencode/read-frame reader [options]) |
One complete nREPL dictionary as its original Bytes |
(encoding/bencode/write writer value [options]) |
Encode and write a value; return the byte count |
A reader is a buffered reader or a callback accepting a byte count and
returning up to that many Bytes, null at EOF, or an error. Reads stop at the
value's boundary, so the next call can read another message. read-frame
retains the original encoding and accepts arbitrary-size wire integers. It
builds no value, so a frame can nest to any depth that memory allows.
Converting such a frame to a DUST value still requires integers to fit i64.
Messages have no size limit of their own. The one bound comes from Bytes:
one bencode string, and one frame from read-frame, becomes one Bytes value,
and a Bytes value holds at most 2,147,483,392 bytes, the longest string LuaJIT
represents. A string whose declared length passes that bound fails before its
bytes are read. A frame fails as soon as the bytes it needs pass the bound:
before a string whose declared length would take it past, or at any later
byte, including the closing e.
A writer is a stream or a callback accepting Bytes and returning the positive
number written. Partial writes are completed automatically. Writing does not
close the stream. Stream options contain timeout; reads also accept utf8
and canonical. The timeout applies to each underlying I/O call. Callbacks
control their own I/O deadlines. After a malformed, truncated or timed-out
stream read, close the connection; decoding cannot resume a partial value.
14 Cryptography
The crypto/ library provides Ed25519 signatures, PASETO v4.public tokens and
host-backed random generators. Keys, signatures, messages, footers and implicit
assertions are Bytes. Tokens are strings.
14.1. Secure random generators
Function(crypto/random) → generator
Creates a generator backed by the operating system's secure entropy source.
Use it with random/int, random/float, random/choose, random/shuffle and
random/bytes, with the same bounds and validation as a seeded generator:
(let [g (crypto/random)]
[(random/int g 0 100)
(random/choose g [Atreides Fremen])
(random/bytes g 32)])
Secure randomness requires permission for each evaluation, including calls to a
function that captured a generator earlier. The stardust command grants this
permission when the io plugin is explicitly selected.
Linux, macOS and Windows supply entropy; other targets report it unavailable.
Host entropy failures return #err <crypto entropy>; they never select a seeded
fallback. Empty byte requests and shuffles of zero or one items draw no entropy.
Returning or encoding a secure generator is an
error: their state cannot be serialized. Seeded generators keep their existing
reproducible sequence and #rng representation. Without a grant:
14.2. Ed25519
| Signature | Result |
|---|---|
(crypto/sign/ed25519/generate-keypair [seed]) |
{private seed public key}. With a 32-byte seed, requires stdlib and no grant. Without a seed, requires io and the secure-random grant for host entropy. |
(crypto/sign/ed25519/public-key seed) |
32-byte public key |
(crypto/sign/ed25519/sign seed message) |
64-byte signature |
(crypto/sign/ed25519/verify key message signature) |
Boolean signature validity |
(crypto/sign/ed25519/import-private bytes) |
Checked 32-byte seed |
(crypto/sign/ed25519/export-private seed) |
Checked 32-byte seed |
(crypto/sign/ed25519/import-public bytes) |
Checked public-key encoding |
(crypto/sign/ed25519/export-public key) |
Checked public-key encoding |
The private representation is the seed, not a 64-byte expanded private key.
Import/export use raw Bytes; they do not read PEM or DER. Wrong argument kinds
or lengths are errors. A correctly sized invalid signature returns false.
All operations except seedless key generation require no entropy grant.
Private seeds are ordinary Bytes: callers must keep them secret.
This example uses a public test seed. Never use it for real keys.
(let [keys (crypto/sign/ed25519/generate-keypair (encoding/decode "hex" "b4cbfb43df4ce210727d953e4a713307fa19bb7d9f85041438d9e11b942a3774")) message (encoding/encode "utf8" "House Atreides") signature (crypto/sign/ed25519/sign (get keys "private") message)] [(count signature) (crypto/sign/ed25519/verify (get keys "public") message signature) (crypto/sign/ed25519/verify (get keys "public") #b64 "" signature)])
(let [keys (crypto/sign/ed25519/generate-keypair (encoding/decode "hex" "b4cbfb43df4ce210727d953e4a713307fa19bb7d9f85041438d9e11b942a3774")) message (encoding/encode "utf8" "House Atreides") signature (crypto/sign/ed25519/sign (get keys "private") message)] [(count signature) (crypto/sign/ed25519/verify (get keys "public") message signature) (crypto/sign/ed25519/verify (get keys "public") #b64 "" signature)])
64 true false
14.3. PASETO v4.public
Only v4.public is supported. It authenticates the message and footer; both remain readable in the token. The implicit assertion is authenticated but is not included in the token.
| Signature | Result |
|---|---|
(crypto/paseto/v4/public/public-key seed) |
Ed25519 public key, using the same Bytes representation |
(crypto/paseto/v4/public/sign seed message [opts]) |
Signed token string, with optional footer or implicit assertion |
(crypto/paseto/v4/public/verify key token [opts]) |
{<verified> message bytes footer bytes} after the requested checks |
(crypto/paseto/v4/public/parse token [opts]) |
{<!verified> message bytes footer bytes}, with an optional length limit |
sign options are footer and implicit, both Bytes. verify accepts
implicit, expected-footer (Bytes), and max-length (positive integer).
Supplying an empty expected-footer requires an empty footer. parse accepts
only max-length. The default maximum input token length is 4096 bytes.
Signing does not impose that limit; raise it explicitly when verifying a
larger token. Unsupported options, malformed tokens and failed verification
return errors.
(let [seed (encoding/decode "hex" "b4cbfb43df4ce210727d953e4a713307fa19bb7d9f85041438d9e11b942a3774") token (crypto/paseto/v4/public/sign seed (encoding/encode "utf8" "Arrakis") {footer #b64 "AQ==" implicit #b64 "Ag=="})] (crypto/paseto/v4/public/verify (crypto/paseto/v4/public/public-key seed) token {expected-footer #b64 "AQ==" implicit #b64 "Ag=="}))
(let [seed (encoding/decode "hex" "b4cbfb43df4ce210727d953e4a713307fa19bb7d9f85041438d9e11b942a3774") token (crypto/paseto/v4/public/sign seed (encoding/encode "utf8" "Arrakis") {footer #b64 "AQ==" implicit #b64 "Ag=="})] (crypto/paseto/v4/public/verify (crypto/paseto/v4/public/public-key seed) token {expected-footer #b64 "AQ==" implicit #b64 "Ag=="}))
{<verified> footer #b64 "AQ==" message #b64 "QXJyYWtpcw=="}
parse does not authenticate anything. Its footer can help choose a public
key, but neither the footer nor the message is trusted until verify succeeds.
14.3.1. Claims
| Signature | Result |
|---|---|
(crypto/paseto/v4/public/sign-claims seed claims opts) |
Signed JSON object token |
(crypto/paseto/v4/public/verify-claims key token opts) |
{<verified> claims map footer bytes} |
Both operations require now as a #utc in opts; they never read the
host clock. Signing accepts footer and implicit, adds iat from now when
absent, and never invents an expiration. UTC values in exp, nbf and
iat become RFC3339 strings; the inserted iat uses whole seconds.
Verification checks claims only after signature verification. It accepts
implicit, expected-footer, max-length and these claim options:
| Option | Check |
|---|---|
issuer, subject, audience |
Nonempty string must match iss, sub or aud |
leeway |
Nonnegative #dur tolerance; defaults to zero |
<require-expiration> |
Require exp |
<require-not-before> |
Require nbf |
<require-issued-at> |
Require iat |
Present exp, nbf and iat are always validated, even without a requirement
flag. Expiration is exclusive: at exp the token is expired. nbf and iat
may equal now. Leeway relaxes these comparisons. Registered textual claims
iss, sub, aud and jti must be strings; timestamps must be complete RFC3339
strings with at most nine fractional digits. Duplicate JSON keys, including
nested keys, are rejected. Claim clocks and tolerance must fit signed 64-bit
nanoseconds (approximately years 1677–2262). Returned claims retain JSON
timestamp strings and user fields.
Claims use literal JSON, not DUST's tagged JSON transport. Keys such as
#role, ##role and $comment remain ordinary keys. Native values in
user claims become plain JSON objects: #link 42 signs as
{"#link":42} and verification returns the map {#link 42}, not a link.
Registered timestamp conversion remains as described above.
(let [seed (encoding/decode "hex" "b4cbfb43df4ce210727d953e4a713307fa19bb7d9f85041438d9e11b942a3774") token (crypto/paseto/v4/public/sign-claims seed {exp #utc "2026-01-02T00:00:00Z" sub "Paul Atreides"} {now #utc "2026-01-01T00:00:00Z"}) result (crypto/paseto/v4/public/verify-claims (crypto/paseto/v4/public/public-key seed) token {<require-expiration require-issued-at> now #utc "2026-01-01T00:00:00Z" subject "Paul Atreides"})] [(get result "verified") (get (get result "claims") "sub")])
(let [seed (encoding/decode "hex" "b4cbfb43df4ce210727d953e4a713307fa19bb7d9f85041438d9e11b942a3774") token (crypto/paseto/v4/public/sign-claims seed {exp #utc "2026-01-02T00:00:00Z" sub "Paul Atreides"} {now #utc "2026-01-01T00:00:00Z"}) result (crypto/paseto/v4/public/verify-claims (crypto/paseto/v4/public/public-key seed) token {<require-expiration require-issued-at> now #utc "2026-01-01T00:00:00Z" subject "Paul Atreides"})] [(get result "verified") (get (get result "claims") "sub")])
true "Paul Atreides"
15 Random Functions
The random/ library makes reproducible random values from a seed. Seeded
generators read no host entropy: random/seeded always takes an explicit seed,
and the same seed gives the same values on every host and in every later version.
15.1. Generators
A generator is mutable. Each call that takes a
generator advances it in place, as regexes/find advances a matcher. Two calls
on the same generator give the next two values of one sequence:
(let [g (random/seeded 42)]
[(random/int g 0 6) (random/int g 0 6)])
; [0 2] on every run
The algorithm is xoshiro256**, seeded through SplitMix64: the generator's four 64-bit state words are the first four SplitMix64 outputs for the seed. This choice is fixed.
A generator in a result is written as its algorithm and its current state, 64 lowercase hexadecimal digits for the four state words in order, each most significant digit first:
#rng {xoshiro256ss "9d1c68b67d1ceb4323acb714c3a78d019d431c524cad8dc572e82a070b0b9ddb"}
The state written is the one the generator has when the result is exported,
after the whole evaluation, not when the generator is placed in the result. So
[g (random/int g 0 6)] shows in its first slot the state after the
random/int call.
A #rng value read back from a document, or bound from the host, becomes a
new generator that continues the same sequence. It changes into a generator in
place when a random function first uses it, so every reference to it shares
one state. A payload that is not one xoshiro256ss member with 64 lowercase
hexadecimal digits, or whose state is all zero, produces #err <invalid tag>
when a random function uses it. Two generators are equal when their states are
equal.
(let [g (random/seeded 42)] [(random/int g 0 6) (random/int g 0 6) g])
(let [g (random/seeded 42)] [(random/int g 0 6) (random/int g 0 6) g])
0 2 #rng {xoshiro256ss "9d1c68b67d1ceb4323acb714c3a78d019d431c524cad8dc572e82a070b0b9ddb"}
(let [g #rng {xoshiro256ss "9d1c68b67d1ceb4323acb714c3a78d019d431c524cad8dc572e82a070b0b9ddb"}] [(random/int g 0 6) (random/int g 0 6) (random/int g 0 6) g])
(let [g #rng {xoshiro256ss "9d1c68b67d1ceb4323acb714c3a78d019d431c524cad8dc572e82a070b0b9ddb"}] [(random/int g 0 6) (random/int g 0 6) (random/int g 0 6) g])
4 5 5 #rng {xoshiro256ss "7e3fedbea92a13a5c9a25ba0f11c828cc38346747039f414cf55c271f2386fa5"}
(random/int #rng {xoshiro256ss "00"} 0 6) (random/int #rng {xoshiro256ss "0000000000000000000000000000000000000000000000000000000000000000"} 0 6) (random/int #rng {xoshiro256ss "6DB07C7DD404690B81DDC5FE6C15769825CFE223490D9D1F9252543D113B0C36"} 0 6) (random/int #rng {pcg32 "6db07c7dd404690b81ddc5fe6c15769825cfe223490d9d1f9252543d113b0c36"} 0 6) (random/int #rng 42 0 6) (random/int #rng {xoshiro256ss "bdd732262feb6e9528efe333b266f10347526757130f9f52581ce1ff0e4ae394" extra true} 0 6)
(random/int #rng {xoshiro256ss "00"} 0 6) (random/int #rng {xoshiro256ss "0000000000000000000000000000000000000000000000000000000000000000"} 0 6) (random/int #rng {xoshiro256ss "6DB07C7DD404690B81DDC5FE6C15769825CFE223490D9D1F9252543D113B0C36"} 0 6) (random/int #rng {pcg32 "6db07c7dd404690b81ddc5fe6c15769825cfe223490d9d1f9252543d113b0c36"} 0 6) (random/int #rng 42 0 6) (random/int #rng {<extra> xoshiro256ss "bdd732262feb6e9528efe333b266f10347526757130f9f52581ce1ff0e4ae394"} 0 6)
#err {<invalid tag> message "#rng requires a xoshiro256ss state of 64 hex digits, not all zero"} #err {<invalid tag> message "#rng requires a xoshiro256ss state of 64 hex digits, not all zero"} #err {<invalid tag> message "#rng requires a xoshiro256ss state of 64 hex digits, not all zero"} #err {<invalid tag> message "#rng requires a xoshiro256ss state of 64 hex digits, not all zero"} #err {<invalid tag> message "#rng requires a xoshiro256ss state of 64 hex digits, not all zero"} #err {<invalid tag> message "#rng requires a xoshiro256ss state of 64 hex digits, not all zero"}
Ranges are half-open: lo is included and hi is not. An empty range, where
lo > hi=, produces #err <invalid value>. A bound of the wrong type, or a
value that is not a generator, produces #err <mismatch type>.
15.2. random/seeded
Function(random/seeded seed) → generator
Returns a new generator for the integer seed. Every integer is a seed,
negative ones included.
| Call | Result |
|---|---|
(random/seeded 42) |
#rng {xoshiro256ss bdd732262feb6e9528efe333b266f10347526757130f9f52581ce1ff0e4ae394} |
(random/seeded 0) |
#rng {xoshiro256ss e220a8397b1dcdaf6e789e6aa1b965f406c45d188009454ff88bb8a8724c81ec} |
(random/seeded 1.5) |
#err <mismatch type> |
(random/seeded 42) (random/seeded 0) (random/seeded -1) (random/seeded -9223372036854775808)
#rng {xoshiro256ss "bdd732262feb6e9528efe333b266f10347526757130f9f52581ce1ff0e4ae394"} #rng {xoshiro256ss "e220a8397b1dcdaf6e789e6aa1b965f406c45d188009454ff88bb8a8724c81ec"} #rng {xoshiro256ss "e4d971771b652c20e99ff867dbf682c9382ff84cb27281e96d1db36ccba982d2"} #rng {xoshiro256ss "481ec0a212a9f3dbc46fa638a630901261a685ffc80a8140592e268383e356f9"}
(let [a (random/seeded 7) b (random/seeded 7)] [(random/int a 0 100) (random/int b 0 100) (random/int a 0 100) (random/int b 0 100)])
(let [a (random/seeded 7) b (random/seeded 7)] [(random/int a 0 100) (random/int b 0 100) (random/int a 0 100) (random/int b 0 100)])
70 70 27 27
(random/seeded 1.5) (random/seeded "abc") (random/seeded) (random/int 42 0 6) (random/int #other {xoshiro256ss "6db07c7dd404690b81ddc5fe6c15769825cfe223490d9d1f9252543d113b0c36"} 0 6)
(random/seeded 1.5) (random/seeded "abc") (random/seeded) (random/int 42 0 6) (random/int #other {xoshiro256ss "6db07c7dd404690b81ddc5fe6c15769825cfe223490d9d1f9252543d113b0c36"} 0 6)
#err {<mismatch type> message "random/seeded requires an integer seed"} #err {<mismatch type> message "random/seeded requires an integer seed"} #err {<arity mismatch> message "wrong number of arguments"} #err {<mismatch type> message "expected a random generator"} #err {<mismatch type> message "expected a random generator"}
15.3. random/int
Function(random/int generator lo hi) → integer
Returns an integer x with lo < x < hi=, uniform over the range. The range
can span all 64-bit integers. Integers use Lemire's multiply-and-reject method,
so no value is more likely than another.
Call, on (random/seeded 42) |
Result |
|---|---|
(random/int g 0 6) |
0 |
(random/int g -10 -5) |
-10 |
(random/int g -9223372036854775808 9223372036854775807) |
-7676373272452217067 |
(random/int g 5 5) |
#err <invalid value> |
(let [g (random/seeded 42)] [(random/int g 0 6) (random/int g 0 6) (random/int g 0 6) (random/int g 0 6) (random/int g 0 6) (random/int g 0 6) (random/int g 0 6) (random/int g 0 6) (random/int g 0 6) (random/int g 0 6)]) (let [g (random/seeded 42)] [(random/int g -10 -5) (random/int g 5 6) (random/int g -1000000000000000000 1000000000000000000)]) (let [g (random/seeded 7)] [(random/int g 0 3) (random/int g 0 3) (random/int g 0 3) (random/int g 0 3) (random/int g 0 3)])
(let [g (random/seeded 42)] [(random/int g 0 6) (random/int g 0 6) (random/int g 0 6) (random/int g 0 6) (random/int g 0 6) (random/int g 0 6) (random/int g 0 6) (random/int g 0 6) (random/int g 0 6) (random/int g 0 6)]) (let [g (random/seeded 42)] [(random/int g -10 -5) (random/int g 5 6) (random/int g -1000000000000000000 1000000000000000000)]) (let [g (random/seeded 7)] [(random/int g 0 3) (random/int g 0 3) (random/int g 0 3) (random/int g 0 3) (random/int g 0 3)])
[[0 2 4 5 5 4 4 5 4 3] [-10 5 360086822056278777] [2 0 2 2 2]]
(let [g (random/seeded 42)] [(random/int g -9223372036854775808 9223372036854775807) (random/int g -9223372036854775808 9223372036854775807) (random/int g -9223372036854775808 9223372036854775807)]) (let [g (random/seeded 42)] [(random/int g -1000000000000000000 1000000000000000000) (random/int g -1000000000000000000 1000000000000000000) (random/int g -1000000000000000000 1000000000000000000)])
(let [g (random/seeded 42)] [(random/int g -9223372036854775808 9223372036854775807) (random/int g -9223372036854775808 9223372036854775807) (random/int g -9223372036854775808 9223372036854775807)]) (let [g (random/seeded 42)] [(random/int g -1000000000000000000 1000000000000000000) (random/int g -1000000000000000000 1000000000000000000) (random/int g -1000000000000000000 1000000000000000000)])
[[-7676373272452217067 -2232420343890232707 3321214725393783200] [-832274057880235478 -242039498674662721 360086822056278777]]
(let [g #rng {xoshiro256ss "0000000000000001000000000000000000000000000000010000000000000001"}] [(random/int g 0 6) g]) (let [g #rng {xoshiro256ss "0000000000000001000000000000000000000000000000010000000000000001"} warm (random/seeded 7)] (for [i (lists/range 48)] (random/int warm 0 2)) [(random/int g 0 6) g])
(let [g #rng {xoshiro256ss "0000000000000001000000000000000000000000000000010000000000000001"}] [(random/int g 0 6) g]) (let [g #rng {xoshiro256ss "0000000000000001000000000000000000000000000000010000000000000001"} warm (random/seeded 7)] (for [i (lists/range 48)] (random/int warm 0 2)) [(random/int g 0 6) g])
[[0 #rng {xoshiro256ss "0000000004000080000020000400000040000000040000000010000004000000"}] [0 #rng {xoshiro256ss "0000000004000080000020000400000040000000040000000010000004000000"}]]
(random/int (random/seeded 1) 5 5) (random/int (random/seeded 1) 6 0) (random/int (random/seeded 1) 9223372036854775807 -9223372036854775808)
#err {<invalid value> message "random range is empty: lo must be below hi"} #err {<invalid value> message "random range is empty: lo must be below hi"} #err {<invalid value> message "random range is empty: lo must be below hi"}
(random/int (random/seeded 1) 0.0 6.0) (random/int (random/seeded 1) 0 6.5) (random/int (random/seeded 1) "a" "z") (random/int (random/seeded 1) 6)
#err {<mismatch type> message "random/int requires integer bounds"} #err {<mismatch type> message "random/int requires integer bounds"} #err {<mismatch type> message "random/int requires integer bounds"} #err {<arity mismatch> message "wrong number of arguments"}
15.4. random/float
Function(random/float generator lo hi) → float
Returns a float x with lo < x < hi=. Both bounds are floats. The function
takes the top 53 bits of the next output as u in [0, 1), and maps it to lo +
u * (hi - lo). When hi - lo is too large for a float, it uses lo * (1 - u) +
hi * u. A result that rounds up to hi is drawn again.
Call, on (random/seeded 42) |
Result |
|---|---|
(random/float g 0.0 1.0) |
0.08386297105988216 |
(random/float g -2.5 2.5) |
-2.080685144700589 |
(random/float g 0 1) |
#err <mismatch type> |
(let [g (random/seeded 42)] [(random/float g 0.0 1.0) (random/float g 0.0 1.0) (random/float g 0.0 1.0)]) (let [g (random/seeded 42)] [(random/float g -2.5 2.5) (random/float g 100.0 100.5) (random/float g -1.0e308 1.0e308)]) (let [g (random/seeded 7)] [(random/float g 0.0 1.0e-300) (random/float g -1.0 0.0)])
(let [g (random/seeded 42)] [(random/float g 0.0 1.0) (random/float g 0.0 1.0) (random/float g 0.0 1.0)]) (let [g (random/seeded 42)] [(random/float g -2.5 2.5) (random/float g 100.0 100.5) (random/float g -1e+308 1e+308)]) (let [g (random/seeded 7)] [(random/float g 0.0 1e-300) (random/float g -1.0 0.0)])
[[0.08386297105988216 0.3789802506626686 0.6800434110281394] [-2.080685144700589 100.18949012533133 3.600868220562787e+307] [7.0057648217968965e-301 -0.7212487705262157]]
(random/float (random/seeded 1) 1.0 1.0) (random/float (random/seeded 1) 2.0 1.0)
#err {<invalid value> message "random range is empty: lo must be below hi"} #err {<invalid value> message "random range is empty: lo must be below hi"}
(random/float (random/seeded 1) 0 1) (random/float (random/seeded 1) 0.0 1) (random/float (random/seeded 1) "a" "b")
#err {<mismatch type> message "random/float requires float bounds"} #err {<mismatch type> message "random/float requires float bounds"} #err {<mismatch type> message "random/float requires float bounds"}
15.5. random/choose
Function(random/choose generator list) → value
Returns one item of list, each with the same chance. An empty list or
null produces #err <invalid value>.
Call, on (random/seeded 42) |
Result |
|---|---|
(random/choose g ["a" "b" "c"]) |
"a" |
(random/choose g ["only"]) |
"only" |
(random/choose g []) |
#err <invalid value> |
(let [g (random/seeded 42)] [(random/choose g ["a" "b" "c"]) (random/choose g ["a" "b" "c"]) (random/choose g ["a" "b" "c"]) (random/choose g ["a" "b" "c"])]) (let [g (random/seeded 42)] [(random/choose g ["only"]) (random/choose g [1 2.5 "three" {four 4}])]) (let [g (random/seeded 7)] (random/choose g [[1 2] [3 4]]))
(let [g (random/seeded 42)] [(random/choose g ["a" "b" "c"]) (random/choose g ["a" "b" "c"]) (random/choose g ["a" "b" "c"]) (random/choose g ["a" "b" "c"])]) (let [g (random/seeded 42)] [(random/choose g ["only"]) (random/choose g [1 2.5 "three" {four 4}])]) (let [g (random/seeded 7)] (random/choose g [[1 2] [3 4]]))
[["a" "b" "c" "c"] ["only" 2.5] [3 4]]
(random/choose (random/seeded 1) []) (random/choose (random/seeded 1) null)
#err {<invalid value> message "random/choose requires a nonempty list"} #err {<invalid value> message "random/choose requires a nonempty list"}
(random/choose (random/seeded 1) {a 1}) (random/choose (random/seeded 1) "abc") (random/choose ["a" "b"])
#err {<mismatch type> message "expected a list or null"} #err {<mismatch type> message "expected a list or null"} #err {<arity mismatch> message "wrong number of arguments"}
15.6. random/shuffle
Function(random/shuffle generator list) → list
Returns a new list with the items of list in a uniform random order, and
leaves list unchanged. The order comes from a Fisher–Yates shuffle that
swaps each position i, from the last down to the second, with a position
from 0 to i. null shuffles to [].
Call, on (random/seeded 7) |
Result |
|---|---|
(random/shuffle g [1 2 3 4 5]) |
[1 5 3 2 4] |
(random/shuffle g []) |
[] |
(random/shuffle g {a 1}) |
#err <mismatch type> |
(let [g (random/seeded 7)] [(random/shuffle g [1 2 3 4 5]) (random/shuffle g [1 2 3 4 5]) (random/shuffle g ["a" "b" "c" "d" "e" "f" "g" "h"])]) (let [g (random/seeded 7) xs [1 2 3]] [(random/shuffle g xs) xs]) (let [g (random/seeded 7)] [(random/shuffle g []) (random/shuffle g ["only"]) (random/shuffle g null)])
(let [g (random/seeded 7)] [(random/shuffle g [1 2 3 4 5]) (random/shuffle g [1 2 3 4 5]) (random/shuffle g ["a" "b" "c" "d" "e" "f" "g" "h"])]) (let [g (random/seeded 7) xs [1 2 3]] [(random/shuffle g xs) xs]) (let [g (random/seeded 7)] [(random/shuffle g []) (random/shuffle g ["only"]) (random/shuffle g null)])
[[[1 5 3 2 4] [2 3 1 4 5] ["g" "a" "c" "e" "f" "h" "b" "d"]] [[2 1 3] [1 2 3]] [[] ["only"] []]]
(random/shuffle (random/seeded 1) {a 1}) (random/shuffle (random/seeded 1) "abc") (random/shuffle [1 2 3])
#err {<mismatch type> message "expected a list or null"} #err {<mismatch type> message "expected a list or null"} #err {<arity mismatch> message "wrong number of arguments"}
15.7. random/bytes
Function(random/bytes generator count) → bytes
Returns Bytes of count uniform random bytes. Each generator output
gives eight bytes, least significant byte first. The bytes that the last
output has left over are discarded, so two calls for four bytes each do not
return the same bytes as one call for eight. count must be a nonnegative
integer; a count of zero returns #b64 "" and leaves the generator
unchanged.
Call, on (random/seeded 7) |
Result |
|---|---|
(random/bytes g 4) |
#b64 "Wnb5Tg="= |
(random/bytes g 0) |
#b64 "" |
(random/bytes g -1) |
#err <invalid value> |
(let [g (random/seeded 7)] (random/bytes g 13)) (let [g (random/seeded 7)] [(random/bytes g 4) (random/bytes g 0) (random/bytes g 9) g]) (let [g (random/seeded 7)] (count (random/bytes g 100000))) (let [g (random/seeded 7)] (= (random/bytes g 8) (random/bytes (random/seeded 7) 8))) (let [g (random/seeded 7)] (encoding/encode "hex" (random/bytes g 8))) (let [g (random/seeded 7)] (random/bytes g -1))
#b64 "Wnb5Tvf6WLPSLEhPlg==" [#b64 "Wnb5Tg==" #b64 "" #b64 "0ixIT5Y9XEeW" #rng {xoshiro256ss "c373822e58bc6c1c8021eb139356b060caa6ed97295a947cf3b6bf257b7e0bf8"}] 100000 true "5a76f94ef7fa58b3" #err {<invalid value> message "random/bytes count must be nonnegative"}
(random/bytes (random/seeded 7) 1.5) (random/bytes (random/seeded 7) null) (random/bytes (random/seeded 7) "4") (random/bytes [1] 4) (random/bytes 7 4) (random/bytes (random/seeded 1))
#err {<mismatch type> message "random/bytes requires an integer count"} #err {<mismatch type> message "random/bytes requires an integer count"} #err {<mismatch type> message "random/bytes requires an integer count"} #err {<mismatch type> message "expected a random generator"} #err {<mismatch type> message "expected a random generator"} #err {<arity mismatch> message "wrong number of arguments"}
16 String Functions
The String library provides strings/ functions for Unicode text. Character counts
and indices count Unicode code points, starting at zero. Substring end indices
are excluded. A combining mark counts separately from the character before it.
Operations do not normalize text unless their documentation says so. Searches
match literal text rather than patterns or regular expressions.
Case conversion and word boundaries recognize Unicode letters and digits. Case conversion is locale independent. Character classification and full case mappings use Unicode 17.0.0, including expanding mappings and the contextual Greek final sigma rule.
16.1. String functions
16.1.1. strings/case
Function(strings/case case value) → string
(strings/case cases value) → string
Converts value with one case selector or a list of selectors. A list applies
the conversions from left to right. An empty list returns the input unchanged.
The selector and input must be strings. Unknown selectors produce an error.
| Selector | Conversion |
|---|---|
upper |
Unicode uppercase |
lower |
Unicode lowercase |
camel |
Words joined in camel case |
pascal |
Words joined in Pascal case |
snake |
Lowercase words joined with underscores |
kebab |
Lowercase words joined with hyphens |
title |
Capitalized words joined with spaces |
screaming-snake |
Uppercase words joined with underscores |
case-fold |
Unicode default full case folding |
Case conversion can change the number of code points: straße becomes
STRASSE with upper. Case folding is for caseless matching. It does not
normalize text or use Turkic-specific mappings.
Naming conversions split words at separators and case transitions. An acronym
followed by a capitalized word is split: HTTPServer contains HTTP and
Server. (strings/case [snake upper] HTTPServer) returns HTTP_SERVER.
(strings/case "upper" "straße") (strings/case "lower" "HELLO") (strings/case "camel" "HTTP_server") (strings/case "title" "hELLO_world") (strings/case "case-fold" "Straße")
"STRASSE" "hello" "httpServer" "Hello World" "strasse"
(strings/case ["snake" "upper"] "HTTPServer") (strings/case ["upper" "lower"] "Straße") (strings/case [] "Hello") (strings/case ["camel" "snake"] "hello_world")
"HTTP_SERVER" "strasse" "Hello" "hello_world"
16.1.2. strings/trim
Function(strings/trim s opts) → string
(strings/trim s text opts) → string
Returns s with whitespace or text removed from the ends selected by opts.
opts is a map tagged with exactly one of left, right, or both, optionally with repeat, as in {<both repeat>}.
Whitespace trimming removes full Unicode whitespace runs.
Text trimming removes one exact match per end, or repeats with repeat.
Both ends are processed left first.
Empty text leaves s unchanged.
(strings/trim "\t \nalpha beta\r " <both>) (strings/trim " hi " <both>) (strings/trim " hi " <both>) (strings/trim "" <both>) (strings/trim "\t\n" <both>) (strings/trim "hi" <both>) (strings/trim "hi " <both>)
"alpha beta" "hi" "hi" "" "" "hi" "hi"
(strings/trim "hahaha" "ha" <left>) (strings/trim "hahaha" "ha" <both>) (strings/trim "hahaha" "ha" <both repeat>) (strings/trim "ababa" "aba" <both>) (strings/trim "ababa" "aba" <both repeat>) (strings/trim "hahaxhaha" "ha" <left repeat>) (strings/trim "hahaxhaha" "ha" <repeat right>) (strings/trim "hahaxhahaxhaha" "ha" <both repeat>) (strings/trim "aabb" "ab" <left repeat>) (strings/trim "abc" "abc" <both>) (strings/trim "ab" "abc" <both repeat>) (strings/trim "abc" "" <both repeat>) (strings/trim "" "" <both repeat>) (strings/trim "" "a" <both repeat>) (strings/trim "🙂🙂x🙂🙂" "🙂" <both repeat>) (strings/trim "Éxé" "é" <both repeat>) (strings/trim "éxé" "é" <both repeat>) (strings/trim " x " " " <both>) (strings/trim " x " " " <both repeat>)
"haha" "ha" "" "ba" "ba" "xhaha" "hahax" "xhahax" "aabb" "" "ab" "abc" "" "" "x" "Éx" "éxé" " x " "x"
{both-left (strings/trim "abc" <both left>) both-right (strings/trim "abc" <both right>) conflicting-sides (strings/trim "abc" <left right>) extra (strings/trim "abc" "a" "extra" <both>) missing (strings/trim) missing-side (strings/trim "abc" {}) old-arity (strings/trim "abc") opts-list (strings/trim "abc" ["both"]) opts-null (strings/trim "abc" null) opts-string (strings/trim "abc" "both") repeat-only (strings/trim "abc" <repeat>) source-null (strings/trim null <both>) source-number (strings/trim 1 <left>) text-null (strings/trim "abc" null <left>) text-number (strings/trim "abc" 1 <right>) text-options (strings/trim "abc" "a" <all both>) text-opts-null (strings/trim "abc" "a" null) text-source-null (strings/trim null "a" <right>) text-source-number (strings/trim 1 "a" <both repeat>) unknown-option (strings/trim "abc" <all both>)}
#cases [{output #err <invalid value> select "missing-side"} {output #err <invalid value> select "repeat-only"} {output #err <invalid value> select "conflicting-sides"} {output #err <invalid value> select "both-left"} {output #err <invalid value> select "both-right"} {output #err <invalid value> select "unknown-option"} {output #err <invalid value> select "text-options"} {output #err <mismatch type> select "opts-string"} {output #err <mismatch type> select "opts-list"} {output #err <mismatch type> select "opts-null"} {output #err <mismatch type> select "text-opts-null"} {output #err <mismatch type> select "source-null"} {output #err <mismatch type> select "source-number"} {output #err <mismatch type> select "text-source-null"} {output #err <mismatch type> select "text-source-number"} {output #err <mismatch type> select "text-null"} {output #err <mismatch type> select "text-number"} {output #err <arity mismatch> select "missing"} {output #err <arity mismatch> select "old-arity"} {output #err <arity mismatch> select "extra"}]
16.1.3. strings/trim-prefix
Function(strings/trim-prefix s prefix) → string
Returns s without prefix when s starts with it, otherwise s. It removes
one match. An empty prefix leaves s unchanged.
16.1.4. strings/trim-suffix
Function(strings/trim-suffix s suffix) → string
Returns s without suffix when s ends with it, otherwise s. It removes
one match. An empty suffix leaves s unchanged.
16.1.5. strings/split
Function(strings/split string separator) → list
(strings/split string separator limit) → list
Splits at each literal occurrence of separator, preserving empty fields.
An empty separator splits into Unicode code points; splitting an empty string
with an empty separator returns a list containing the empty string.
An optional positive limit permits at most that many parts and keeps the
unsplit remainder in the final part. A zero limit removes trailing empty
parts. A negative limit preserves all parts, including trailing empty strings.
Omitting limit preserves trailing empty parts.
(strings/split "a,b,c" ",") (strings/split "é猫🙂" "") (strings/split "a.b." ".") (strings/split "" ",") (strings/split "" "")
[["a" "b" "c"] ["é" "猫" "🙂"] ["a" "b" ""] [""] []]
16.1.6. strings/join
Function(strings/join strings separator) → string
Joins a list of strings with separator between consecutive elements.
An empty list produces the empty string. Elements and the separator must be strings.
(strings/join ["a" "b"] ",") (strings/join ["é" "猫" "🙂"] "") (strings/join [] "猫")
"a,b" "é猫🙂" ""
16.1.7. strings/replace
Function(strings/replace string search replacement) → string
Replaces non-overlapping literal occurrences of search, from left to right.
An empty search inserts replacement before, between, and after the input's
Unicode code points: (strings/replace ab "" x) returns xaxbx.
(strings/replace "banana" "na" "x") (strings/replace "ab" "" "x") (strings/replace "é猫" "" "🙂") (strings/replace "a.b." "." "猫")
"baxx" "xaxbx" "🙂é🙂猫🙂" "a猫b猫"
16.1.8. strings/substring
Function(strings/substring string start) → string
(strings/substring string start end) → string
Returns the code points from start up to, but excluding, end.
Without end, returns the rest of the string. Both indices must be integers
between zero and the string length, and start must not exceed end. Other
indices produce #err <bounds index>.
(strings/substring "Aé猫Z" 1 3) (strings/substring "é猫🙂" 1 3) (strings/substring "é猫" 2 2) (strings/substring "é猫🙂" 1)
"é猫" "猫🙂" "" "猫🙂"
16.1.9. strings/starts-with?
Function(strings/starts-with? string prefix) → boolean
Returns whether the string begins with the literal prefix.
Every string starts with the empty string.
(strings/starts-with? "abc" "a") (strings/starts-with? "é猫" "é") (strings/starts-with? "é猫" "猫") (strings/starts-with? "é猫" "")
true true false true
16.1.10. strings/ends-with?
Function(strings/ends-with? string suffix) → boolean
Returns whether the string ends with the literal suffix.
Every string ends with the empty string.
(strings/ends-with? "abc" "c") (strings/ends-with? "é猫" "猫") (strings/ends-with? "é猫" "é") (strings/ends-with? "é猫" "")
true true false true
16.1.11. strings/includes?
Function(strings/includes? string search) → boolean
Returns whether the string contains the literal search.
Every string includes the empty string.
(strings/includes? "a.b" ".") (strings/includes? "é猫🙂" "猫") (strings/includes? "é猫" "z") (strings/includes? "é猫" "") (strings/includes? "é" "é")
true true false true false
16.1.12. strings/words
Function(strings/words text) → list
Splits text at runs of Unicode WhiteSpace, omitting empty fields. Leading and
trailing whitespace need no separate trim. Empty or whitespace-only text
returns []. Punctuation remains part of each word.
{case0 (strings/words " Paul\tAtreides\n Arrakis ") case1 (strings/words "\u0085Paul\u00a0Atreides\u1680Duncan\u2003Idaho\u2028Chani\u2029Stilgar\u202fGurney\u205fHalleck\u3000") case2 (strings/words "") case3 (strings/words " \t\r\n") case4 (strings/words "éclair界😀\u200bword") case5 (let [name "Paul"] (strings/words ~"hello ,name")) case6 (strings/words 42) case7 (strings/words "one" "two")}
{case0 (strings/words " Paul\tAtreides\n Arrakis ") case1 (strings/words " Paul Atreides Duncan Idaho Chani Stilgar Gurney Halleck ") case2 (strings/words "") case3 (strings/words " \t\r\n") case4 (strings/words "éclair界😀word") case5 (let [name "Paul"] (strings/words ~"hello ,name")) case6 (strings/words 42) case7 (strings/words "one" "two")}
#cases [{output ["Paul" "Atreides" "Arrakis"] select "case0"} {output ["Paul" "Atreides" "Duncan" "Idaho" "Chani" "Stilgar" "Gurney" "Halleck"] select "case1"} {output [] select "case2"} {output [] select "case3"} {output ["éclair界😀word"] select "case4"} {output ["hello" "Paul"] select "case5"} {output #err <mismatch type> select "case6"} {output #err <arity mismatch> select "case7"}]
16.1.13. strings/split-lines
Function(strings/split-lines s) → list
Returns the lines of s separated by LF or CRLF, without their line endings.
Trailing empty lines are omitted. A lone CR is ordinary content. An empty string produces a list containing one empty string. A nonempty string containing only line endings produces an empty list.
[(strings/split-lines "a\nb\r\nc\n") (strings/split-lines "") (strings/split-lines "\n\r\n") (strings/split-lines "a\rb") (strings/split-lines "a\n\nb") (strings/split-lines "a b")]
(strings/split-lines """ a b\r c """ ) (strings/split-lines "") (strings/split-lines """ \r """ ) (strings/split-lines "a\rb") (strings/split-lines """ a b """ ) (strings/split-lines "a b")
[["a" "b" "c"] [""] [] [ "a\rb"] ["a" "" "b"] ["a b"]]
16.1.14. strings/index-of
Function(strings/index-of s value) → integer or null
(strings/index-of s value start) → integer or null
Returns the first index of the string value in s at or after start, or null if not found.
The integer start defaults to zero.
Negative starts are treated as zero.
A start beyond the string length finds no nonempty value.
An empty value matches at the start clamped to the range from zero through the string length.
Indices retain their full integer range.
[(strings/index-of "banana" "ana") (strings/index-of "banana" "ana" 2) (strings/index-of "banana" "ana" -3) (strings/index-of "banana" "ana" 9) (strings/index-of "🙂a🙂b" "b") (strings/index-of "é" "é") (strings/index-of "ABC" "a") (strings/index-of "abc" "" 99) (strings/index-of "abc" "" -9) (strings/index-of "" "") (strings/index-of "abc" "b" 9223372036854775807) (strings/index-of "abc" "" 9223372036854775807)]
(strings/index-of "banana" "ana") (strings/index-of "banana" "ana" 2) (strings/index-of "banana" "ana" -3) (strings/index-of "banana" "ana" 9) (strings/index-of "🙂a🙂b" "b") (strings/index-of "é" "é") (strings/index-of "ABC" "a") (strings/index-of "abc" "" 99) (strings/index-of "abc" "" -9) (strings/index-of "" "") (strings/index-of "abc" "b" 9223372036854775807) (strings/index-of "abc" "" 9223372036854775807)
1 3 1 null 3 null null 3 0 0 null 3
16.1.15. strings/last-index-of
Function(strings/last-index-of s value) → integer or null
(strings/last-index-of s value start) → integer or null
Returns the last index of the string value in s at or before start, or null if not found.
The integer start defaults to the string length.
Starts beyond the string length are treated as the string length.
A negative start returns null, including when value is empty.
An empty value matches at any index from zero through the string length.
The start limits the beginning of a match, not its end.
Indices are not narrowed to a host's smaller integer type.
[(strings/last-index-of "banana" "ana") (strings/last-index-of "banana" "ana" 2) (strings/last-index-of "banana" "ana" -1) (strings/last-index-of "banana" "ana" 9223372036854775807) (strings/last-index-of "abc" "abc" 1) (strings/last-index-of "abc" "") (strings/last-index-of "abc" "" -1) (strings/last-index-of "abc" "" 99) (strings/last-index-of "🙂a🙂b" "🙂") (strings/last-index-of "é" "é") (strings/last-index-of "" "")]
(strings/last-index-of "banana" "ana") (strings/last-index-of "banana" "ana" 2) (strings/last-index-of "banana" "ana" -1) (strings/last-index-of "banana" "ana" 9223372036854775807) (strings/last-index-of "abc" "abc" 1) (strings/last-index-of "abc" "") (strings/last-index-of "abc" "" -1) (strings/last-index-of "abc" "" 99) (strings/last-index-of "🙂a🙂b" "🙂") (strings/last-index-of "é" "é") (strings/last-index-of "" "")
3 1 null 3 0 3 null 3 2 null 0
16.1.16. strings/replace-first
Function(strings/replace-first s match replacement) → string
Returns s with the first occurrence of match replaced by replacement.
Both match and replacement are literal strings.
An empty match inserts replacement at the start.
Returns s unchanged when there is no match.
[(strings/replace-first "abab" "ab" "X") (strings/replace-first "aaa" "aa" "X") (strings/replace-first "a.b.a" "." "$1") (strings/replace-first "ab" "" "-") (strings/replace-first "🙂x" "" "-") (strings/replace-first "" "" "+") (strings/replace-first "abc" "x" "q") (strings/replace-first "a" "a" "aa") (strings/replace-first "$1" "$1" "\\")]
(strings/replace-first "abab" "ab" "X") (strings/replace-first "aaa" "aa" "X") (strings/replace-first "a.b.a" "." "$1") (strings/replace-first "ab" "" "-") (strings/replace-first "🙂x" "" "-") (strings/replace-first "" "" "+") (strings/replace-first "abc" "x" "q") (strings/replace-first "a" "a" "aa") (strings/replace-first "$1" "$1" "\\")
"Xab" "Xa" "a$1b.a" "-ab" "-🙂x" "+" "abc" "aa" "\\"
16.1.17. strings/blank?
Function(strings/blank? s) → boolean
Returns true if s is null, empty, or contains only whitespace, otherwise false.
Other non-string values produce #err <mismatch type>.
[(strings/blank? null) (strings/blank? "") (strings/blank? " \t\r\n") (strings/blank? " ") (strings/blank? " ") (strings/blank? " ") (strings/blank? " ") (strings/blank? "") (strings/blank? " a ")]
(strings/blank? null) (strings/blank? "") (strings/blank? " \t\r\n") (strings/blank? " ") (strings/blank? " ") (strings/blank? " ") (strings/blank? " ") (strings/blank? "") (strings/blank? " a ")
true true true true true true true false false
16.1.18. String templates
A template retains literal strings and evaluated values. It is accepted as a
string by string operations; template? distinguishes it from an
ordinary string. Rendering joins the literal pieces with the string forms of
the values.
(let [name "Ada"]
(templates/parts ~"hello-,name"))
; => {strings ["hello-" ""] values ["Ada"]}
(let [name "Ada"]
(template? ~"hello-,name"))
; => true
(let [name "Ada"]
~"hello-,name")
; => "hello-Ada"
(let [name "Ada"]
(str "hello-" name))
; => "hello-Ada"
Use the template to embed forms in a string. Use str to concatenate values.
(let [name "Ada"] [(= ~"hello-,name" (str "hello-" name)) (template? ~"hello-,name") (template? (str "hello-" name))])
true true false
| Signature | Result |
|---|---|
(templates/parts template) |
{strings [...] values [...]}, the literal pieces and the evaluated values |
(templates/from-parts parts) |
A template from a map with strings and values lists |
(templates/render template [options]) |
The rendered string; the escape option changes each value first |
templates/from-parts constructs a template from a map with strings
and values lists. The strings list must have one more item than values.
(templates/from-parts {strings ["hello-" ""] values ["Ada"]})
; => "hello-Ada"
templates/render renders a template. Its optional escape function
receives each evaluated embedded value before it is rendered; literal pieces
pass through unchanged.
For example, escape a query value without escaping its literal parameter prefix:
(let [term "cats & dogs"]
(templates/render
~"search=,term"
{escape (strings/escape "url-query-value")}))
; => "search=cats%20%26%20dogs"
Use the corresponding unescape function to decode an escaped string.
Passing a template to str or strings/join renders its evaluated values.
The result is an ordinary string.
Map literal keys are strings and are not evaluated. To create a key from a template, pass it as a value to a map operation:
(let [name "Ada"]
(put {} ~"hello-,name" 1))
; => {hello-Ada 1}
16.1.19. strings/escape
Function(strings/escape mode text) → string
(strings/escape mode) → function
Escapes text for the specified mode. With only a mode, returns a unary function
that escapes its argument, for use as a template's escape option. The function
prints and hashes as its call, such as (strings/escape "html-text"), and
renders a template argument before escaping it.
(strings/escape "json-pointer" "a/b~") ; => "a~1b~0"
(strings/escape "url-query-value" "a&b c") ; => "a%26b%20c"
(strings/escape "url-form-field" "a&b c") ; => "a%26b+c"
(strings/escape "csv" "a,b") ; => "\"a,b\""
(let [escape-html (strings/escape "html-text")]
(escape-html "<Alice>")) ; => "<Alice>"
Modes are json, dust, ron, csv, json-pointer, html-text,
html-attribute, url-path-segment, url-query-value, and url-form-field.
JSON Pointer mode escapes one segment; URL modes escape one component; CSV mode
escapes one field. The json, dust, and ron modes escape the contents of
a double-quoted string without adding quotes. HTML attribute mode also escapes
quotation marks. URL form fields encode spaces as +; the other URL modes use
%20. An unknown mode produces #err <invalid value>.
[(strings/escape "html-attribute" "&<>\"'")
(strings/escape "html-attribute" "<b>Tom & 'Sue'</b>")
(strings/escape "html-attribute" "&")
(strings/escape "html-attribute" "\\$1🙂")
(strings/escape "html-attribute" "")]
(strings/escape "html-attribute" ""&<>"'"")
(strings/escape "html-attribute" "<b>Tom & 'Sue'</b>")
(strings/escape "html-attribute" "&")
(strings/escape "html-attribute" "\\$1🙂")
(strings/escape "html-attribute" "")
"&<>"'"
"<b>Tom & 'Sue'</b>"
"&amp;"
"\\$1🙂"
""
(strings/escape "json-pointer" "a/b~")
(strings/unescape "json-pointer" "a~1b~0")
(strings/escape "url-query-value" "a&b c")
(strings/escape "url-form-field" "a&b c")
(strings/unescape "url-form-field" "a%26b+c")
(strings/escape "csv" "a,b")
(strings/unescape "csv" "\"a,b\"")
(strings/escape "url-form-field" "*~ ")
(strings/escape "json-pointer" "a/b~")
(strings/unescape "json-pointer" "a~1b~0")
(strings/escape "url-query-value" "a&b c")
(strings/escape "url-form-field" "a&b c")
(strings/unescape "url-form-field" "a%26b+c")
(strings/escape "csv" "a,b")
(strings/unescape
"csv"
"""
"a,b"
"""
)
(strings/escape "url-form-field" "*~ ")
"a~1b~0"
"a/b~"
"a%26b%20c"
"a%26b+c"
"a&b c"
"""
"a,b"
"""
"a,b"
"*%7E+"
(strings/escape "json" "a\"b\n")
(strings/unescape "json" "\\uD83D\\uDE00")
(strings/unescape "ron" (strings/escape "ron" "a\"b\n"))
(strings/unescape "dust" (strings/escape "dust" "a\\b"))
(strings/unescape "json" "\\q")
(strings/unescape "url-query-value" "%2G")
(strings/unescape "json-pointer" "~2")
(strings/escape
"json"
"""
a"b
"""
)
(strings/unescape "json" "\\uD83D\\uDE00")
(strings/unescape
"ron"
(strings/escape
"ron"
"""
a"b
"""
))
(strings/unescape "dust" (strings/escape "dust" "a\\b"))
(strings/unescape "json" "\\q")
(strings/unescape "url-query-value" "%2G")
(strings/unescape "json-pointer" "~2")
""a\u005c"b\\n""
"😀"
"""
a"b
"""
"a\\b"
#err {<invalid value>
message "invalid string escape"}
#err {<invalid value>
message "invalid URL percent escape"}
#err {<invalid value>
message "invalid JSON Pointer escape"}
(strings/escape "html-text" "<a & b>")
(strings/escape "html-attribute" "\"<a>\"")
(strings/unescape "html-text" "<a & b>")
(strings/unescape "html-attribute" "😀 "x"")
(strings/unescape "html-text" "© ≂̸")
(strings/escape "html-text" "<a & b>")
(strings/escape
"html-attribute"
"""
"<a>"
"""
)
(strings/unescape "html-text" "<a & b>")
(strings/unescape "html-attribute" "😀 "x"")
(strings/unescape "html-text" "© ≂̸")
"<a & b>"
""<a>""
"<a & b>"
""😀 "x"""
"© ≂̸"
(strings/escape "url-path-segment" "a/b")
(strings/unescape "url-path-segment" "a%2Fb")
(let [escape-html (strings/escape "html-text")] (escape-html "<Alice>"))
(let [decode (strings/unescape "html-text")] (decode "<Alice>"))
(let [name "<Alice>"] (templates/render ~"<p>,name,</p>" {escape (strings/escape "html-text")}))
(fn? (strings/escape "html-text"))
(strings/escape "unknown" "x")
(strings/unescape "unknown" "x")
(strings/escape 1 "x")
(strings/escape "html-text" 1)
((strings/escape "html-text") "x" "y")
"a%2Fb"
"a/b"
"<Alice>"
"<Alice>"
"<p><Alice></p>"
true
#err <invalid value>
#err <invalid value>
#err <mismatch type>
#err <mismatch type>
#err <arity mismatch>
(let [escape-html (strings/escape "html-text")]
[(escape-html "<Alice>")
(fn? escape-html)
(escape-html ~"<,(str "b"),(do ">")")
(hashes/digest "sha256" escape-html)])
(let
[escape-html (strings/escape "html-text")]
[(escape-html "<Alice>") (fn? escape-html)
(escape-html ~"<,(str "b"),(do ">")") (hashes/digest "sha256" escape-html)])
"<Alice>"
true
"<b>"
#hash #sha256 "2d140a5655b694b51aecece118441a80fdd245852dc87ae6babb33de709aba34"
[(strings/escape)
(strings/unescape "html-text" "a" "b")
((strings/escape "html-text"))
((strings/unescape "html-text") 1)]
(strings/escape)
(strings/unescape "html-text" "a" "b")
((strings/escape "html-text"))
((strings/unescape "html-text") 1)
#err <arity mismatch>
#err <arity mismatch>
#err <arity mismatch>
#err <mismatch type>
16.1.20. strings/unescape
Function(strings/unescape mode text) → string
(strings/unescape mode) → function
Decodes text for the same modes as strings/escape. With only a mode, returns
a unary decoding function that prints and hashes as its call, such as
(strings/unescape "url-query-value"). Invalid JSON Pointer, URL percent, CSV, and quoted
string escapes produce #err <invalid value>, as do URL percent escapes whose
bytes are not UTF-8, since strings are always Unicode text. HTML decoding recognizes
semicolon-terminated named and numeric character references.
(strings/unescape "json-pointer" "a~1b~0") ; => "a/b~"
(strings/unescape "html-text" "<Alice>") ; => "<Alice>"
(let [decode (strings/unescape "url-query-value")]
(decode "cats%20%26%20dogs")) ; => "cats & dogs"
16.1.21. strings/normalize
Function(strings/normalize s) → string
(strings/normalize s form) → string
Returns s normalized to the Unicode normalization form, defaulting to NFC.
The form is one of the exact strings NFC, NFD, NFKC, or NFKD.
Other strings produce an error.
NFC and NFD apply canonical normalization.
NFKC and NFKD also apply compatibility normalization, which can remove meaningful distinctions.
Normalization does not perform case folding or guarantee visually distinct identifiers.
[(strings/normalize "é") (strings/normalize "é" "NFD") (strings/normalize "A①ffi" "NFKC") (strings/normalize "Å①" "NFKD") (strings/normalize "①" "NFC") (strings/normalize "가" "NFC") (strings/normalize "" "NFD") (strings/normalize "É" "NFC") (strings/normalize "ࢡ" "NFC")]
(strings/normalize "é") (strings/normalize "é" "NFD") (strings/normalize "A①ffi" "NFKC") (strings/normalize "Å①" "NFKD") (strings/normalize "①" "NFC") (strings/normalize "가" "NFC") (strings/normalize "" "NFD") (strings/normalize "É" "NFC") (strings/normalize "ࢡ" "NFC")
"é" "é" "A1ffi" "Å1" "①" "가" "" "É" "ࢡ"
16.1.22. strings/of
Function(strings/of points) → string
Returns the string formed by the Unicode scalar values in the list points, in order.
Each element must be an integer from zero through 1114111, excluding the surrogate range 55296 through 57343. Invalid scalar values and non-integer elements produce errors. An empty list produces the empty string. Unassigned code points and noncharacters are accepted when they are valid scalar values. The result is not normalized.
[(strings/of [65 769]) (strings/of [128578]) (strings/of []) (strings/of [0 65]) (strings/of [1114111]) (strings/of [888])]
(strings/of [65 769]) (strings/of [128578]) (strings/of []) (strings/of [0 65]) (strings/of [1114111]) (strings/of [888])
"Á" "🙂" "" "\u0000A" "" ""
16.2. strings/humanize
Function(strings/humanize value options?) → string
Formats an integer, float, duration, or UTC value as readable text. Options are a map with string keys. Unknown options and options irrelevant to the value's kind are errors.
| Value kind | Options | Defaults |
|---|---|---|
| Integer or float | scale, unit, precision |
SI scale, empty unit, precision 1 |
| Duration | precision |
Precision 1 |
| UTC | mode, now |
Absolute mode |
For numbers, scale is si or binary. SI uses powers of 1000 with prefixes
such as k and M; binary uses powers of 1024 with prefixes such as Ki and
Mi. A string unit is appended directly, allowing B, /s, and Unicode
units. Signed integers retain full precision before rounding.
precision is an integer from zero through nine and selects the maximum
fractional decimal places. Rounding is halfway away from zero; trailing
fractional zeros are omitted. A rounded value can carry into the next unit:
999950 at the default precision becomes 1M.
(strings/humanize 1500) (strings/humanize 1536 {scale "binary" unit "B"}) (strings/humanize 1234 {precision 2 unit "/s"}) (strings/humanize -1250) (strings/humanize 999950) (strings/humanize 9223372036854775807 {precision 9})
"1.5k" "1.5KiB" "1.23k/s" "-1.3k" "1M" "9.223372037E"
Durations use hours, minutes, seconds, or a suitable subsecond unit. Examples
include 1h 30m, 2.5s, 150µs, and 100ns. The precision applies to the
displayed fractional unit; the stored tick value is unchanged.
(strings/humanize #dur "PT1H30M") (strings/humanize #dur "PT2.5S") (strings/humanize #dur "PT0.00015S") (strings/humanize #dur "PT59.99S") (strings/humanize #dur "PT1.2345678S" {precision 9}) (strings/humanize #dur "PT0.0000001S")
"1h 30m" "2.5s" "150µs" "1m" "1.2345678s" "100ns"
UTC mode is absolute or relative. Absolute formatting produces the
canonical UTC timestamp, retaining its 100 ns precision. Relative formatting
requires an explicit UTC now option and produces text such as 3 minutes ago
or in 2 days. It selects the largest whole unit among days, hours, minutes,
and seconds; differences shorter than a second produce now. Supplying now
in absolute mode is an error. The function never reads the clock implicitly.
(strings/humanize #utc "2026-10-29T12:00:00.1234567Z") (strings/humanize #utc "2026-10-29T12:00:00Z" {mode "relative" now #utc "2026-10-29T12:03:00Z"}) (strings/humanize #utc "2026-10-31T12:00:00Z" {mode "relative" now #utc "2026-10-29T12:00:00Z"}) (strings/humanize #utc "2026-10-29T12:00:00Z" {mode "relative" now #utc "2026-10-29T12:00:00Z"})
"2026-10-29T12:00:00.1234567Z" "3 minutes ago" "in 2 days" "now"
(strings/humanize #utc "2026-10-29T12:00:00Z" {mode "relative"})
#err <invalid value>
See the Time library for temporal constructors, arithmetic,
calendar operations, and time/now.
17 Parsing Expression Grammars
The pegs/ namespace matches Unicode text with parsing expression grammars
(PEGs). A grammar can use recursive rules, captures, labels and ordinary DUST
actions. It requires the stdlib plugin. Matching is not guaranteed to take
linear time.
17.1. Compile, match and search
| Signature | Result |
|---|---|
(pegs/compile pattern) |
An immutable compiled PEG |
(pegs/match pattern text [start [options]]) |
A capture List, or null for no match |
(pegs/find pattern text [start [options]]) |
The first matching start index, or null |
(pegs/find-all pattern text [start [options]]) |
All matching start indices, including overlaps |
(pegs/replace-first pattern text replacement [start [options]]) |
Replace the first match |
(pegs/replace pattern text replacement [start [options]]) |
Replace non-overlapping matches |
(pegs/compile-form form [env]) |
Compile pattern data with an optional bindings Map |
The first six forms take unquoted pattern syntax. They are macros, and cannot
be passed to apply. A pattern can refer to a local containing a compiled PEG
or a character predicate.
pegs/compile-form is an ordinary function. Its optional env Map has String
keys naming PEG, predicate, or action bindings. It does not evaluate pattern data as DUST
code. Keep action functions in env to keep their original lexical bindings.
Input must be a valid UTF-8 String. The optional start defaults to zero;
null also selects zero. Otherwise it must be an integer from zero through
the input's code-point count, inclusive. The optional options map comes last.
Without options, or with null, the operation uses the default step budget.
Its only option, steps, is a positive integer that sets the operation's
step budget (see Values, errors and limits), as in
(pegs/match p text null {steps 50000000}). Options must be null or a map.
An unknown option or a steps value that is not a positive integer is an error.
Indices count code points, not bytes. Line and column start at one. LF starts
a new line, and CRLF is one line break. A match accepts a prefix. Add (end)
to require the end of the active input window.
(let [p (pegs/compile "a")]
(pegs/match (seq p "b" (end)) "ab"))
(pegs/match (seq #re "([a-z]+)" ":" ($ (+ chars/ascii-digit?)) (end)) "spice:42")
(pegs/match (seq (position) 1 (line) (column)) "α\r\nβ" 3)
Results, in order:
[]
["spice" "42"]
[3 2 2]
(let [suffix "!"
action (fn [text] (str text suffix))
p (pegs/compile-form `(call ($ (+ chars/word?)) action) {action action})]
(pegs/match p "spice"))
(pegs/match #peg (seq "a" ($ "b")) "ab")
Results, in order:
["spice!"]
["b"]
Search includes the boundary at the end of the input. find-all resumes one
code point after each match's start, so matches can overlap. Replacements
resume at the end of a consuming match. After an empty replacement, search
advances one code point and preserves that input character. An empty match at
the end is processed once.
A replacement is a String or a function. The function receives captures as
positional arguments. With no captures, it receives the whole matched text.
Its result must be a String. The prefix before start remains unchanged.
No match leaves the input unchanged.
(pegs/find (end) "abc")
(pegs/find-all "" "ab")
(pegs/replace "" "ab" "-")
(pegs/find-all "aa" "aaa")
(pegs/replace "aa" "aaa" "X")
(pegs/replace-first "a" "aaa" "X")
(pegs/replace ($ (+ chars/ascii-digit?)) "a12b34" (fn [n] (str "[" n "]")))
Results, in order:
3
[0 1 2]
"-a-b-"
[0 1]
"Xa"
"Xaa"
"a[12]b[34]"
17.2. Patterns and rule names
A String matches literal text. A nonnegative integer consumes that many code
points. true succeeds empty, and false fails. A grammar Map requires a
main rule. Rules can refer forward and call each other recursively.
Compilation rejects recursion that can repeat without consuming input,
including cycles through lookahead or nullable external PEGs.
A bare name selects a rule in the nearest enclosing grammar, then an outer
grammar, then a captured compiled PEG or function. A referenced rule name must
not also name a lexical binding. Quote literal text: "word" matches text, and word
refers to a rule or binding.
A function in pattern position is a consuming character predicate. It receives
one code point as a String; true consumes it and false fails. A non-Boolean
result is a Type_Mismatch. At end of input the predicate is not called.
Use a named function such as chars/letter?, a lexical function binding, or
an inline (fn [c] ( c "a"))=. The chars/ predicates accept one String that contains exactly one code point and
return a Boolean. They are also schemas. In a pattern, write the name without the call, such as chars/letter?.
| Signature | Matches |
|---|---|
(chars/letter? c) |
One Unicode letter |
(chars/word? c) |
One Unicode letter or decimal digit |
(chars/space? c) |
One Unicode whitespace code point |
(chars/ascii-letter? c) |
One ASCII letter |
(chars/ascii-word? c) |
One ASCII letter or decimal digit |
(chars/ascii-space? c) |
One ASCII whitespace character |
(chars/ascii-digit? c) |
One ASCII decimal digit |
(chars/hex? c) |
One ASCII hexadecimal digit |
pegs/newline |
CRLF or LF |
pegs/line-end |
Newline or end of the active window |
The reusable PEG values contain ordinary patterns. Outside pattern syntax,
read them as :pegs/newline and :pegs/line-end, like other builtin constants.
Operators are recognized only in invocation heads. Label names and error tags
are literal names, not variable lookups.
A List pattern must have the form [name "<-" p].
17.3. Operators
Here, p and q are patterns. Bounds and capture indices are literal
nonnegative integers. Unknown operators and incorrect arities are errors.
| Operator | Behavior |
|---|---|
(seq p*) |
Match in order; an empty sequence succeeds |
(or p*) |
Select the first success; an empty choice fails |
(repeat p min max) |
Greedy repetition; null maximum means unbounded |
(opt p), (? p) |
Repeat zero or one time |
(any p), (* p) |
Repeat zero or more times |
(some p), (+ p) |
Repeat one or more times |
(not p) |
Require failure, consume nothing, discard captures and labels |
(look p) |
Require success, consume nothing, keep captures and labels |
(end) |
Require the end of the active window |
(set "chars") |
Consume one member code point |
(range "az" "AZ" ...) |
Consume one code point in any inclusive pair |
(to p) |
Consume up to the first match; discard its captures and labels |
(thru p) |
Consume through the first match; keep its captures and labels |
(within p window) |
Match window, then run p inside it; consume the whole window |
(split p separator) |
Run p in each segment, keeping its captures; consume the window |
(sep-by p separator) |
Match p followed by zero or more separator p pairs |
(capture p), ($ p) |
Append consumed text after p's captures |
(group p) |
Replace p's captures with one List, including an empty List |
(drop p) |
Remove captures, keeping labels |
(join p) |
Concatenate captures' str representations into one String |
(nth p index) |
Keep capture index; a missing capture fails |
(number p [base]) |
Parse consumed text into one number; invalid text fails |
(position), (line), (column) |
Append the absolute input coordinate |
(label p name), [name "<-" p] |
Require exactly one capture and bind its name |
(backref name) |
Append the bound capture without consuming |
(backmatch name) |
Match the bound String at the current position |
(call p [params] body*), (call p f) |
Replace captures with one action result |
(check p [params] body*), (check p f) |
As call; false, null or an ordinary error result fails |
(error [p [tags]]) |
Abort the PEG call with an error when p matches |
Each range String contains exactly two ordered code points. number defaults
to base 10 and accepts DUST integer/float spelling. Other bases, from 2 through
36, accept signed integers. The whole consumed text must parse without overflow.
to and thru try every boundary, including the window's end. A successful
thru executes its pattern once. within discards window captures and labels.
Its inner pattern need not consume the whole window unless it uses end.
split includes empty and trailing segments and discards separator captures
and labels. An empty separator match is an invalid-PEG error. Each separator
is found once per boundary. All coordinates remain relative to the original input.
17.4. Captures, actions and backtracking
A match returns a List even when it captures nothing. False, null and ordinary
error values can be captured data. nth selects a capture, not an element
inside a captured List. An unset backreference fails. A label bound to false
or null is set. backmatch requires a String label.
A failed branch restores the input position, captures and labels. Ordered choice does not reopen a successful alternative after a later failure. Repetition does not give back successful iterations. An unbounded repetition undoes an empty attempt and stops without counting it. Finite repetition can count empty successes up to its bound.
(pegs/match (or (seq ($ "a") "x") ($ "ab")) "ab")
(pegs/match (seq (or "a" "ab") "c") "abc")
(pegs/match (seq (any "a") "a") "aaa")
(pegs/match (any ($ "")) "")
(pegs/match (some ($ "")) "")
(pegs/match (group "a") "a")
(pegs/match (nth (group (seq ($ "a") ($ "b"))) 1) "ab")
(pegs/match (nth (seq ($ "a") ($ "b")) 1) "ab")
Results, in order:
["ab"]
null
null
[]
null
[[]]
null
["b"]
Each rule or compiled-PEG call has a fresh label frame. A nested rule cannot overwrite its caller's labels. Label a nested call to export its single result. Duplicate syntactic label definitions in one frame are invalid. Repetition of one definition keeps its last successful binding.
Inline actions can read labels introduced by their pattern. These labels
shadow outer locals. An optional label that was not bound supplies null.
Positional parameters support ordinary function destructuring, _ and ....
A name cannot occur in both positional parameters and implicit labels.
Label-only actions can omit parameters: (call p body*). A sole Local/Const
reference, Function value or (fn ...) expression instead selects the function
form. Use explicit [] to make a bare label reference an inline body.
An empty parameter List ignores positional captures. The function form receives
positional captures under ordinary function arity rules.
Actions execute immediately. Backtracking does not undo their mutations,
transactions or I/O. Another attempted branch can execute an action again.
Compilation never executes actions. Cancellation and exhausted budgets propagate
through or, not and check.
(let [seen []]
[(pegs/match (or (seq (call "a" [] (lists/append seen 1)) "x") "ab") "ab")
seen])
(pegs/match (call (seq ($ "a") ($ "b")) [first ... rest] [first rest]) "ab")
(pegs/match (nth (call "" [] false) 0) "")
(pegs/match (nth (call "" [] null) 0) "")
Results, in order:
[[] [1]]
[["a" ["b"]]]
[false]
[null]
(pegs/match
{main node
node (check
(seq "<" [tag "<-" ($ (+ chars/word?))] ">"
[children "<-" (group (* node))]
"</" [close "<-" ($ (+ chars/word?))] ">")
(when (= tag close) {tag tag children children}))}
"<a><b></b></a>")
Results, in order:
[{tag "a" children [{tag "b" children []}]}]
A regex leaf matches at the current position using the native regex engine. It appends numbered groups 1 through N, excluding group zero. Unmatched groups append null. Named groups keep numeric slots and do not define PEG labels. A successful regex is atomic. Later failure cannot request another match length. Anchors see the active window, not a suffix beginning at each search candidate.
17.5. Comments and source data
DUST semicolon comments in patterns and actions are source annotations. They do not affect operands, validation, matching or compiled-code cache keys. Authored namespace source keeps its comments and source spans through save/load. Canonical PEG values and evaluated results do not keep authored comments.
#mute removal happens before arity and name checks. A muted required root
is an error. Comments in subject text are ordinary input. The grammar must
explicitly recognize or skip them.
(pegs/match (seq "a" ; annotation, not an operand
#mute (unknown ignored)
"b") "ab")
(pegs/match ($ (seq ";" (to pegs/line-end))) "; keep me")
Results, in order:
[]
["; keep me"]
; A Fluent message subset: comments, identifiers and plain-text values.
; This grammar does not implement Fluent expressions or its resolver.
(pegs/match
{main (seq (* (or (drop comment) message)) (end))
horizontal-space (set " \t")
comment (seq "#" (to pegs/line-end) pegs/line-end)
message (call
(seq [id "<-" ($ (seq chars/ascii-letter? (* (or chars/ascii-word? "-"))))]
(* horizontal-space) "=" (* horizontal-space)
[value "<-" ($ (to pegs/line-end))] pegs/line-end)
{id id value value})}
"# Greeting\nhello-user = Hello, traveler!\nfarewell = Goodbye")
Results, in order:
[{id "hello-user" value "Hello, traveler!"} {id "farewell" value "Goodbye"}]
17.6. Values, errors and limits
A #peg pattern value contains one pattern form. Quoting or decoding preserves
that source without executing it. Materialization requires stdlib. Closed
PEGs serialize with normalized source through all document codecs and can be
used in another runtime. Referenced closed PEGs are included in that source.
A PEG with live lexical action bindings works in its runtime, but serialization
reports the existing unrepresentable-function error. Compiled PEGs compare by
identity. Rebinding an outer local does not replace an already captured value.
Mutable captured values keep their ordinary aliases.
Invalid patterns report <invalid peg> with a message and pattern-path.
The path contains rule names and zero-based operand indices. Action errors
retain their ordinary classifications and DUST source positions.
The error operator defaults to true. Its last String capture supplies the
message, or the message is PEG match failed. Its error has peg and the
literal tags, plus input-index, input-line and input-column at the operator's
entry position. These subject coordinates are separate from DUST position.
Tags cannot use diagnostic field names: message, input-index, input-line,
input-column, position, code or value. The error aborts the PEG operation
and returns ordinary #err data to DUST.
Compilation limits source nodes to 1,000,000. It has no work limit and no depth
limit, and a grammar can have any number of rules: the evaluation's CPU and
memory budgets bound compilation. One
PEG operation has a step budget, by default 10,000,000 steps, shared across
input preparation, dispatch, search and native regex visits. It is a work
bound: it ends a pattern that runs away, even with unlimited CPU time. Past it,
the operation fails with a Resource_Limit error that names the budget. The
steps option sets another budget for one operation. Nested PEG callbacks share
the remaining steps of the operation that called them, and their own steps
option has no effect. Rule calls nest to any depth: the step budget and the
memory budget bound them. Captures, checkpoints and find-all results have no
count limit; the runtime memory budget bounds them. Runtime memory limits include stacks, caches and native
scratch.
Compilation and matching observe cancellation. The runtime remains reusable
after a limit or cancellation. Compiled code caching is limited to 64 entries
per runtime.
18 Regular Expression Functions
The regexes/ namespace uses regular expressions with leftmost-first matching.
Patterns support literal text, character classes, Unicode-aware shorthand classes,
alternatives, numbered and named captures, anchors, and greedy or lazy repetition.
Backreferences and lookaround are not supported.
For a fixed pattern, matching time grows linearly with the input length.
Choice and capture priority use leftmost-first matching, including
when a repeated group can match empty text.
A #re literal contains a pattern string and produces a regex value.
An invalid pattern produces an error when the literal is evaluated.
Quoting a literal preserves its source data without evaluating the pattern. Regex values retain
their original pattern text for formatting and compare by that text.
Matching uses UTF-8 and Unicode properties for shorthand classes by default.
Unicode category escapes \p{...} and \P{...} support L, Lu, Ll,
N, Nd, Mn, Pc, Z, and Zs, and their long names.
Leading flag groups enable Unicode simple case folding ((?i)), multiline
anchors ((?m)), and matching newlines with dot ((?s)). Flags may be
combined, as in (?im). Scoped flag groups are not supported.
The \C byte-matching construct is rejected because captures must not split a UTF-8 code point.
re denotes a regex value. Literal text operations use strings/.
Functions that return matches accept an optional final options map, tagged
with named, indices, or both. The named tag selects a map of named
captures, with {} when the pattern has no named groups. The indices tag
returns zero-based, start-inclusive, end-exclusive code-point ranges instead of
text. With indices and no capture groups, the result is a single range; with
groups, it is a list of ranges. Combine the tags to map names to ranges. An
unmatched capture is null. Without options, regexes/groups defines the result
format.
(regexes/find #re "(?<year>[0-9]{4})" "2026" <named>)
; {year "2026"}
(regexes/find #re "(?<year>[0-9]{4})" "2026" <named indices>)
; {year [0 4]}
18.1. Regex functions
18.1.1. regexes/pattern
Function(regexes/pattern s) → pattern
Returns a regex value for string s, or s unchanged if it is already a pattern.
Invalid patterns produce an error.
18.1.2. regexes/matcher
Function(regexes/matcher re s) → matcher
Returns a new mutable matcher for re in string s, for use with regexes/find and regexes/groups.
A matcher can be used across evaluations in the same session.
It cannot be serialized or used in another session.
The current match is cleared when a search reaches the end without a match.
18.1.3. regexes/find
Function(regexes/find matcher [opts]) → string, list, map, or null
(regexes/find re s [opts]) → string, list, map, or null
Returns the next match from matcher, or the first match of re in string s.
Returns null if there is no match.
The matcher form advances matcher.
The pattern and string form starts a fresh search.
Results use the capture format of regexes/groups.
18.1.4. regexes/groups
Function(regexes/groups matcher [opts]) → string, list, or map
Returns the current match from matcher without advancing it.
Without options and with no capture groups, returns the matched string.
Otherwise, returns a list containing the full match followed by each capture in group-number order.
An unmatched group is null.
Without a current match, produces an error.
18.1.5. regexes/matches
Function(regexes/matches re s [opts]) → string, list, map, or null
Returns the match if re matches the entire string s, otherwise null.
Results use the capture format of regexes/groups.
18.1.6. regexes/find-all
Function(regexes/find-all re s [opts]) → list
Returns an eager list of successive, non-overlapping matches of re in string s.
Each item uses the capture format of regexes/groups.
Returns an empty list if there are no matches.
After an empty match, the search first tries a nonempty match at the same
position; if there is none, it advances by one code point.
18.1.7. regexes/split
Function(regexes/split s re) → list
(regexes/split s re limit) → list
Returns a list of parts of string s split on matches of re.
The integer limit defaults to zero.
A positive limit permits at most that many parts, with the unsplit suffix in the last part.
Zero omits trailing empty strings.
A negative limit preserves them.
A zero-width match at the start of s does not create a leading empty part.
If no split occurs, the result contains s as its only part.
18.1.8. regexes/replace
Function(regexes/replace s re replacement [opts]) → string
Returns string s with all non-overlapping matches of re replaced by replacement.
replacement is a string or a function of the match.
In a replacement string, $1, $2, etc. substitute captured groups.
$0 substitutes the whole match. A backslash escapes the next character; an
unmatched capture substitutes an empty string. When a match is replaced, an invalid group number or a trailing backslash
produces an error. When digits follow a group number, the
longest valid group number is used. Use regexes/quote-replacement for literal
replacement text.
A function receives each match in regexes/groups format, in search order, and must return a string, which is inserted literally.
The optional result options select the argument format for a function replacement.
Result options are invalid for a string replacement.
18.1.9. regexes/replace-first
Function(regexes/replace-first s re replacement [opts]) → string
Returns string s with the first match of re replaced by replacement.
Uses the replacement rules of regexes/replace.
18.1.10. regexes/quote-replacement
Function(regexes/quote-replacement replacement) → string
Returns string replacement escaped for literal use with regexes/replace or regexes/replace-first.
19 Mathematics Functions
19.1. Math functions
The math/ functions accept numbers, and selected functions also accept temporal values. Arguments to a function must all have
the same numeric type; mixed integers and floats produce #err <mismatch type>.
math/abs also accepts a duration. Each function describes its result and
errors below. The namespace includes constants for pi, tau, e, and conversion
between degrees and radians.
19.1.1. math/pi
The constant :math/pi is the float 3.141592653589793, the nearest binary64 approximation to pi.
19.1.2. math/tau
The constant :math/tau is the float 6.283185307179586, the nearest binary64 approximation to two times pi.
19.1.3. math/deg2rad
The constant :math/deg2rad is pi divided by 180, as a float. Multiply degrees
by this value to convert them to radians.
19.1.4. math/rad2deg
The constant :math/rad2deg is 180 divided by pi, as a float. Multiply radians
by this value to convert them to degrees.
19.1.5. math/e
The constant :math/e is the float 2.718281828459045, the nearest binary64 approximation to the base of natural logarithms.
19.1.6. math/floor
Function(math/floor n) → float
Returns the greatest integral-valued float less than or equal to n after conversion to a float.
[(math/floor 1.8) (math/floor -1.2) (math/floor 2) (math/floor 0.0) (math/floor 9007199254740993) (math/floor 100000000000000000000.0)]
(math/floor 1.8) (math/floor -1.2) (math/floor 2) (math/floor 0.0) (math/floor 9007199254740993) (math/floor 100000000000000000000.0)
1.0 -2.0 2.0 0.0 9007199254740992.0 100000000000000000000.0
19.1.7. math/ceil
Function(math/ceil n) → float
Returns the least integral-valued float greater than or equal to n after conversion to a float.
[(math/ceil 1.2) (math/ceil -1.8) (math/ceil 2) (math/ceil 0.0) (math/ceil -0.2) (math/ceil 9007199254740993) (math/ceil 100000000000000000000.0)]
(math/ceil 1.2) (math/ceil -1.8) (math/ceil 2) (math/ceil 0.0) (math/ceil -0.2) (math/ceil 9007199254740993) (math/ceil 100000000000000000000.0)
2.0 -1.0 2.0 0.0 0.0 9007199254740992.0 100000000000000000000.0
19.1.8. math/round
Function(math/round n) → integer
Returns the integer nearest to n, rounding halfway cases away from zero.
Integer inputs are returned unchanged.
A float whose rounded value is outside the signed 64-bit integer range produces #err <integer overflow>.
[(math/round 1.4) (math/round 1.5) (math/round 2.5) (math/round -1.5) (math/round -2.5) (math/round -1.6) (math/round 0.5) (math/round -0.5) (math/round 0.49999999999999994) (math/round -0.5000000000000001) (math/round 7) (math/round 9007199254740993) (math/round 9223372036854775807) (math/round -9223372036854775808) (math/round -9223372036854776000.0) (math/round 9223372036854775000.0)]
(math/round 1.4) (math/round 1.5) (math/round 2.5) (math/round -1.5) (math/round -2.5) (math/round -1.6) (math/round 0.5) (math/round -0.5) (math/round 0.49999999999999994) (math/round -0.5000000000000001) (math/round 7) (math/round 9007199254740993) (math/round 9223372036854775807) (math/round -9223372036854775808) (math/round -9223372036854776000.0) (math/round 9223372036854775000.0)
1 2 3 -2 -3 -2 1 -1 0 -1 7 9007199254740993 9223372036854775807 -9223372036854775808 -9223372036854775808 9223372036854774784
19.1.9. math/rint
Function(math/rint n) → float
Returns the integral-valued float nearest to n after conversion to a float, choosing the even integer in halfway cases.
The result does not depend on the host's current rounding mode.
[(math/rint 1.5) (math/rint 2.5) (math/rint -1.5) (math/rint -2.5) (math/rint 0.5) (math/rint -0.5) (math/rint 7) (math/rint 9007199254740993)]
(math/rint 1.5) (math/rint 2.5) (math/rint -1.5) (math/rint -2.5) (math/rint 0.5) (math/rint -0.5) (math/rint 7) (math/rint 9007199254740993)
2.0 2.0 -2.0 -2.0 0.0 0.0 7.0 9007199254740992.0
19.1.10. math/trunc
Function(math/trunc n) → float
Returns n converted to a float with its fractional part discarded, rounding toward zero.
[(math/trunc 1.8) (math/trunc -1.8) (math/trunc 2) (math/trunc -0.2) (math/trunc 9007199254740993)]
(math/trunc 1.8) (math/trunc -1.8) (math/trunc 2) (math/trunc -0.2) (math/trunc 9007199254740993)
1.0 -1.0 2.0 0.0 9007199254740992.0
19.1.11. math/pow
Function(math/pow base exponent) → float
Returns base raised to exponent.
A zero exponent returns 1.0, including when base is zero.
A negative base requires an integral-valued exponent after float conversion.
A zero base with a negative exponent produces #err <float overflow>.
[(math/pow 2 3) (math/pow -2 3) (math/pow 9 0.5) (math/pow 0 0) (math/pow 2 -3)]
(math/pow 2 3) (math/pow -2 3) (math/pow 9 0.5) (math/pow 0 0) (math/pow 2 -3)
8.0 -8.0 #err <mismatch type> 1.0 0.125
19.1.12. math/sqrt
Function(math/sqrt n) → float
Returns the square root of n.
A negative n produces #err <float overflow>.
A zero result has the same sign as n.
[(math/sqrt 0) (math/sqrt 4) (math/sqrt 9.0)]
(math/sqrt 0) (math/sqrt 4) (math/sqrt 9.0)
0.0 2.0 3.0
19.1.13. math/cbrt
Function(math/cbrt n) → float
Returns the real cube root of n, with the same sign as n.
[(math/round (* 1000000000000.0 (math/cbrt -8))) (math/round (* 1000000000000.0 (math/cbrt 0))) (math/round (* 1000000000000.0 (math/cbrt 27)))]
(math/round (* 1000000000000.0 (math/cbrt -8))) (math/round (* 1000000000000.0 (math/cbrt 0))) (math/round (* 1000000000000.0 (math/cbrt 27)))
-2000000000000 0 3000000000000
19.1.14. math/hypot
Function(math/hypot x y) → float
Returns the square root of x*x + y*y without intermediate overflow or underflow.
An out-of-range final result produces #err <float overflow>.
[(math/hypot 3 4) (math/hypot -3 -4) (math/hypot 0 0) (math/hypot 0 1.5)]
(math/hypot 3 4) (math/hypot -3 -4) (math/hypot 0 0) (math/hypot 0 1.5)
5.0 5.0 0.0 #err <mismatch type>
[(math/round (* 1000000000000.0 (/ (math/hypot 1e+308 1e+308) 1e+308))) (math/round (* 1000000000000.0 (/ (math/hypot 1e-308 1e-308) 1e-308)))]
(math/round (* 1000000000000.0 (/ (math/hypot 1e+308 1e+308) 1e+308))) (math/round (* 1000000000000.0 (/ (math/hypot 1e-308 1e-308) 1e-308)))
1414213562373 1414213562373
19.1.15. math/exp
Function(math/exp n) → float
Returns e raised to n.
[(math/round (* 1000000000000.0 (math/exp -1))) (math/round (* 1000000000000.0 (math/exp 0))) (math/round (* 1000000000000.0 (math/exp 1)))]
(math/round (* 1000000000000.0 (math/exp -1))) (math/round (* 1000000000000.0 (math/exp 0))) (math/round (* 1000000000000.0 (math/exp 1)))
367879441171 1000000000000 2718281828459
19.1.16. math/exp2
Function(math/exp2 n) → float
Returns two raised to n.
[(math/exp2 -3) (math/exp2 0) (math/exp2 3)]
(math/exp2 -3) (math/exp2 0) (math/exp2 3)
0.125 1.0 8.0
19.1.17. math/expm1
Function(math/expm1 n) → float
Returns e raised to n minus one, computed without the loss of precision from subtracting one from math/exp's rounded result near zero.
[(math/round (* 1000000000000.0 (math/expm1 -1))) (math/round (* 1000000000000.0 (math/expm1 0))) (math/round (* 1000000000000.0 (math/expm1 1)))]
(math/round (* 1000000000000.0 (math/expm1 -1))) (math/round (* 1000000000000.0 (math/expm1 0))) (math/round (* 1000000000000.0 (math/expm1 1)))
-632120558829 0 1718281828459
19.1.18. math/log
Function(math/log n) → float
(math/log n base) → float
Returns the natural logarithm of n, or its logarithm in the supplied base.
When base is supplied, both numbers must have the same type. The base must be
positive and cannot be one.
A zero or negative n produces #err <float overflow>.
[(math/round (* 1000000000000.0 (math/log 0.5))) (math/round (* 1000000000000.0 (math/log 1))) (math/round (* 1000000000000.0 (math/log 2)))]
(math/round (* 1000000000000.0 (math/log 0.5))) (math/round (* 1000000000000.0 (math/log 1))) (math/round (* 1000000000000.0 (math/log 2)))
-693147180560 0 693147180560
19.1.19. math/log2
Function(math/log2 n) → float
Returns the base-two logarithm of n.
A zero or negative n produces #err <float overflow>.
[(math/log2 0.5) (math/log2 1) (math/log2 2) (math/log2 8)]
(math/log2 0.5) (math/log2 1) (math/log2 2) (math/log2 8)
-1.0 0.0 1.0 3.0
19.1.20. math/log10
Function(math/log10 n) → float
Returns the base-ten logarithm of n.
A zero or negative n produces #err <float overflow>.
[(math/log10 0.1) (math/log10 1) (math/log10 10) (math/log10 100)]
(math/log10 0.1) (math/log10 1) (math/log10 10) (math/log10 100)
-1.0 0.0 1.0 2.0
19.1.21. math/log1p
Function(math/log1p n) → float
Returns the natural logarithm of one plus n, computed without the loss of precision from rounding 1 + n near zero.
An n less than or equal to -1 produces #err <float overflow>.
[(math/round (* 1000000000000.0 (math/log1p -0.5))) (math/round (* 1000000000000.0 (math/log1p 0))) (math/round (* 1000000000000.0 (math/log1p 1)))]
(math/round (* 1000000000000.0 (math/log1p -0.5))) (math/round (* 1000000000000.0 (math/log1p 0))) (math/round (* 1000000000000.0 (math/log1p 1)))
-693147180560 0 693147180560
19.1.22. math/sin
Function(math/sin angle) → float
Returns the sine of angle in radians.
[(math/round (* 1000000000000.0 (math/sin -1))) (math/round (* 1000000000000.0 (math/sin 0))) (math/round (* 1000000000000.0 (math/sin 1)))]
(math/round (* 1000000000000.0 (math/sin -1))) (math/round (* 1000000000000.0 (math/sin 0))) (math/round (* 1000000000000.0 (math/sin 1)))
-841470984808 0 841470984808
19.1.23. math/cos
Function(math/cos angle) → float
Returns the cosine of angle in radians.
[(math/round (* 1000000000000.0 (math/cos -1))) (math/round (* 1000000000000.0 (math/cos 0))) (math/round (* 1000000000000.0 (math/cos 1)))]
(math/round (* 1000000000000.0 (math/cos -1))) (math/round (* 1000000000000.0 (math/cos 0))) (math/round (* 1000000000000.0 (math/cos 1)))
540302305868 1000000000000 540302305868
19.1.24. math/tan
Function(math/tan angle) → float
Returns the tangent of angle in radians.
[(math/round (* 1000000000000.0 (math/tan -1))) (math/round (* 1000000000000.0 (math/tan 0))) (math/round (* 1000000000000.0 (math/tan 1)))]
(math/round (* 1000000000000.0 (math/tan -1))) (math/round (* 1000000000000.0 (math/tan 0))) (math/round (* 1000000000000.0 (math/tan 1)))
-1557407724655 0 1557407724655
19.1.25. math/asin
Function(math/asin n) → float
Returns the arc sine of n in radians, in the range from negative pi/2 to pi/2.
An n outside [-1, 1] produces #err <float overflow>.
[(math/round (* 1000000000000.0 (math/asin -1))) (math/round (* 1000000000000.0 (math/asin 0))) (math/round (* 1000000000000.0 (math/asin 1)))]
(math/round (* 1000000000000.0 (math/asin -1))) (math/round (* 1000000000000.0 (math/asin 0))) (math/round (* 1000000000000.0 (math/asin 1)))
-1570796326795 0 1570796326795
19.1.26. math/acos
Function(math/acos n) → float
Returns the arc cosine of n in radians, in the range from zero to pi.
An n outside [-1, 1] produces #err <float overflow>.
[(math/round (* 1000000000000.0 (math/acos -1))) (math/round (* 1000000000000.0 (math/acos 0))) (math/round (* 1000000000000.0 (math/acos 1)))]
(math/round (* 1000000000000.0 (math/acos -1))) (math/round (* 1000000000000.0 (math/acos 0))) (math/round (* 1000000000000.0 (math/acos 1)))
3141592653590 1570796326795 0
19.1.27. math/atan
Function(math/atan n) → float
Returns the arc tangent of n in radians, in the range from negative pi/2 to pi/2.
[(math/round (* 1000000000000.0 (math/atan -1))) (math/round (* 1000000000000.0 (math/atan 0))) (math/round (* 1000000000000.0 (math/atan 1)))]
(math/round (* 1000000000000.0 (math/atan -1))) (math/round (* 1000000000000.0 (math/atan 0))) (math/round (* 1000000000000.0 (math/atan 1)))
-785398163397 0 785398163397
19.1.28. math/atan2
Function(math/atan2 y x) → float
Returns the angle of the point (x, y) in radians, in the range from negative pi to pi, using both signs to select the quadrant.
The y argument comes first.
For zero y and positive x or positive zero x, returns zero with y's sign.
For zero y and negative x or negative zero x, returns pi with y's sign.
[(math/round (* 1000000000000.0 (math/atan2 0 1))) (math/round (* 1000000000000.0 (math/atan2 1 1))) (math/round (* 1000000000000.0 (math/atan2 1 -1))) (math/round (* 1000000000000.0 (math/atan2 -1 -1))) (math/round (* 1000000000000.0 (math/atan2 -1 1)))]
(math/round (* 1000000000000.0 (math/atan2 0 1))) (math/round (* 1000000000000.0 (math/atan2 1 1))) (math/round (* 1000000000000.0 (math/atan2 1 -1))) (math/round (* 1000000000000.0 (math/atan2 -1 -1))) (math/round (* 1000000000000.0 (math/atan2 -1 1)))
0 785398163397 2356194490192 -2356194490192 -785398163397
[(math/round (* 1000000000000.0 (math/atan2 0.0 (- 0.0)))) (math/round (* 1000000000000.0 (math/atan2 (- 0.0) (- 0.0)))) (math/copy-sign 1.0 (math/atan2 (- 0.0) 0.0))]
(math/round (* 1000000000000.0 (math/atan2 0.0 (- 0.0)))) (math/round (* 1000000000000.0 (math/atan2 (- 0.0) (- 0.0)))) (math/copy-sign 1.0 (math/atan2 (- 0.0) 0.0))
3141592653590 -3141592653590 -1.0
19.1.29. math/sinh
Function(math/sinh n) → float
Returns the hyperbolic sine of n.
[(math/round (* 1000000000000.0 (math/sinh -1))) (math/round (* 1000000000000.0 (math/sinh 0))) (math/round (* 1000000000000.0 (math/sinh 1)))]
(math/round (* 1000000000000.0 (math/sinh -1))) (math/round (* 1000000000000.0 (math/sinh 0))) (math/round (* 1000000000000.0 (math/sinh 1)))
-1175201193644 0 1175201193644
19.1.30. math/cosh
Function(math/cosh n) → float
Returns the hyperbolic cosine of n.
[(math/round (* 1000000000000.0 (math/cosh -1))) (math/round (* 1000000000000.0 (math/cosh 0))) (math/round (* 1000000000000.0 (math/cosh 1)))]
(math/round (* 1000000000000.0 (math/cosh -1))) (math/round (* 1000000000000.0 (math/cosh 0))) (math/round (* 1000000000000.0 (math/cosh 1)))
1543080634815 1000000000000 1543080634815
19.1.31. math/tanh
Function(math/tanh n) → float
Returns the hyperbolic tangent of n.
[(math/round (* 1000000000000.0 (math/tanh -1))) (math/round (* 1000000000000.0 (math/tanh 0))) (math/round (* 1000000000000.0 (math/tanh 1)))]
(math/round (* 1000000000000.0 (math/tanh -1))) (math/round (* 1000000000000.0 (math/tanh 0))) (math/round (* 1000000000000.0 (math/tanh 1)))
-761594155956 0 761594155956
19.1.32. math/asinh
Function(math/asinh n) → float
Returns the inverse hyperbolic sine of n.
[(math/round (* 1000000000000.0 (math/asinh -1))) (math/round (* 1000000000000.0 (math/asinh 0))) (math/round (* 1000000000000.0 (math/asinh 1)))]
(math/round (* 1000000000000.0 (math/asinh -1))) (math/round (* 1000000000000.0 (math/asinh 0))) (math/round (* 1000000000000.0 (math/asinh 1)))
-881373587020 0 881373587020
19.1.33. math/acosh
Function(math/acosh n) → float
Returns the nonnegative inverse hyperbolic cosine of n.
An n less than 1 produces #err <float overflow>.
[(math/round (* 1000000000000.0 (math/acosh 1))) (math/round (* 1000000000000.0 (math/acosh 2))) (math/round (* 1000000000000.0 (math/acosh 3)))]
(math/round (* 1000000000000.0 (math/acosh 1))) (math/round (* 1000000000000.0 (math/acosh 2))) (math/round (* 1000000000000.0 (math/acosh 3)))
0 1316957896925 1762747174039
19.1.34. math/atanh
Function(math/atanh n) → float
Returns the inverse hyperbolic tangent of n.
An n outside the open interval from -1 to 1 produces #err <float overflow>.
[(math/round (* 1000000000000.0 (math/atanh -0.5))) (math/round (* 1000000000000.0 (math/atanh 0))) (math/round (* 1000000000000.0 (math/atanh 0.5)))]
(math/round (* 1000000000000.0 (math/atanh -0.5))) (math/round (* 1000000000000.0 (math/atanh 0))) (math/round (* 1000000000000.0 (math/atanh 0.5)))
-549306144334 0 549306144334
19.1.35. math/signum
Function(math/signum n) → float
Returns -1.0 for negative n, 1.0 for positive n, or zero with n's sign for zero.
[(math/signum -3) (math/signum 0) (math/signum 5.5) (math/signum (- 0.0))]
(math/signum -3) (math/signum 0) (math/signum 5.5) (math/signum (- 0.0))
-1.0 0.0 1.0 0.0
19.1.36. math/copy-sign
Function(math/copy-sign magnitude sign) → float
Returns the absolute value of magnitude with the sign of sign, including the sign of floating-point zero.
[(math/copy-sign 3.5 -2) (math/copy-sign -3.5 2) (math/copy-sign 1.0 (math/copy-sign 0 -1)) (math/copy-sign 2 (- 0.0)) (math/copy-sign -2 0.0)]
(math/copy-sign 3.5 -2) (math/copy-sign -3.5 2) (math/copy-sign 1.0 (math/copy-sign 0 -1)) (math/copy-sign 2 (- 0.0)) (math/copy-sign -2 0.0)
#err <mismatch type> #err <mismatch type> -1.0 #err <mismatch type> #err <mismatch type>
19.1.37. math/floor-div
Function(math/floor-div n d) → integer
Returns the integer quotient of n divided by d, rounded toward negative infinity.
Before division, float arguments are converted to integers by truncating toward zero.
An out-of-range conversion or quotient produces #err <integer overflow>.
A zero divisor after conversion produces #err <division integer zero>.
[(math/floor-div 5 3) (math/floor-div -5 3) (math/floor-div 5 -3) (math/floor-div -5 -3) (math/floor-div 9223372036854775807 1) (math/floor-div -9223372036854775808 1) (math/floor-div 5.9 2.1) (math/floor-div -5.9 2.1)]
(math/floor-div 5 3) (math/floor-div -5 3) (math/floor-div 5 -3) (math/floor-div -5 -3) (math/floor-div 9223372036854775807 1) (math/floor-div -9223372036854775808 1) (math/floor-div 5.9 2.1) (math/floor-div -5.9 2.1)
1 -2 -2 1 9223372036854775807 -9223372036854775808 2 -3
19.1.38. math/floor-mod
Function(math/floor-mod n d) → integer
Returns the integer remainder of n divided by d using a quotient rounded toward negative infinity.
Before division, float arguments are converted to integers by truncating toward zero.
An out-of-range conversion produces #err <integer overflow>.
A zero divisor after conversion produces #err <division integer zero>.
A nonzero result has the divisor's sign and a smaller magnitude.
The quotient need not fit in an integer, so (math/floor-mod -9223372036854775808 -1) returns 0.
[(math/floor-mod 5 3) (math/floor-mod -5 3) (math/floor-mod 5 -3) (math/floor-mod -5 -3) (math/floor-mod -9223372036854775808 -1) (math/floor-mod 9223372036854775807 2) (math/floor-mod 5.9 2.1) (math/floor-mod -5.9 2.1)]
(math/floor-mod 5 3) (math/floor-mod -5 3) (math/floor-mod 5 -3) (math/floor-mod -5 -3) (math/floor-mod -9223372036854775808 -1) (math/floor-mod 9223372036854775807 2) (math/floor-mod 5.9 2.1) (math/floor-mod -5.9 2.1)
2 1 -1 -2 0 1 1 1
19.1.39. math/abs
Function(math/abs value) → value
Returns the absolute value, preserving integer or float kind. The absolute value of the minimum integer overflows and is an error. Durations are also accepted and return a duration; the minimum tick duration likewise overflows. UTC timestamps are rejected.
19.1.40. math/sign
Function(math/sign number) → integer
Returns integer -1, 0, or 1 according to the argument's sign.
19.1.41. math/lerp
Function(math/lerp start end fraction) → float
Returns start + (end - start) * fraction as a float. The fraction is not
clamped, so values outside zero through one extrapolate beyond the endpoints.
(math/lerp 10.0 20.0 0.5) (math/lerp 10.0 20.0 1.5) (math/lerp 10 20 0)
15.0 25.0 10.0
19.1.42. math/inverse-lerp
Function(math/inverse-lerp start end value) → float
Returns the fraction locating value between start and end, without
clamping. Equal endpoints are an error.
(math/inverse-lerp 10 20 15) (math/inverse-lerp 10 20 25) (math/inverse-lerp 10 20 10)
0.5 1.5 0.0
19.1.43. math/remap
Function(math/remap input-start input-end output-start output-end value) → float
Maps value from the input interval to the output interval, without clamping.
Equal input endpoints are an error. Reversed intervals are accepted.
(math/remap 0 10 100 200 5) (math/remap 0 10 100 200 15) (math/remap 10 0 100 200 5)
150.0 250.0 150.0
19.1.44. math/zero?
Function(math/zero? n) → boolean
Returns true if n is zero, otherwise false.
(math/zero? 0) (math/zero? 0.0) (math/zero? 3) (math/zero? -2) (math/zero? 0.5) (math/zero? -0.5) (math/zero? -9223372036854775808) (math/zero? 9223372036854775807)
true true false false false false false false
{boolean (math/zero? false) extra (math/zero? 0 0) list (math/zero? []) missing (math/zero?) null-input (math/zero? null) string (math/zero? "0")}
#cases [{output #err <mismatch type> select "string"} {output #err <mismatch type> select "null-input"} {output #err <mismatch type> select "boolean"} {output #err <mismatch type> select "list"} {output #err <arity mismatch> select "missing"} {output #err <arity mismatch> select "extra"}]
19.1.45. math/odd?
Function(math/odd? n) → boolean
Returns true if integer n is odd, otherwise false.
(math/odd? 1) (math/odd? 2) (math/odd? -3) (math/odd? 0) (math/odd? -2) (math/odd? -9223372036854775808) (math/odd? 9223372036854775807)
true false true false false false true
{boolean (math/odd? true) extra (math/odd? 1 3) float (math/odd? 1.0) fractional (math/odd? 1.5) missing (math/odd?) null-input (math/odd? null) string (math/odd? "1")}
#cases [{output #err <mismatch type> select "float"} {output #err <mismatch type> select "fractional"} {output #err <mismatch type> select "string"} {output #err <mismatch type> select "null-input"} {output #err <mismatch type> select "boolean"} {output #err <arity mismatch> select "missing"} {output #err <arity mismatch> select "extra"}]
19.1.46. math/even?
Function(math/even? n) → boolean
Returns true if integer n is even, otherwise false.
(math/even? 0) (math/even? 2) (math/even? -3) (math/even? 1) (math/even? -2) (math/even? -9223372036854775808) (math/even? 9223372036854775807)
true true false false true true false
{boolean (math/even? false) extra (math/even? 2 4) float (math/even? 2.0) fractional (math/even? 2.5) missing (math/even?) null-input (math/even? null) string (math/even? "2")}
#cases [{output #err <mismatch type> select "float"} {output #err <mismatch type> select "fractional"} {output #err <mismatch type> select "string"} {output #err <mismatch type> select "null-input"} {output #err <mismatch type> select "boolean"} {output #err <arity mismatch> select "missing"} {output #err <arity mismatch> select "extra"}]
19.1.47. math/min
Function(math/min value more*) → value
Returns the least argument. Requires at least one argument, and all arguments must have the same numeric or temporal kind. Integer and temporal comparisons retain full 64-bit precision.
(math/min 3 1 2) (math/min 1.5 0.5) (math/min 9007199254740994 9007199254740993)
1 0.5 9007199254740993
19.1.48. math/max
Function(math/max value more*) → value
Returns the greatest argument. Requires at least one argument, and all arguments must have the same numeric or temporal kind. Integer and temporal comparisons retain full 64-bit precision.
(math/max 3 1 2) (math/max 1.5 0.5) (math/max -9007199254740994 -9007199254740993)
3 1.5 -9007199254740993
19.1.49. math/clamp
Function(math/clamp value low high) → value
Returns value limited to the inclusive interval from low through high.
All three arguments must have the same numeric or temporal kind, and low
must not exceed high.
19.2. Packed math values
Packed math values are immutable arrays of finite binary64 components, the
same numbers as a Float. Each shape is its own value kind. Its kind predicate
is its tag name with ?, such as v3? or m44?, and a schema uses that
predicate. A #v4 value is not a #quat value. DUST, RON, and EDN use these tags:
| Tag | Components | Value |
|---|---|---|
#v2 |
2 | two-dimensional vector |
#v3 |
3 | three-dimensional vector |
#v4 |
4 | four-dimensional vector |
#m22 |
4 | 2 by 2 matrix |
#m33 |
9 | 3 by 3 matrix |
#m44 |
16 | 4 by 4 matrix |
#quat |
4 | quaternion |
#aabb |
6 | minimum and maximum three-dimensional points |
#ray |
6 | origin and direction |
#sphere |
4 | center and radius |
#plane |
4 | normal and distance |
#triangle |
9 | three three-dimensional points |
#frustum |
24 | six planes |
A Float component keeps its exact value, including -0.0, and an Integer
component becomes the nearest Float. No component or operation rounds to
binary32. As for Floats, -0.0 and 0.0 are equal, order together, and hash
together. An operation whose result or intermediate value passes the Float
range produces #err <float overflow>.
19.2.1. Conventions
- Matrix layout
- A matrix is row-major: its tag lists rows, and its
components are stored row after row. A matrix multiplies a column vector,
so
(* m v)ism vand(* a b)appliesbfirst, thena. A translation is in the last column of a#m44. - Coordinate basis
- Space is right-handed and Y-up.
:math/vectors/rightis +X,:math/vectors/upis +Y, and:math/vectors/forwardis −Z, as in OpenGL and glTF cameras. (cljgame is Z-up with +Y forward; convert at that boundary.) - Angle units
- Angles are radians, as for
math/sin. - Quaternions
- A
#quatlistsx y z w: the vector part, then the scalar part.(* q1 q2)is the Hamilton product q1 q2, which appliesq2first andq1second, as matrices do.(* q v)rotates the#v3vby a unit quaternionq, so(* q1 q2 v)is(* q1 (* q2 v)). - Planes
- A
#planewith normalnand distancedholds the pointspwheren · p + d = 0. Its positive side, wheren · p + d > 0, is the inside of a#frustum. - Contact
- Geometry boundary contact and tangency count as intersections.
- Tolerance
- Two computations of one result, such as the scalar and batch kernels, or a kernel and its binary64 reference, agree when each component satisfies |a − b| ≤ 1e-12 · max(1, |a|, |b|): a relative tolerance at magnitudes above one and an absolute one below. Operators and named operations give exact binary64 results of their formulas; they do not round to the tolerance.
(* #m22 [[0 -1] [1 0]] #v2 [1 0]) (* #m44 [[1 0 0 5] [0 1 0 6] [0 0 1 7] [0 0 0 1]] #v4 [1 1 1 1]) (* #m44 [[1 0 0 5] [0 1 0 6] [0 0 1 7] [0 0 0 1]] #v4 [1 1 1 0]) (* #quat [0 0.7071067811865476 0 0.7071067811865476] :math/vectors/forward) (let [yaw #quat [0 0.7071067811865476 0 0.7071067811865476] roll #quat [0 0 0.7071067811865476 0.7071067811865476]] (* yaw roll :math/vectors/right)) (let [yaw #quat [0 0.7071067811865476 0 0.7071067811865476] roll #quat [0 0 0.7071067811865476 0.7071067811865476]] (* roll yaw :math/vectors/right)) (math/intersects? #plane [[0 1 0] -2] #sphere [[0 2 0] 0.5]) (math/intersects? #ray [[0 5 0] [0 -1 0]] #plane [[0 1 0] -2])
(* #m22 [[0.0 -1.0] [1.0 0.0]] #v2 [1.0 0.0]) (* #m44 [[1.0 0.0 0.0 5.0] [0.0 1.0 0.0 6.0] [0.0 0.0 1.0 7.0] [0.0 0.0 0.0 1.0]] #v4 [1.0 1.0 1.0 1.0]) (* #m44 [[1.0 0.0 0.0 5.0] [0.0 1.0 0.0 6.0] [0.0 0.0 1.0 7.0] [0.0 0.0 0.0 1.0]] #v4 [1.0 1.0 1.0 0.0]) (* #quat [0.0 0.7071067811865476 0.0 0.7071067811865476] :math/vectors/forward) (let [yaw #quat [0.0 0.7071067811865476 0.0 0.7071067811865476] roll #quat [0.0 0.0 0.7071067811865476 0.7071067811865476]] (* yaw roll :math/vectors/right)) (let [yaw #quat [0.0 0.7071067811865476 0.0 0.7071067811865476] roll #quat [0.0 0.0 0.7071067811865476 0.7071067811865476]] (* roll yaw :math/vectors/right)) (math/intersects? #plane [[0.0 1.0 0.0] -2.0] #sphere [[0.0 2.0 0.0] 0.5]) (math/intersects? #ray [[0.0 5.0 0.0] [0.0 -1.0 0.0]] #plane [[0.0 1.0 0.0] -2.0])
#v2 [0.0 1.0] #v4 [6.0 7.0 8.0 1.0] #v4 [1.0 1.0 1.0 0.0] #v3 [-1.0000000000000002 0.0 2.220446049250313e-16] #v3 [-4.440892098500626e-16 1.0000000000000004 0.0] #v3 [-4.440892098500626e-16 0.0 -1.0000000000000004] true true
19.2.2. Operators
The arithmetic operators +, -, * and / take packed values. As for
numbers, they reduce left to right, one pair at a time, so
(* 2 3 v) is (* (* 2 3) v). A number operand can be an Integer or a
Float; it becomes a Float.
| Operands | Operators | Result |
|---|---|---|
| two vectors of one width | + - * / |
componentwise vector |
| vector and number, either order | * |
scaled vector |
| vector and number | / |
vector divided by the number |
| two matrices of one size | + - |
componentwise matrix |
| two matrices of one size | * |
matrix product |
| matrix and vector of its size | * |
column vector product |
| two quaternions | * |
Hamilton product |
quaternion and #v3 |
* |
rotated vector |
| one vector or matrix | - |
negation |
Other pairs give #err <mismatch type>: a vector and a number with + or
-, a number divided by a vector, a matrix and a number, quaternions with +
or -, geometry values, and #m44 with #v3. Points and directions
transform differently, so a #m44 transforms a #v3 by name, as with
math/vectors/transform. A zero divisor gives
#err <division float zero>.
(+ #v3 [1 2 3] #v3 [10 20 30] #v3 [100 200 300]) (- #v2 [1 2] #v2 [0.5 0.5]) (- #v3 [1 -2 0]) (* #v3 [1 2 3] 2) (* 0.5 #v3 [1 2 3]) (* 2 3 #v2 [1 1]) (* #v4 [1 2 3 4] #v4 [2 2 2 2]) (/ #v3 [1 2 3] 2) (/ #v3 [1 2 3] #v3 [2 4 8]) (+ #m22 [[1 2] [3 4]] #m22 [[1 1] [1 1]]) (- #m33 [[1 2 3] [4 5 6] [7 8 9]] #m33 [[1 0 0] [0 1 0] [0 0 1]]) (* #m22 [[1 2] [3 4]] #m22 [[5 6] [7 8]]) (* #m22 [[1 2] [3 4]] #v2 [1 1]) (* #m44 [[1 0 0 10] [0 1 0 20] [0 0 1 30] [0 0 0 1]] #v4 [1 2 3 1]) (* #quat [0 0 1 0] #v3 [1 2 3]) (* #quat [1 0 0 0] #quat [0 1 0 0]) (* #quat [0 1 0 0] #quat [1 0 0 0]) (* #quat [0 0 0 1] #quat [0 0 1 0] #v3 [1 0 0]) (* #v3 [1e300 0 0] 1e10)
(+ #v3 [1.0 2.0 3.0] #v3 [10.0 20.0 30.0] #v3 [100.0 200.0 300.0]) (- #v2 [1.0 2.0] #v2 [0.5 0.5]) (- #v3 [1.0 -2.0 0.0]) (* #v3 [1.0 2.0 3.0] 2) (* 0.5 #v3 [1.0 2.0 3.0]) (* 2 3 #v2 [1.0 1.0]) (* #v4 [1.0 2.0 3.0 4.0] #v4 [2.0 2.0 2.0 2.0]) (/ #v3 [1.0 2.0 3.0] 2) (/ #v3 [1.0 2.0 3.0] #v3 [2.0 4.0 8.0]) (+ #m22 [[1.0 2.0] [3.0 4.0]] #m22 [[1.0 1.0] [1.0 1.0]]) (- #m33 [[1.0 2.0 3.0] [4.0 5.0 6.0] [7.0 8.0 9.0]] #m33 [[1.0 0.0 0.0] [0.0 1.0 0.0] [0.0 0.0 1.0]]) (* #m22 [[1.0 2.0] [3.0 4.0]] #m22 [[5.0 6.0] [7.0 8.0]]) (* #m22 [[1.0 2.0] [3.0 4.0]] #v2 [1.0 1.0]) (* #m44 [[1.0 0.0 0.0 10.0] [0.0 1.0 0.0 20.0] [0.0 0.0 1.0 30.0] [0.0 0.0 0.0 1.0]] #v4 [1.0 2.0 3.0 1.0]) (* #quat [0.0 0.0 1.0 0.0] #v3 [1.0 2.0 3.0]) (* #quat [1.0 0.0 0.0 0.0] #quat [0.0 1.0 0.0 0.0]) (* #quat [0.0 1.0 0.0 0.0] #quat [1.0 0.0 0.0 0.0]) (* #quat [0.0 0.0 0.0 1.0] #quat [0.0 0.0 1.0 0.0] #v3 [1.0 0.0 0.0]) (* #v3 [1e+300 0.0 0.0] 10000000000.0)
#v3 [111.0 222.0 333.0] #v2 [0.5 1.5] #v3 [-1.0 2.0 -0.0] #v3 [2.0 4.0 6.0] #v3 [0.5 1.0 1.5] #v2 [6.0 6.0] #v4 [2.0 4.0 6.0 8.0] #v3 [0.5 1.0 1.5] #v3 [0.5 0.5 0.375] #m22 [[2.0 3.0] [4.0 5.0]] #m33 [[0.0 2.0 3.0] [4.0 4.0 6.0] [7.0 8.0 8.0]] #m22 [[19.0 22.0] [43.0 50.0]] #v2 [3.0 7.0] #v4 [11.0 22.0 33.0 1.0] #v3 [-1.0 -2.0 3.0] #quat [0.0 0.0 1.0 0.0] #quat [0.0 0.0 -1.0 0.0] #v3 [-1.0 0.0 0.0] #err {<float overflow> message "floating-point overflow"}
(+ #v3 [1 2 3] 1) (+ #v2 [1 2] #v3 [1 2 3]) (- 1 #v2 [1 2]) (/ 1 #v2 [1 2]) (/ #v2 [1 2] 0) (/ #v2 [1 2] #v2 [1 0]) (* #m22 [[1 2] [3 4]] 2) (* #m44 [[1 0 0 0] [0 1 0 0] [0 0 1 0] [0 0 0 1]] #v3 [1 2 3]) (* #m33 [[1 0 0] [0 1 0] [0 0 1]] #m22 [[1 0] [0 1]]) (+ #quat [0 0 0 1] #quat [0 0 0 1]) (- #quat [0 0 0 1]) (* #aabb [[0 0 0] [1 1 1]] 2) (+ #v2 [1 2] "1") (* #v2 [1e300 1] #v2 [1e300 1]) (* #aabb [[0 0 0] [1 1 1]]) (* #ray [[0 0 0] [1 0 0]]) (* #sphere [[0 0 0] 1]) (* #plane [[0 1 0] 0]) (* #triangle [[0 0 0] [1 0 0] [0 1 0]]) (* #frustum [[1 0 0 1] [-1 0 0 1] [0 1 0 1] [0 -1 0 1] [0 0 1 1] [0 0 -1 1]])
(+ #v3 [1.0 2.0 3.0] 1) (+ #v2 [1.0 2.0] #v3 [1.0 2.0 3.0]) (- 1 #v2 [1.0 2.0]) (/ 1 #v2 [1.0 2.0]) (/ #v2 [1.0 2.0] 0) (/ #v2 [1.0 2.0] #v2 [1.0 0.0]) (* #m22 [[1.0 2.0] [3.0 4.0]] 2) (* #m44 [[1.0 0.0 0.0 0.0] [0.0 1.0 0.0 0.0] [0.0 0.0 1.0 0.0] [0.0 0.0 0.0 1.0]] #v3 [1.0 2.0 3.0]) (* #m33 [[1.0 0.0 0.0] [0.0 1.0 0.0] [0.0 0.0 1.0]] #m22 [[1.0 0.0] [0.0 1.0]]) (+ #quat [0.0 0.0 0.0 1.0] #quat [0.0 0.0 0.0 1.0]) (- #quat [0.0 0.0 0.0 1.0]) (* #aabb [[0.0 0.0 0.0] [1.0 1.0 1.0]] 2) (+ #v2 [1.0 2.0] "1") (* #v2 [1e+300 1.0] #v2 [1e+300 1.0]) (* #aabb [[0.0 0.0 0.0] [1.0 1.0 1.0]]) (* #ray [[0.0 0.0 0.0] [1.0 0.0 0.0]]) (* #sphere [[0.0 0.0 0.0] 1.0]) (* #plane [[0.0 1.0 0.0] 0.0]) (* #triangle [[0.0 0.0 0.0] [1.0 0.0 0.0] [0.0 1.0 0.0]]) (* #frustum [[1.0 0.0 0.0 1.0] [-1.0 0.0 0.0 1.0] [0.0 1.0 0.0 1.0] [0.0 -1.0 0.0 1.0] [0.0 0.0 1.0 1.0] [0.0 0.0 -1.0 1.0]])
#err {<mismatch type> message "packed + requires two vectors or two matrices of one shape"} #err {<mismatch type> message "packed + requires two vectors or two matrices of one shape"} #err {<mismatch type> message "packed - requires two vectors or two matrices of one shape"} #err {<mismatch type> message "packed / requires a vector and a vector of its width or a number"} #err {<division float zero> message "division by zero"} #err {<division float zero> message "division by zero"} #err {<mismatch type> message "unsupported packed * operands; transform points and directions by name"} #err {<mismatch type> message "unsupported packed * operands; transform points and directions by name"} #err {<mismatch type> message "unsupported packed * operands; transform points and directions by name"} #err {<mismatch type> message "packed + requires two vectors or two matrices of one shape"} #err {<mismatch type> message "unsupported packed - operand"} #err {<mismatch type> message "unsupported packed * operands; transform points and directions by name"} #err {<mismatch type> message "packed + requires two vectors or two matrices of one shape"} #err {<float overflow> message "floating-point overflow"} #err {<mismatch type> message "unsupported packed * operand"} #err {<mismatch type> message "unsupported packed * operand"} #err {<mismatch type> message "unsupported packed * operand"} #err {<mismatch type> message "unsupported packed * operand"} #err {<mismatch type> message "unsupported packed * operand"} #err {<mismatch type> message "unsupported packed * operand"}
19.2.3. Destructuring and lookup
A list binding pattern in let, fn or for selects
a packed value's parts, as its tag writes them:
| Value | Parts |
|---|---|
#v2, #v3, #v4 |
components |
#quat |
x y z w |
#m22, #m33, #m44 |
row vectors |
#aabb |
minimum and maximum #v3 |
#ray |
origin and direction #v3 |
#sphere |
center #v3 and radius |
#plane |
normal #v3 and distance |
#triangle |
three #v3 points |
#frustum |
six #plane values |
A component is a Float. Destructuring reads components directly and makes no
intermediate list. A nested pattern reads the components of a packed part
without making that part: [[x] [_ _ z]] over an AABB makes no #v3. Only a
packed part bound to a name becomes its own value. Short and long patterns
follow the list rules: a missing part binds null, extra parts are ignored,
and a ... rest capture is a list of the remaining parts. A map pattern over
a packed value is #err <mismatch type>.
(let [[x y z] #v3 [1 2 3]] (+ x y z)) (let [[x y z] #v3 [1 2 3]] [x y z]) (let [[x y z w] #quat [0 0 0 1]] [x y z w]) (let [[r0 r1] #m22 [[1 2] [3 4]]] [r0 r1]) (let [[[a b] [c d]] #m22 [[1 2] [3 4]]] [a b c d]) (let [[minimum maximum] #aabb [[0 0 0] [1 2 3]]] [minimum maximum]) (let [[[x] [_ _ z]] #aabb [[7 0 0] [1 2 3]]] [x z]) (let [[origin direction] #ray [[0 0 0] [1 0 0]]] [origin direction]) (let [[center radius] #sphere [[1 2 3] 4]] [center radius]) (let [[normal distance] #plane [[0 1 0] -2]] [normal distance]) (let [[a b c] #triangle [[0 0 0] [1 0 0] [0 1 0]]] c) (let [[near] #frustum [[0 0 1 1] [0 0 -1 1] [1 0 0 1] [-1 0 0 1] [0 1 0 1] [0 -1 0 1]]] near) (let [[x ... more] #v4 [1 2 3 4]] [x more]) (let [[x y z w] #v3 [1 2 3]] [z w]) (let [[x] null] x) ((fn [[x y]] (+ x y)) #v2 [1.5 2]) (for [[x y] [#v2 [1 2] #v2 [3 4]]] (* x y))
(let [[x y z] #v3 [1.0 2.0 3.0]] (+ x y z)) (let [[x y z] #v3 [1.0 2.0 3.0]] [x y z]) (let [[x y z w] #quat [0.0 0.0 0.0 1.0]] [x y z w]) (let [[r0 r1] #m22 [[1.0 2.0] [3.0 4.0]]] [r0 r1]) (let [[[a b] [c d]] #m22 [[1.0 2.0] [3.0 4.0]]] [a b c d]) (let [[minimum maximum] #aabb [[0.0 0.0 0.0] [1.0 2.0 3.0]]] [minimum maximum]) (let [[[x] [_ _ z]] #aabb [[7.0 0.0 0.0] [1.0 2.0 3.0]]] [x z]) (let [[origin direction] #ray [[0.0 0.0 0.0] [1.0 0.0 0.0]]] [origin direction]) (let [[center radius] #sphere [[1.0 2.0 3.0] 4.0]] [center radius]) (let [[normal distance] #plane [[0.0 1.0 0.0] -2.0]] [normal distance]) (let [[a b c] #triangle [[0.0 0.0 0.0] [1.0 0.0 0.0] [0.0 1.0 0.0]]] c) (let [[near] #frustum [[0.0 0.0 1.0 1.0] [0.0 0.0 -1.0 1.0] [1.0 0.0 0.0 1.0] [-1.0 0.0 0.0 1.0] [0.0 1.0 0.0 1.0] [0.0 -1.0 0.0 1.0]]] near) (let [[x ... more] #v4 [1.0 2.0 3.0 4.0]] [x more]) (let [[x y z w] #v3 [1.0 2.0 3.0]] [z w]) (let [[x] null] x) ((fn [[x y]] (+ x y)) #v2 [1.5 2.0]) (for [[x y] [#v2 [1.0 2.0] #v2 [3.0 4.0]]] (* x y))
6.0 [1.0 2.0 3.0] [0.0 0.0 0.0 1.0] [#v2 [1.0 2.0] #v2 [3.0 4.0]] [1.0 2.0 3.0 4.0] [#v3 [0.0 0.0 0.0] #v3 [1.0 2.0 3.0]] [7.0 3.0] [#v3 [0.0 0.0 0.0] #v3 [1.0 0.0 0.0]] [#v3 [1.0 2.0 3.0] 4.0] [#v3 [0.0 1.0 0.0] -2.0] #v3 [0.0 1.0 0.0] #plane [[0.0 0.0 1.0] 1.0] [1.0 [2.0 3.0 4.0]] [3.0 null] null 3.5 [2.0 12.0]
(let [{x a} #v3 [1 2 3]] a)
(let [{x a} #v3 [1.0 2.0 3.0]] a)
#err {<mismatch type> message "map destructuring requires a map or null"}
(let [[x [y]] #v3 [1 2 3]] y)
(let [[x [y]] #v3 [1.0 2.0 3.0]] y)
#err {<mismatch type> message "list destructuring requires a list, a packed math value, or null"}
For a computed index, get, lists/nth and a packed value in
callee position select the same parts. A path reads through nested parts,
and a string swizzles a vector (see
math/vectors/swizzle).
(get #v3 [4 5 6] 1) (get #v3 [4 5 6] -1) (get #v3 [4 5 6] 3) (get #v3 [4 5 6] 3 0.0) (get #m33 [[1 2 3] [4 5 6] [7 8 9]] 1) (get #m33 [[1 2 3] [4 5 6] [7 8 9]] [2 0]) (get #sphere [[1 2 3] 4] 1) (lists/nth #v3 [4 5 6] 2) (let [v #v3 [4 5 6]] (v 0)) (let [i 2] (#v3 [4 5 6] i)) (get #v3 [4 5 6] "zy") (lists/nth #v3 [4 5 6] 3) (get #m22 [[1 2] [3 4]] "x")
(get #v3 [4.0 5.0 6.0] 1) (get #v3 [4.0 5.0 6.0] -1) (get #v3 [4.0 5.0 6.0] 3) (get #v3 [4.0 5.0 6.0] 3 0.0) (get #m33 [[1.0 2.0 3.0] [4.0 5.0 6.0] [7.0 8.0 9.0]] 1) (get #m33 [[1.0 2.0 3.0] [4.0 5.0 6.0] [7.0 8.0 9.0]] [2 0]) (get #sphere [[1.0 2.0 3.0] 4.0] 1) (lists/nth #v3 [4.0 5.0 6.0] 2) (let [v #v3 [4.0 5.0 6.0]] (v 0)) (let [i 2] (#v3 [4.0 5.0 6.0] i)) (get #v3 [4.0 5.0 6.0] "zy") (lists/nth #v3 [4.0 5.0 6.0] 3) (get #m22 [[1.0 2.0] [3.0 4.0]] "x")
5.0 6.0 null 0.0 #v3 [4.0 5.0 6.0] 7.0 4.0 6.0 4.0 6.0 #v2 [6.0 5.0] #err {<invalid value> message "index out of range"} #err {<mismatch type> message "a swizzle requires a #v2, #v3, or #v4 vector"}
19.2.4. Packed vectors
A packed vector holds any number of lanes, also none. A #vf value holds
finite binary64 lanes, the same numbers as a Float. A #vi value holds int64
lanes, the same numbers as an Integer. Use them for long vectors, such as text
embeddings of 384 to 1,536 numbers. The kind predicates vf? and vi? are
their schemas.
| Tag | Lanes | Lane value |
|---|---|---|
#vf |
any count | Float; an Integer lane becomes the nearest Float |
#vi |
any count | Integer; a Float lane is an error |
Each lane uses 8 bytes, in memory and in storage. A #vf of 1,536 lanes uses
12,288 bytes for its lanes. A list of the same 1,536 Floats uses 24,592 bytes
in memory. One cell holds at most 536,870,911 lanes, which is the cell's byte
length limit divided by 8.
count gives the number of lanes. get, lists/nth, a call of
the vector, and a list binding pattern select lanes as for a list. Two vectors
are equal when they have the same tag, the same length and equal lanes. A
-0.0 lane equals 0.0. Vectors of one tag order lane by lane, and a shorter
vector that is a prefix of a longer one comes first. A #vf is never equal to
a #vi or a list.
#vf [0.12 -0.03 0.88] #vf [1 2 3] #vi [1 -2 9007199254740993] #vf [] (count #vf [0.12 -0.03 0.88]) (count #vi []) (= #vf [1.0 -0.0] #vf [1.0 0.0]) (= #vf [1.0 2.0] #vf [1.0 2.0 3.0]) (= #vi [1] #vf [1.0]) (sort [#vf [2.0] #vf [1.0 5.0] #vf [1.0]]) (sort [#vi [3] #vi [-9223372036854775808 1] #vi []]) ((fn [] #vf [0.5 1.5]))
#vf [0.12 -0.03 0.88] #vf [1.0 2.0 3.0] #vi [1 -2 9007199254740993] #vf [] (count #vf [0.12 -0.03 0.88]) (count #vi []) (= #vf [1.0 -0.0] #vf [1.0 0.0]) (= #vf [1.0 2.0] #vf [1.0 2.0 3.0]) (= #vi [1] #vf [1.0]) (sort [#vf [2.0] #vf [1.0 5.0] #vf [1.0]]) (sort [#vi [3] #vi [-9223372036854775808 1] #vi []]) ((fn [] #vf [0.5 1.5]))
#vf [0.12 -0.03 0.88] #vf [1.0 2.0 3.0] #vi [1 -2 9007199254740993] #vf [] 3 0 true false #err {<mismatch type> message "equality requires matching types"} [#vf [1.0] #vf [1.0 5.0] #vf [2.0]] [#vi [] #vi [-9223372036854775808 1] #vi [3]] #vf [0.5 1.5]
(get #vf [0.5 1.5 2.5] 1) (#vi [7 8 9] 2) (lists/nth #vf [0.5 1.5] 0) (get #vi [7 8 9] 5) (get #vf [0.5 1.5] -1) (let [[x y ... rest] #vf [1.0 2.0 3.0 4.0]] [x y rest]) (let [[a b c] #vi [1 2]] [a b c])
1.5 9 0.5 null 1.5 [1.0 2.0 [3.0 4.0]] [1 2 null]
The arithmetic operators take packed vectors:
| Operands | Operators | Result |
|---|---|---|
two #vf of one length |
+ - * / |
lane by lane #vf |
two #vi of one length |
+ - * |
lane by lane #vi |
two #vi of one length |
/ |
lane by lane #vf |
#vf and a number, either order |
* |
scaled #vf |
#vf and a number |
/ |
#vf divided by the number |
#vi and an Integer, either order |
* |
scaled #vi |
#vi and an Integer |
/ |
#vf divided by the Integer |
| one vector | - |
negation |
As for Integers, a #vi result that passes the int64 range gives
#err <integer overflow>. A #vi quotient is a #vf, as an Integer quotient
is a Float. Two vectors of different lengths give #err <invalid value>.
These operands give #err <mismatch type>: a #vf with a #vi, a vector with
a fixed packed value such as #v3, a #vi with a Float, a vector and a number
with + or -, and a number divided by a vector.
(+ #vf [1.0 2.0 3.0] #vf [0.5 0.5 0.5]) (- #vf [1.0 2.0] #vf [0.5 2.0]) (* #vf [1.0 2.0] #vf [3.0 4.0]) (/ #vf [1.0 2.0] #vf [4.0 8.0]) (* 2 #vf [0.5 -0.25]) (/ #vf [1.0 3.0] 2) (- #vf [1.0 -2.0]) (+ #vi [1 2] #vi [10 20] #vi [100 200]) (* #vi [1 -2] 3) (/ #vi [1 3] 2) (- #vi [5 -6])
#vf [1.5 2.5 3.5] #vf [0.5 0.0] #vf [3.0 8.0] #vf [0.25 0.25] #vf [1.0 -0.5] #vf [0.5 1.5] #vf [-1.0 2.0] #vi [111 222] #vi [3 -6] #vf [0.5 1.5] #vi [-5 6]
(+ #vf [1.0 2.0] #vf [1.0]) (+ #vf [1.0] #vi [1]) (* #vi [1] 1.5) (+ #vf [1.0] 1) (+ #vf [1.0 2.0] #v2 [1.0 2.0]) (/ 2 #vf [1.0]) (/ #vf [1.0] 0) (/ #vi [1] 0) (* #vi [9223372036854775807] 2) (* #vf [1e+300] 10000000000.0)
#err {<invalid value> message "packed vectors must have the same length"} #err {<mismatch type> message "packed vector operands must both be #vf or both be #vi"} #err {<mismatch type> message "a #vi combines with Integers only"} #err {<mismatch type> message "packed + requires two vectors of one length"} #err {<mismatch type> message "a packed vector does not combine with a fixed packed value"} #err {<mismatch type> message "a number cannot be divided by a packed vector"} #err {<division float zero> message "division by zero"} #err {<division integer zero> message "division by zero"} #err {<integer overflow> message "integer overflow"} #err {<float overflow> message "floating-point overflow"}
19.2.5. Constants
These constants are packed values, not functions:
| Constant | Value |
|---|---|
:math/vectors/v2-zero, :math/vectors/v3-zero, :math/vectors/v4-zero |
zero vectors |
:math/vectors/v2-one, :math/vectors/v3-one, :math/vectors/v4-one |
vectors of ones |
:math/vectors/right |
#v3 [1.0 0.0 0.0] |
:math/vectors/up |
#v3 [0.0 1.0 0.0] |
:math/vectors/forward |
#v3 [0.0 0.0 -1.0] |
:math/quaternions/identity |
#quat [0.0 0.0 0.0 1.0] |
:math/matrices/identity-22, :math/matrices/identity-33, :math/matrices/identity-44 |
identity matrices |
:math/vectors/v2-zero :math/vectors/v3-zero :math/vectors/v4-zero :math/vectors/v2-one :math/vectors/v3-one :math/vectors/v4-one :math/vectors/right :math/vectors/up :math/vectors/forward :math/quaternions/identity :math/matrices/identity-22 :math/matrices/identity-33 :math/matrices/identity-44 (* :math/matrices/identity-33 #v3 [1 2 3])
:math/vectors/v2-zero :math/vectors/v3-zero :math/vectors/v4-zero :math/vectors/v2-one :math/vectors/v3-one :math/vectors/v4-one :math/vectors/right :math/vectors/up :math/vectors/forward :math/quaternions/identity :math/matrices/identity-22 :math/matrices/identity-33 :math/matrices/identity-44 (* :math/matrices/identity-33 #v3 [1.0 2.0 3.0])
#v2 [0.0 0.0] #v3 [0.0 0.0 0.0] #v4 [0.0 0.0 0.0 0.0] #v2 [1.0 1.0] #v3 [1.0 1.0 1.0] #v4 [1.0 1.0 1.0 1.0] #v3 [1.0 0.0 0.0] #v3 [0.0 1.0 0.0] #v3 [0.0 0.0 -1.0] #quat [0.0 0.0 0.0 1.0] #m22 [[1.0 0.0] [0.0 1.0]] #m33 [[1.0 0.0 0.0] [0.0 1.0 0.0] [0.0 0.0 1.0]] #m44 [[1.0 0.0 0.0 0.0] [0.0 1.0 0.0 0.0] [0.0 0.0 1.0 0.0] [0.0 0.0 0.0 1.0]] #v3 [1.0 2.0 3.0]
19.2.6. math/vectors/v2
Function(math/vectors/v2 x y) → v2
Returns #v2 [x y].
(math/vectors/v2 1 2) (math/vectors/v2 -0.5 1e3) (math/vectors/v2 -0.0 0) (math/vectors/v2 1 "2") (math/vectors/v2 1.7976931348623157e308 5e-324) (math/vectors/v2 1)
(math/vectors/v2 1 2) (math/vectors/v2 -0.5 1000.0) (math/vectors/v2 -0.0 0) (math/vectors/v2 1 "2") (math/vectors/v2 1.7976931348623157e+308 5e-324) (math/vectors/v2 1)
#v2 [1.0 2.0] #v2 [-0.5 1000.0] #v2 [-0.0 0.0] #err {<mismatch type> message "math components must be numbers"} #v2 [1.7976931348623157e+308 5e-324] #err {<arity mismatch> message "wrong number of arguments"}
19.2.7. math/vectors/v3
Function(math/vectors/v3 x y z) → v3
Returns #v3 [x y z].
(math/vectors/v3 1 2 3) (math/vectors/v3 0.1 0.2 0.3) (math/vectors/v3 16777217 0 0) (math/vectors/v3 1 2 null) (math/vectors/v3 1 2 3 4)
#v3 [1.0 2.0 3.0] #v3 [0.1 0.2 0.3] #v3 [16777217.0 0.0 0.0] #err {<mismatch type> message "math components must be numbers"} #err {<arity mismatch> message "wrong number of arguments"}
19.2.8. math/vectors/v4
Function(math/vectors/v4 x y z w) → v4
Returns #v4 [x y z w].
(math/vectors/v4 1 2 3 4) (math/vectors/v4 0 0 0 1) (= (math/vectors/v4 0 0 0 1) #quat [0 0 0 1]) (math/vectors/v4 1 2 3 true)
(math/vectors/v4 1 2 3 4) (math/vectors/v4 0 0 0 1) (= (math/vectors/v4 0 0 0 1) #quat [0.0 0.0 0.0 1.0]) (math/vectors/v4 1 2 3 true)
#v4 [1.0 2.0 3.0 4.0] #v4 [0.0 0.0 0.0 1.0] #err {<mismatch type> message "equality requires matching types"} #err {<mismatch type> message "math components must be numbers"}
19.2.9. math/matrices/m22
Function(math/matrices/m22 m00 m01 m10 m11) → m22
Returns a row-major 2 by 2 matrix.
(math/matrices/m22 1 2 3 4) (math/matrices/m22 1 0 0 1) (= (math/matrices/m22 1 2 3 4) #m22 [[1 2] [3 4]]) (math/matrices/m22 1 2 3)
(math/matrices/m22 1 2 3 4) (math/matrices/m22 1 0 0 1) (= (math/matrices/m22 1 2 3 4) #m22 [[1.0 2.0] [3.0 4.0]]) (math/matrices/m22 1 2 3)
#m22 [[1.0 2.0] [3.0 4.0]] #m22 [[1.0 0.0] [0.0 1.0]] true #err {<arity mismatch> message "wrong number of arguments"}
19.2.10. math/matrices/m33
Function(math/matrices/m33 m00 m01 m02 m10 m11 m12 m20 m21 m22) → m33
Returns a row-major 3 by 3 matrix.
(math/matrices/m33 1 2 3 4 5 6 7 8 9) (math/matrices/m33 1 0 0 0 1 0 0 0 1) (= (math/matrices/m33 1 0 0 0 1 0 0 0 1) #m33 [[1 0 0] [0 1 0] [0 0 1]]) (math/matrices/m33 1 0 0 0 1 0 0 0 "1")
(math/matrices/m33 1 2 3 4 5 6 7 8 9) (math/matrices/m33 1 0 0 0 1 0 0 0 1) (= (math/matrices/m33 1 0 0 0 1 0 0 0 1) #m33 [[1.0 0.0 0.0] [0.0 1.0 0.0] [0.0 0.0 1.0]]) (math/matrices/m33 1 0 0 0 1 0 0 0 "1")
#m33 [[1.0 2.0 3.0] [4.0 5.0 6.0] [7.0 8.0 9.0]] #m33 [[1.0 0.0 0.0] [0.0 1.0 0.0] [0.0 0.0 1.0]] true #err {<mismatch type> message "math components must be numbers"}
19.2.11. math/matrices/m44
Function(math/matrices/m44 m00 m01 m02 m03 m10 m11 m12 m13 m20 m21 m22 m23 m30 m31 m32 m33) → m44
Returns a row-major 4 by 4 matrix.
(math/matrices/m44 1 0 0 10 0 1 0 20 0 0 1 30 0 0 0 1) (= (math/matrices/m44 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1) #m44 [[1 0 0 0] [0 1 0 0] [0 0 1 0] [0 0 0 1]]) (math/matrices/m44 2 0 0 0 0 3 0 0 0 0 4 0 0 0 0 1) (math/matrices/m44 1 2 3)
(math/matrices/m44 1 0 0 10 0 1 0 20 0 0 1 30 0 0 0 1) (= (math/matrices/m44 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1) #m44 [[1.0 0.0 0.0 0.0] [0.0 1.0 0.0 0.0] [0.0 0.0 1.0 0.0] [0.0 0.0 0.0 1.0]]) (math/matrices/m44 2 0 0 0 0 3 0 0 0 0 4 0 0 0 0 1) (math/matrices/m44 1 2 3)
#m44 [[1.0 0.0 0.0 10.0] [0.0 1.0 0.0 20.0] [0.0 0.0 1.0 30.0] [0.0 0.0 0.0 1.0]] true #m44 [[2.0 0.0 0.0 0.0] [0.0 3.0 0.0 0.0] [0.0 0.0 4.0 0.0] [0.0 0.0 0.0 1.0]] #err {<arity mismatch> message "wrong number of arguments"}
19.2.12. math/quaternions/quaternion
Function(math/quaternions/quaternion x y z w) → quat
Returns #quat [x y z w].
(math/quaternions/quaternion 0 0 0 1) (math/quaternions/quaternion 0.5 0.5 0.5 0.5) (= (math/quaternions/quaternion 0 0 0 1) #v4 [0 0 0 1]) (math/quaternions/quaternion 0 0 1)
(math/quaternions/quaternion 0 0 0 1) (math/quaternions/quaternion 0.5 0.5 0.5 0.5) (= (math/quaternions/quaternion 0 0 0 1) #v4 [0.0 0.0 0.0 1.0]) (math/quaternions/quaternion 0 0 1)
#quat [0.0 0.0 0.0 1.0] #quat [0.5 0.5 0.5 0.5] #err {<mismatch type> message "equality requires matching types"} #err {<arity mismatch> message "wrong number of arguments"}
19.2.13. math/aabbs/aabb
Function(math/aabbs/aabb minimum maximum) → aabb
Returns an AABB from two #v3 values.
(math/aabbs/aabb #v3 [-1 -1 -1] #v3 [1 1 1]) (math/aabbs/aabb #v3 [0 0 0] #v3 [0 0 0]) (= (math/aabbs/aabb #v3 [-1 -2 -3] #v3 [1 2 3]) #aabb [[-1 -2 -3] [1 2 3]]) (math/aabbs/aabb #v3 [0 0 0] #v2 [1 1]) (math/aabbs/aabb [0 0 0] [1 1 1])
(math/aabbs/aabb #v3 [-1.0 -1.0 -1.0] #v3 [1.0 1.0 1.0]) (math/aabbs/aabb #v3 [0.0 0.0 0.0] #v3 [0.0 0.0 0.0]) (= (math/aabbs/aabb #v3 [-1.0 -2.0 -3.0] #v3 [1.0 2.0 3.0]) #aabb [[-1.0 -2.0 -3.0] [1.0 2.0 3.0]]) (math/aabbs/aabb #v3 [0.0 0.0 0.0] #v2 [1.0 1.0]) (math/aabbs/aabb [0 0 0] [1 1 1])
#aabb [[-1.0 -1.0 -1.0] [1.0 1.0 1.0]] #aabb [[0.0 0.0 0.0] [0.0 0.0 0.0]] true #err {<mismatch type> message "geometry constructor received the wrong math value"} #err {<mismatch type> message "geometry constructor received the wrong math value"}
19.2.14. math/rays/ray
Function(math/rays/ray origin direction) → ray
Returns a ray from two #v3 values. The direction need not have unit length.
(math/rays/ray #v3 [0 0 0] #v3 [1 0 0]) (math/rays/ray #v3 [1 2 3] #v3 [0 0 -2]) (math/rays/ray #v3 [0 0 0] #v4 [1 0 0 0])
(math/rays/ray #v3 [0.0 0.0 0.0] #v3 [1.0 0.0 0.0]) (math/rays/ray #v3 [1.0 2.0 3.0] #v3 [0.0 0.0 -2.0]) (math/rays/ray #v3 [0.0 0.0 0.0] #v4 [1.0 0.0 0.0 0.0])
#ray [[0.0 0.0 0.0] [1.0 0.0 0.0]] #ray [[1.0 2.0 3.0] [0.0 0.0 -2.0]] #err {<mismatch type> message "geometry constructor received the wrong math value"}
19.2.15. math/spheres/sphere
Function(math/spheres/sphere center radius) → sphere
Returns a sphere from a #v3 center and a numeric radius.
(math/spheres/sphere #v3 [0 0 0] 1) (math/spheres/sphere #v3 [1 2 3] 0.5) (math/spheres/sphere #v3 [0 0 0] "1") (math/spheres/sphere #v2 [0 0] 1)
(math/spheres/sphere #v3 [0.0 0.0 0.0] 1) (math/spheres/sphere #v3 [1.0 2.0 3.0] 0.5) (math/spheres/sphere #v3 [0.0 0.0 0.0] "1") (math/spheres/sphere #v2 [0.0 0.0] 1)
#sphere [[0.0 0.0 0.0] 1.0] #sphere [[1.0 2.0 3.0] 0.5] #err {<mismatch type> message "math components must be numbers"} #err {<mismatch type> message "sphere center must be #v3"}
19.2.16. math/planes/plane
Function(math/planes/plane normal distance) → plane
Returns a plane from a #v3 normal and a numeric distance.
(math/planes/plane #v3 [0 1 0] -2) (math/planes/plane #v3 [1 0 0] 0) (math/planes/plane #v3 [0 1 0] null)
(math/planes/plane #v3 [0.0 1.0 0.0] -2) (math/planes/plane #v3 [1.0 0.0 0.0] 0) (math/planes/plane #v3 [0.0 1.0 0.0] null)
#plane [[0.0 1.0 0.0] -2.0] #plane [[1.0 0.0 0.0] 0.0] #err {<mismatch type> message "math components must be numbers"}
19.2.17. math/triangles/triangle
Function(math/triangles/triangle a b c) → triangle
Returns a triangle from three #v3 points.
(math/triangles/triangle #v3 [0 0 0] #v3 [1 0 0] #v3 [0 1 0]) (math/triangles/triangle #v3 [1 1 1] #v3 [2 2 2] #v3 [3 3 3]) (math/triangles/triangle #v3 [0 0 0] #v3 [1 0 0])
(math/triangles/triangle #v3 [0.0 0.0 0.0] #v3 [1.0 0.0 0.0] #v3 [0.0 1.0 0.0]) (math/triangles/triangle #v3 [1.0 1.0 1.0] #v3 [2.0 2.0 2.0] #v3 [3.0 3.0 3.0]) (math/triangles/triangle #v3 [0.0 0.0 0.0] #v3 [1.0 0.0 0.0])
#triangle [[0.0 0.0 0.0] [1.0 0.0 0.0] [0.0 1.0 0.0]] #triangle [[1.0 1.0 1.0] [2.0 2.0 2.0] [3.0 3.0 3.0]] #err {<arity mismatch> message "wrong number of arguments"}
19.2.18. math/frustums/frustum
Function(math/frustums/frustum left right bottom top near far) → frustum
Returns a frustum from six #plane values.
(math/frustums/frustum #plane [[1 0 0] 1] #plane [[-1 0 0] 1] #plane [[0 1 0] 1] #plane [[0 -1 0] 1] #plane [[0 0 1] 1] #plane [[0 0 -1] 1]) (= (math/frustums/frustum #plane [[1 0 0] 1] #plane [[-1 0 0] 1] #plane [[0 1 0] 1] #plane [[0 -1 0] 1] #plane [[0 0 1] 1] #plane [[0 0 -1] 1]) #frustum [[1 0 0 1] [-1 0 0 1] [0 1 0 1] [0 -1 0 1] [0 0 1 1] [0 0 -1 1]]) (math/frustums/frustum #plane [[1 0 0] 1] #plane [[-1 0 0] 1] #plane [[0 1 0] 1] #plane [[0 -1 0] 1] #plane [[0 0 1] 1] #v4 [0 0 -1 1])
(math/frustums/frustum #plane [[1.0 0.0 0.0] 1.0] #plane [[-1.0 0.0 0.0] 1.0] #plane [[0.0 1.0 0.0] 1.0] #plane [[0.0 -1.0 0.0] 1.0] #plane [[0.0 0.0 1.0] 1.0] #plane [[0.0 0.0 -1.0] 1.0]) (= (math/frustums/frustum #plane [[1.0 0.0 0.0] 1.0] #plane [[-1.0 0.0 0.0] 1.0] #plane [[0.0 1.0 0.0] 1.0] #plane [[0.0 -1.0 0.0] 1.0] #plane [[0.0 0.0 1.0] 1.0] #plane [[0.0 0.0 -1.0] 1.0]) #frustum [[1.0 0.0 0.0 1.0] [-1.0 0.0 0.0 1.0] [0.0 1.0 0.0 1.0] [0.0 -1.0 0.0 1.0] [0.0 0.0 1.0 1.0] [0.0 0.0 -1.0 1.0]]) (math/frustums/frustum #plane [[1.0 0.0 0.0] 1.0] #plane [[-1.0 0.0 0.0] 1.0] #plane [[0.0 1.0 0.0] 1.0] #plane [[0.0 -1.0 0.0] 1.0] #plane [[0.0 0.0 1.0] 1.0] #v4 [0.0 0.0 -1.0 1.0])
#frustum [[1.0 0.0 0.0 1.0] [-1.0 0.0 0.0 1.0] [0.0 1.0 0.0 1.0] [0.0 -1.0 0.0 1.0] [0.0 0.0 1.0 1.0] [0.0 0.0 -1.0 1.0]] true #err {<mismatch type> message "geometry constructor received the wrong math value"}
19.2.19. v2?
Function(v2? value) → boolean
Returns true for a #v2 value, a two-dimensional vector, otherwise false.
Another packed kind with the same number of components, or a list of the
components, is not one.
(v2? #v2 [1 2]) (v2? #v4 [1 2 3 4]) (v2? [1 2])
(v2? #v2 [1.0 2.0]) (v2? #v4 [1.0 2.0 3.0 4.0]) (v2? [1 2])
true false false
19.2.20. v3?
Function(v3? value) → boolean
Returns true for a #v3 value, a three-dimensional vector, otherwise
false. Another packed kind with the same number of components, or a list of
the components, is not one. As a schema, v3? accepts a #v3 field value.
(v3? #v3 [1 2 3]) (v3? #v4 [1 2 3 4]) (v3? [1 2 3]) (schemas/valid? {position v3?} {position #v3 [1 2 3]}) (schemas/valid? {position v3?} {position [1 2 3]})
(v3? #v3 [1.0 2.0 3.0]) (v3? #v4 [1.0 2.0 3.0 4.0]) (v3? [1 2 3]) (schemas/valid? {position v3?} {position #v3 [1.0 2.0 3.0]}) (schemas/valid? {position v3?} {position [1 2 3]})
true false false true false
19.2.21. v4?
Function(v4? value) → boolean
Returns true for a #v4 value, a four-dimensional vector, otherwise
false. Another packed kind with the same number of components, or a list of
the components, is not one.
(v4? #v4 [1 2 3 4]) (v4? #quat [0 0 0 1]) (v4? [1 2 3 4])
(v4? #v4 [1.0 2.0 3.0 4.0]) (v4? #quat [0.0 0.0 0.0 1.0]) (v4? [1 2 3 4])
true false false
19.2.22. m22?
Function(m22? value) → boolean
Returns true for a #m22 value, a 2 by 2 matrix, otherwise false. Another
packed kind with the same number of components, or a list of the components,
is not one.
(m22? #m22 [[1 0] [0 1]]) (m22? #v4 [1 0 0 1]) (m22? [[1 0] [0 1]])
(m22? #m22 [[1.0 0.0] [0.0 1.0]]) (m22? #v4 [1.0 0.0 0.0 1.0]) (m22? [[1 0] [0 1]])
true false false
19.2.23. m33?
Function(m33? value) → boolean
Returns true for a #m33 value, a 3 by 3 matrix, otherwise false. Another
packed kind with the same number of components, or a list of the components,
is not one.
(m33? #m33 [[1 0 0] [0 1 0] [0 0 1]]) (m33? #triangle [[1 0 0] [0 1 0] [0 0 1]]) (m33? [[1 0 0] [0 1 0] [0 0 1]])
(m33? #m33 [[1.0 0.0 0.0] [0.0 1.0 0.0] [0.0 0.0 1.0]]) (m33? #triangle [[1.0 0.0 0.0] [0.0 1.0 0.0] [0.0 0.0 1.0]]) (m33? [[1 0 0] [0 1 0] [0 0 1]])
true false false
19.2.24. m44?
Function(m44? value) → boolean
Returns true for a #m44 value, a 4 by 4 matrix, otherwise false. Another
packed kind with the same number of components, or a list of the components,
is not one.
(m44? #m44 [[1 0 0 0] [0 1 0 0] [0 0 1 0] [0 0 0 1]]) (m44? #m33 [[1 0 0] [0 1 0] [0 0 1]]) (m44? [[1 0 0 0] [0 1 0 0] [0 0 1 0] [0 0 0 1]])
(m44? #m44 [[1.0 0.0 0.0 0.0] [0.0 1.0 0.0 0.0] [0.0 0.0 1.0 0.0] [0.0 0.0 0.0 1.0]]) (m44? #m33 [[1.0 0.0 0.0] [0.0 1.0 0.0] [0.0 0.0 1.0]]) (m44? [[1 0 0 0] [0 1 0 0] [0 0 1 0] [0 0 0 1]])
true false false
19.2.25. quat?
Function(quat? value) → boolean
Returns true for a #quat value, a quaternion, otherwise false. Another
packed kind with the same number of components, or a list of the components,
is not one.
(quat? #quat [0 0 0 1]) (quat? #v4 [0 0 0 1]) (quat? [0 0 0 1])
(quat? #quat [0.0 0.0 0.0 1.0]) (quat? #v4 [0.0 0.0 0.0 1.0]) (quat? [0 0 0 1])
true false false
19.2.26. aabb?
Function(aabb? value) → boolean
Returns true for a #aabb value, an AABB, otherwise false. Another packed
kind with the same number of components, or a list of the components, is not
one.
(aabb? #aabb [[0 0 0] [1 1 1]]) (aabb? #ray [[0 0 0] [1 1 1]]) (aabb? [[0 0 0] [1 1 1]])
(aabb? #aabb [[0.0 0.0 0.0] [1.0 1.0 1.0]]) (aabb? #ray [[0.0 0.0 0.0] [1.0 1.0 1.0]]) (aabb? [[0 0 0] [1 1 1]])
true false false
19.2.27. ray?
Function(ray? value) → boolean
Returns true for a #ray value, a ray, otherwise false. Another packed
kind with the same number of components, or a list of the components, is not
one.
(ray? #ray [[0 0 0] [0 0 -1]]) (ray? #aabb [[0 0 0] [0 0 -1]]) (ray? [[0 0 0] [0 0 -1]])
(ray? #ray [[0.0 0.0 0.0] [0.0 0.0 -1.0]]) (ray? #aabb [[0.0 0.0 0.0] [0.0 0.0 -1.0]]) (ray? [[0 0 0] [0 0 -1]])
true false false
19.2.28. sphere?
Function(sphere? value) → boolean
Returns true for a #sphere value, a sphere, otherwise false. Another
packed kind with the same number of components, or a list of the components,
is not one.
(sphere? #sphere [[0 0 0] 1]) (sphere? #plane [[0 0 0] 1]) (sphere? [[0 0 0] 1])
(sphere? #sphere [[0.0 0.0 0.0] 1.0]) (sphere? #plane [[0.0 0.0 0.0] 1.0]) (sphere? [[0 0 0] 1])
true false false
19.2.29. plane?
Function(plane? value) → boolean
Returns true for a #plane value, a plane, otherwise false. Another
packed kind with the same number of components, or a list of the components,
is not one.
(plane? #plane [[0 1 0] 0]) (plane? #sphere [[0 1 0] 0]) (plane? [[0 1 0] 0])
(plane? #plane [[0.0 1.0 0.0] 0.0]) (plane? #sphere [[0.0 1.0 0.0] 0.0]) (plane? [[0 1 0] 0])
true false false
19.2.30. triangle?
Function(triangle? value) → boolean
Returns true for a #triangle value, a triangle, otherwise false. Another
packed kind with the same number of components, or a list of the components,
is not one.
(triangle? #triangle [[0 0 0] [1 0 0] [0 1 0]]) (triangle? #m33 [[0 0 0] [1 0 0] [0 1 0]]) (triangle? [[0 0 0] [1 0 0] [0 1 0]])
(triangle? #triangle [[0.0 0.0 0.0] [1.0 0.0 0.0] [0.0 1.0 0.0]]) (triangle? #m33 [[0.0 0.0 0.0] [1.0 0.0 0.0] [0.0 1.0 0.0]]) (triangle? [[0 0 0] [1 0 0] [0 1 0]])
true false false
19.2.31. frustum?
Function(frustum? value) → boolean
Returns true for a #frustum value, a frustum, otherwise false. Another
packed kind with the same number of components, or a list of the components,
is not one.
(frustum? #frustum [[1 0 0 1] [-1 0 0 1] [0 1 0 1] [0 -1 0 1] [0 0 1 1] [0 0 -1 1]]) (frustum? #m44 [[1 0 0 0] [0 1 0 0] [0 0 1 0] [0 0 0 1]]) (frustum? [[1 0 0 1] [-1 0 0 1] [0 1 0 1] [0 -1 0 1] [0 0 1 1] [0 0 -1 1]])
(frustum? #frustum [[1.0 0.0 0.0 1.0] [-1.0 0.0 0.0 1.0] [0.0 1.0 0.0 1.0] [0.0 -1.0 0.0 1.0] [0.0 0.0 1.0 1.0] [0.0 0.0 -1.0 1.0]]) (frustum? #m44 [[1.0 0.0 0.0 0.0] [0.0 1.0 0.0 0.0] [0.0 0.0 1.0 0.0] [0.0 0.0 0.0 1.0]]) (frustum? [[1 0 0 1] [-1 0 0 1] [0 1 0 1] [0 -1 0 1] [0 0 1 1] [0 0 -1 1]])
true false false
19.2.32. vf?
Function(vf? value) → boolean
Returns true for a #vf value, a packed vector of Float lanes, otherwise
false. A #vi value, a fixed packed value such as #v3, or a list of
numbers is not one.
(vf? #vf [1.0 2.0]) (vf? #vf []) (vf? #vi [1 2]) (vf? #v2 [1.0 2.0]) (vf? [1.0 2.0])
true true false false false
19.2.33. vi?
Function(vi? value) → boolean
Returns true for a #vi value, a packed vector of Integer lanes, otherwise
false. A #vf value or a list of integers is not one.
19.2.34. math/vectors/vector?
Function(math/vectors/vector? value) → boolean
Returns true for #v2, #v3, and #v4 values.
(math/vectors/vector? #v2 [1 2]) (math/vectors/vector? #v4 [1 2 3 4]) (math/vectors/vector? #quat [0 0 0 1]) (math/vectors/vector? [1 2 3]) (math/vectors/vector? null)
(math/vectors/vector? #v2 [1.0 2.0]) (math/vectors/vector? #v4 [1.0 2.0 3.0 4.0]) (math/vectors/vector? #quat [0.0 0.0 0.0 1.0]) (math/vectors/vector? [1 2 3]) (math/vectors/vector? null)
true true false false false
19.2.35. math/matrices/matrix?
Function(math/matrices/matrix? value) → boolean
Returns true for #m22, #m33, and #m44 values.
(math/matrices/matrix? #m22 [[1 2] [3 4]]) (math/matrices/matrix? #m44 [[1 0 0 10] [0 1 0 20] [0 0 1 30] [0 0 0 1]]) (math/matrices/matrix? #v4 [1 2 3 4]) (math/matrices/matrix? [[1 2] [3 4]])
(math/matrices/matrix? #m22 [[1.0 2.0] [3.0 4.0]]) (math/matrices/matrix? #m44 [[1.0 0.0 0.0 10.0] [0.0 1.0 0.0 20.0] [0.0 0.0 1.0 30.0] [0.0 0.0 0.0 1.0]]) (math/matrices/matrix? #v4 [1.0 2.0 3.0 4.0]) (math/matrices/matrix? [[1 2] [3 4]])
true true false false
19.2.36. math/quaternions/quaternion?
Function(math/quaternions/quaternion? value) → boolean
Returns true for #quat values.
(math/quaternions/quaternion? #quat [0 0 0 1]) (math/quaternions/quaternion? #v4 [0 0 0 1]) (math/quaternions/quaternion? "quat")
(math/quaternions/quaternion? #quat [0.0 0.0 0.0 1.0]) (math/quaternions/quaternion? #v4 [0.0 0.0 0.0 1.0]) (math/quaternions/quaternion? "quat")
true false false
19.2.37. math/aabbs/aabb?
Function(math/aabbs/aabb? value) → boolean
Returns true for #aabb values.
(math/aabbs/aabb? #aabb [[-1 -1 -1] [1 1 1]]) (math/aabbs/aabb? #ray [[0 0 0] [1 0 0]]) (math/aabbs/aabb? {})
(math/aabbs/aabb? #aabb [[-1.0 -1.0 -1.0] [1.0 1.0 1.0]]) (math/aabbs/aabb? #ray [[0.0 0.0 0.0] [1.0 0.0 0.0]]) (math/aabbs/aabb? {})
true false false
19.2.38. math/rays/ray?
Function(math/rays/ray? value) → boolean
Returns true for #ray values.
(math/rays/ray? #ray [[0 0 0] [1 0 0]]) (math/rays/ray? #aabb [[-1 -1 -1] [1 1 1]]) (math/rays/ray? 1)
(math/rays/ray? #ray [[0.0 0.0 0.0] [1.0 0.0 0.0]]) (math/rays/ray? #aabb [[-1.0 -1.0 -1.0] [1.0 1.0 1.0]]) (math/rays/ray? 1)
true false false
19.2.39. math/spheres/sphere?
Function(math/spheres/sphere? value) → boolean
Returns true for #sphere values.
(math/spheres/sphere? #sphere [[0 0 0] 1]) (math/spheres/sphere? #plane [[0 0 0] 1]) (math/spheres/sphere? null)
(math/spheres/sphere? #sphere [[0.0 0.0 0.0] 1.0]) (math/spheres/sphere? #plane [[0.0 0.0 0.0] 1.0]) (math/spheres/sphere? null)
true false false
19.2.40. math/planes/plane?
Function(math/planes/plane? value) → boolean
Returns true for #plane values.
(math/planes/plane? #plane [[0 1 0] -2]) (math/planes/plane? #sphere [[0 1 0] 2]) (math/planes/plane? [0 1 0 -2])
(math/planes/plane? #plane [[0.0 1.0 0.0] -2.0]) (math/planes/plane? #sphere [[0.0 1.0 0.0] 2.0]) (math/planes/plane? [0 1 0 -2])
true false false
19.2.41. math/triangles/triangle?
Function(math/triangles/triangle? value) → boolean
Returns true for #triangle values.
(math/triangles/triangle? #triangle [[0 0 0] [1 0 0] [0 1 0]]) (math/triangles/triangle? #m33 [[0 0 0] [1 0 0] [0 1 0]]) (math/triangles/triangle? false)
(math/triangles/triangle? #triangle [[0.0 0.0 0.0] [1.0 0.0 0.0] [0.0 1.0 0.0]]) (math/triangles/triangle? #m33 [[0.0 0.0 0.0] [1.0 0.0 0.0] [0.0 1.0 0.0]]) (math/triangles/triangle? false)
true false false
19.2.42. math/frustums/frustum?
Function(math/frustums/frustum? value) → boolean
Returns true for #frustum values.
(math/frustums/frustum? #frustum [[1 0 0 1] [-1 0 0 1] [0 1 0 1] [0 -1 0 1] [0 0 1 1] [0 0 -1 1]]) (math/frustums/frustum? #aabb [[-1 -1 -1] [1 1 1]]) (math/frustums/frustum? [])
(math/frustums/frustum? #frustum [[1.0 0.0 0.0 1.0] [-1.0 0.0 0.0 1.0] [0.0 1.0 0.0 1.0] [0.0 -1.0 0.0 1.0] [0.0 0.0 1.0 1.0] [0.0 0.0 -1.0 1.0]]) (math/frustums/frustum? #aabb [[-1.0 -1.0 -1.0] [1.0 1.0 1.0]]) (math/frustums/frustum? [])
true false false
19.2.43. math/vectors/swizzle
Function(math/vectors/swizzle vector pattern) → float
v2
v3
v4
Returns the components of a #v2, #v3 or #v4 that pattern names, in
its order. The pattern is one to four letters, all from xyzw or all from
rgba, and letters can repeat. One letter returns a Float; two to four
return the vector of that width. (v pattern) is the same swizzle. A literal
pattern compiles to direct component reads.
A pattern that mixes xyzw and rgba, has another letter, is empty or longer
than four letters, or names a component the vector does not have gives
#err <invalid value>. A value that is not a vector gives
#err <mismatch type>.
(math/vectors/swizzle #v3 [1 2 3] "zyx") (math/vectors/swizzle #v4 [1 2 3 4] "rgb") (math/vectors/swizzle #v2 [1 2] "yyxx") (math/vectors/swizzle #v3 [1 2 3] "y") (#v3 [1 2 3] "xz") (let [color #v4 [0.5 0.25 1 1]] (color "bgr"))
(math/vectors/swizzle #v3 [1.0 2.0 3.0] "zyx") (math/vectors/swizzle #v4 [1.0 2.0 3.0 4.0] "rgb") (math/vectors/swizzle #v2 [1.0 2.0] "yyxx") (math/vectors/swizzle #v3 [1.0 2.0 3.0] "y") (#v3 [1.0 2.0 3.0] "xz") (let [color #v4 [0.5 0.25 1.0 1.0]] (color "bgr"))
#v3 [3.0 2.0 1.0] #v3 [1.0 2.0 3.0] #v4 [2.0 2.0 1.0 1.0] 2.0 #v2 [1.0 3.0] #v3 [1.0 0.25 0.5]
(math/vectors/swizzle #v2 [1 2] "xz") (math/vectors/swizzle #v3 [1 2 3] "xg") (math/vectors/swizzle #v3 [1 2 3] "") (math/vectors/swizzle #v3 [1 2 3] "xyzwx") (math/vectors/swizzle #v3 [1 2 3] "xq") (math/vectors/swizzle #quat [0 0 0 1] "x") (math/vectors/swizzle #v3 [1 2 3] 0) (math/vectors/swizzle #v3 [1 2 3])
(math/vectors/swizzle #v2 [1.0 2.0] "xz") (math/vectors/swizzle #v3 [1.0 2.0 3.0] "xg") (math/vectors/swizzle #v3 [1.0 2.0 3.0] "") (math/vectors/swizzle #v3 [1.0 2.0 3.0] "xyzwx") (math/vectors/swizzle #v3 [1.0 2.0 3.0] "xq") (math/vectors/swizzle #quat [0.0 0.0 0.0 1.0] "x") (math/vectors/swizzle #v3 [1.0 2.0 3.0] 0) (math/vectors/swizzle #v3 [1.0 2.0 3.0])
#err {<invalid value> message "a swizzle names a component the vector does not have"} #err {<invalid value> message "a swizzle cannot mix xyzw and rgba"} #err {<invalid value> message "a swizzle names one to four components"} #err {<invalid value> message "a swizzle names one to four components"} #err {<invalid value> message "a swizzle uses the letters xyzw or rgba"} #err {<mismatch type> message "a swizzle requires a #v2, #v3, or #v4 vector"} #err {<mismatch type> message "a swizzle pattern must be a string"} #err {<arity mismatch> message "wrong number of arguments"}
19.2.44. math/vectors/vf
Function(math/vectors/vf numbers) → vf
Returns a #vf with the numbers of a list as its lanes. An Integer becomes the
nearest Float. A #vi argument becomes a #vf with the same numbers, and a
#vf argument is returned as it is.
(math/vectors/vf [1 2.5 -3]) (math/vectors/vf []) (math/vectors/vf #vi [1 2]) (math/vectors/vf [1 "two"])
#vf [1.0 2.5 -3.0] #vf [] #vf [1.0 2.0] #err {<mismatch type> message "math components must be numbers"}
19.2.45. math/vectors/vi
Function(math/vectors/vi integers) → vi
Returns a #vi with the Integers of a list as its lanes. A Float in the list
is an error. A #vi argument is returned as it is.
(math/vectors/vi [1 -2 9007199254740993]) (math/vectors/vi []) (math/vectors/vi [1.0])
#vi [1 -2 9007199254740993] #vi [] #err {<mismatch type> message "#vi lanes must be integers"}
19.2.46. math/vectors/normalize
Function(math/vectors/normalize vector) → v2
v3
v4
vf
Returns a vector with unit length. The vector is a #v2, #v3, #v4 or
#vf. Only the zero vector returns a zero
vector. The vector is divided by its largest component magnitude first, so
no intermediate value leaves the Float range for a finite input.
(math/vectors/normalize #v3 [3 0 4]) (math/vectors/normalize #v2 [0 -2]) (math/vectors/normalize #v4 [1 1 1 1]) (math/vectors/normalize #v3 [0 0 0]) (math/vectors/normalize #v3 [3e38 0 0]) (math/vectors/normalize #quat [0 0 0 1]) (math/vectors/normalize #vf [3 0 4 0])
(math/vectors/normalize #v3 [3.0 0.0 4.0]) (math/vectors/normalize #v2 [0.0 -2.0]) (math/vectors/normalize #v4 [1.0 1.0 1.0 1.0]) (math/vectors/normalize #v3 [0.0 0.0 0.0]) (math/vectors/normalize #v3 [3e+38 0.0 0.0]) (math/vectors/normalize #quat [0.0 0.0 0.0 1.0]) (math/vectors/normalize #vf [3.0 0.0 4.0 0.0])
#v3 [0.6 0.0 0.8] #v2 [0.0 -1.0] #v4 [0.5 0.5 0.5 0.5] #v3 [0.0 0.0 0.0] #v3 [1.0 0.0 0.0] #err {<mismatch type> message "normalize requires a vector"} #vf [0.6 0.0 0.8 0.0]
19.2.47. math/vectors/transform
Function(math/vectors/transform point matrix) → v3
Transforms a #v3 point with a #m44 matrix. The operation uses an implicit
fourth component of one.
(math/vectors/transform #v3 [1 2 3] #m44 [[1 0 0 10] [0 1 0 20] [0 0 1 30] [0 0 0 1]]) (math/vectors/transform #v3 [1 1 1] #m44 [[2 0 0 0] [0 3 0 0] [0 0 4 0] [0 0 0 1]]) (math/vectors/transform #v3 [0 0 0] #m44 [[-1 0 0 0] [0 -1 0 0] [0 0 1 0] [0 0 0 1]]) (math/vectors/transform #v3 [1e308 0 0] #m44 [[10 0 0 0] [0 1 0 0] [0 0 1 0] [0 0 0 1]]) (math/vectors/transform #v4 [1 2 3 1] #m44 [[1 0 0 10] [0 1 0 20] [0 0 1 30] [0 0 0 1]]) (math/vectors/transform #v3 [1e308 1e308 0] #m44 [[10 -10 0 0] [0 1 0 0] [0 0 1 0] [0 0 0 1]]) (math/vectors/transform #v3 [1.7976931348623157e308 -1.7976931348623157e308 0] #m44 [[1 0 0 0] [0 1 0 0] [0 0 1 0] [0 0 0 1]])
(math/vectors/transform #v3 [1.0 2.0 3.0] #m44 [[1.0 0.0 0.0 10.0] [0.0 1.0 0.0 20.0] [0.0 0.0 1.0 30.0] [0.0 0.0 0.0 1.0]]) (math/vectors/transform #v3 [1.0 1.0 1.0] #m44 [[2.0 0.0 0.0 0.0] [0.0 3.0 0.0 0.0] [0.0 0.0 4.0 0.0] [0.0 0.0 0.0 1.0]]) (math/vectors/transform #v3 [0.0 0.0 0.0] #m44 [[-1.0 0.0 0.0 0.0] [0.0 -1.0 0.0 0.0] [0.0 0.0 1.0 0.0] [0.0 0.0 0.0 1.0]]) (math/vectors/transform #v3 [1e+308 0.0 0.0] #m44 [[10.0 0.0 0.0 0.0] [0.0 1.0 0.0 0.0] [0.0 0.0 1.0 0.0] [0.0 0.0 0.0 1.0]]) (math/vectors/transform #v4 [1.0 2.0 3.0 1.0] #m44 [[1.0 0.0 0.0 10.0] [0.0 1.0 0.0 20.0] [0.0 0.0 1.0 30.0] [0.0 0.0 0.0 1.0]]) (math/vectors/transform #v3 [1e+308 1e+308 0.0] #m44 [[10.0 -10.0 0.0 0.0] [0.0 1.0 0.0 0.0] [0.0 0.0 1.0 0.0] [0.0 0.0 0.0 1.0]]) (math/vectors/transform #v3 [1.7976931348623157e+308 -1.7976931348623157e+308 0.0] #m44 [[1.0 0.0 0.0 0.0] [0.0 1.0 0.0 0.0] [0.0 0.0 1.0 0.0] [0.0 0.0 0.0 1.0]])
#v3 [11.0 22.0 33.0] #v3 [2.0 3.0 4.0] #v3 [0.0 0.0 0.0] #err {<float overflow> message "floating-point overflow"} #err {<mismatch type> message "point transform requires #v3"} #err {<float overflow> message "floating-point overflow"} #v3 [1.7976931348623157e+308 -1.7976931348623157e+308 0.0]
19.2.48. math/aabbs/transform
Function(math/aabbs/transform box matrix) → aabb
Transforms an AABB with a #m44 matrix and returns its axis-aligned bounds.
(math/aabbs/transform #aabb [[-1 -2 -3] [1 2 3]] #m44 [[1 0 0 10] [0 1 0 20] [0 0 1 30] [0 0 0 1]]) (math/aabbs/transform #aabb [[-1 -1 -1] [1 1 1]] #m44 [[0 -1 0 0] [1 0 0 0] [0 0 1 0] [0 0 0 1]]) (math/aabbs/transform #aabb [[0 0 0] [1 1 1]] #m44 [[2 0 0 0] [0 3 0 0] [0 0 4 0] [0 0 0 1]]) (math/aabbs/transform #aabb [[-1e308 0 0] [1e308 0 0]] #m44 [[10 0 0 0] [0 1 0 0] [0 0 1 0] [0 0 0 1]]) (math/aabbs/transform #aabb [[-1 -1 -1] [1 1 1]] #m33 [[1 0 0] [0 1 0] [0 0 1]]) (math/aabbs/transform #aabb [[-1.7976931348623157e308 0 0] [1.7976931348623157e308 1 1]] #m44 [[1 0 0 0] [0 1 0 0] [0 0 1 0] [0 0 0 1]]) (math/aabbs/transform #aabb [[0 0 0] [1e308 1 1]] #m44 [[10 0 0 0] [0 1 0 0] [0 0 1 0] [0 0 0 1]])
(math/aabbs/transform #aabb [[-1.0 -2.0 -3.0] [1.0 2.0 3.0]] #m44 [[1.0 0.0 0.0 10.0] [0.0 1.0 0.0 20.0] [0.0 0.0 1.0 30.0] [0.0 0.0 0.0 1.0]]) (math/aabbs/transform #aabb [[-1.0 -1.0 -1.0] [1.0 1.0 1.0]] #m44 [[0.0 -1.0 0.0 0.0] [1.0 0.0 0.0 0.0] [0.0 0.0 1.0 0.0] [0.0 0.0 0.0 1.0]]) (math/aabbs/transform #aabb [[0.0 0.0 0.0] [1.0 1.0 1.0]] #m44 [[2.0 0.0 0.0 0.0] [0.0 3.0 0.0 0.0] [0.0 0.0 4.0 0.0] [0.0 0.0 0.0 1.0]]) (math/aabbs/transform #aabb [[-1e+308 0.0 0.0] [1e+308 0.0 0.0]] #m44 [[10.0 0.0 0.0 0.0] [0.0 1.0 0.0 0.0] [0.0 0.0 1.0 0.0] [0.0 0.0 0.0 1.0]]) (math/aabbs/transform #aabb [[-1.0 -1.0 -1.0] [1.0 1.0 1.0]] #m33 [[1.0 0.0 0.0] [0.0 1.0 0.0] [0.0 0.0 1.0]]) (math/aabbs/transform #aabb [[-1.7976931348623157e+308 0.0 0.0] [1.7976931348623157e+308 1.0 1.0]] #m44 [[1.0 0.0 0.0 0.0] [0.0 1.0 0.0 0.0] [0.0 0.0 1.0 0.0] [0.0 0.0 0.0 1.0]]) (math/aabbs/transform #aabb [[0.0 0.0 0.0] [1e+308 1.0 1.0]] #m44 [[10.0 0.0 0.0 0.0] [0.0 1.0 0.0 0.0] [0.0 0.0 1.0 0.0] [0.0 0.0 0.0 1.0]])
#aabb [[9.0 18.0 27.0] [11.0 22.0 33.0]] #aabb [[-1.0 -1.0 -1.0] [1.0 1.0 1.0]] #aabb [[0.0 0.0 0.0] [2.0 3.0 4.0]] #err {<float overflow> message "floating-point overflow"} #err {<mismatch type> message "AABB transform requires #m44"} #aabb [[-1.7976931348623157e+308 0.0 0.0] [1.7976931348623157e+308 1.0 1.0]] #err {<float overflow> message "floating-point overflow"}
19.2.49. math/rays/intersect-sphere
Function(math/rays/intersect-sphere ray sphere) → list
null
Returns the near and far ray distances. Returns null when there is no hit.
A zero ray direction does not intersect.
(math/rays/intersect-sphere #ray [[-2 0 0] [1 0 0]] #sphere [[0 0 0] 1]) (math/rays/intersect-sphere #ray [[-2 1 0] [1 0 0]] #sphere [[0 0 0] 1]) (math/rays/intersect-sphere #ray [[-2 2 0] [1 0 0]] #sphere [[0 0 0] 1]) (math/rays/intersect-sphere #ray [[0 0 0] [1 0 0]] #sphere [[0 0 0] 1]) (math/rays/intersect-sphere #ray [[2 0 0] [1 0 0]] #sphere [[0 0 0] 1]) (math/rays/intersect-sphere #ray [[0 0 0] [0 0 0]] #sphere [[0 0 0] 1]) (math/rays/intersect-sphere #sphere [[0 0 0] 1] #ray [[-2 0 0] [1 0 0]]) (math/rays/intersect-sphere #ray [[-1e300 0 0] [1 0 0]] #sphere [[0 0 0] 1])
(math/rays/intersect-sphere #ray [[-2.0 0.0 0.0] [1.0 0.0 0.0]] #sphere [[0.0 0.0 0.0] 1.0]) (math/rays/intersect-sphere #ray [[-2.0 1.0 0.0] [1.0 0.0 0.0]] #sphere [[0.0 0.0 0.0] 1.0]) (math/rays/intersect-sphere #ray [[-2.0 2.0 0.0] [1.0 0.0 0.0]] #sphere [[0.0 0.0 0.0] 1.0]) (math/rays/intersect-sphere #ray [[0.0 0.0 0.0] [1.0 0.0 0.0]] #sphere [[0.0 0.0 0.0] 1.0]) (math/rays/intersect-sphere #ray [[2.0 0.0 0.0] [1.0 0.0 0.0]] #sphere [[0.0 0.0 0.0] 1.0]) (math/rays/intersect-sphere #ray [[0.0 0.0 0.0] [0.0 0.0 0.0]] #sphere [[0.0 0.0 0.0] 1.0]) (math/rays/intersect-sphere #sphere [[0.0 0.0 0.0] 1.0] #ray [[-2.0 0.0 0.0] [1.0 0.0 0.0]]) (math/rays/intersect-sphere #ray [[-1e+300 0.0 0.0] [1.0 0.0 0.0]] #sphere [[0.0 0.0 0.0] 1.0])
[[1.0 3.0] [2.0 2.0] null [-1.0 1.0] null null #err {<mismatch type> message "ray-sphere intersection requires #ray"} #err {<float overflow> message "floating-point overflow"}]
19.2.50. math/noise/perlin2
Function(math/noise/perlin2 point) → float
Returns deterministic two-dimensional Perlin noise for a #v2 point. The
noise hash reduces each coordinate modulo 289. Past about 1e160 that
reduction can pass the Float range, which produces #err <float overflow>.
(math/noise/perlin2 #v2 [0 0]) (math/noise/perlin2 #v2 [1 1]) (math/noise/perlin2 #v2 [0.25 -0.75]) (= (math/noise/perlin2 #v2 [0.5 0.5]) (math/noise/perlin2 #v2 [0.5 0.5])) (math/noise/perlin2 #v3 [0 0 0]) (math/noise/perlin2 #v2 [1e300 0.5]) (math/noise/perlin2 #v2 [1e160 0.5])
(math/noise/perlin2 #v2 [0.0 0.0]) (math/noise/perlin2 #v2 [1.0 1.0]) (math/noise/perlin2 #v2 [0.25 -0.75]) (= (math/noise/perlin2 #v2 [0.5 0.5]) (math/noise/perlin2 #v2 [0.5 0.5])) (math/noise/perlin2 #v3 [0.0 0.0 0.0]) (math/noise/perlin2 #v2 [1e+300 0.5]) (math/noise/perlin2 #v2 [1e+160 0.5])
0.0 0.0 -0.2422113204513118 true #err {<mismatch type> message "perlin2 requires #v2"} #err {<float overflow> message "floating-point overflow"} 0.253452410121311
19.2.51. math/intersects?
Function(math/intersects? a b) → boolean
Tests these unordered geometry pairs: AABB with AABB, ray, sphere, or frustum;
ray with sphere, plane, or triangle; and sphere with sphere, plane, or frustum.
Other pairs produce #err <mismatch type>. A test value that passes the Float
range, such as the distance along a ray almost parallel to a plane, produces
#err <float overflow>.
(math/intersects? #aabb [[-1 -1 -1] [1 1 1]] #aabb [[1 1 1] [2 2 2]]) (math/intersects? #aabb [[-1 -1 -1] [1 1 1]] #aabb [[1.5 0 0] [2 1 1]]) (math/intersects? #aabb [[-1 -1 -1] [1 1 1]] #ray [[-2 0 0] [1 0 0]]) (math/intersects? #ray [[-2 0 0] [-1 0 0]] #aabb [[-1 -1 -1] [1 1 1]]) (math/intersects? #aabb [[-1 -1 -1] [1 1 1]] #sphere [[2 0 0] 1]) (math/intersects? #sphere [[2.5 0 0] 1] #aabb [[-1 -1 -1] [1 1 1]]) (math/intersects? #aabb [[-1 -1 -1] [1 1 1]] #frustum [[1 0 0 1] [-1 0 0 1] [0 1 0 1] [0 -1 0 1] [0 0 1 1] [0 0 -1 1]]) (math/intersects? #frustum [[1 0 0 1] [-1 0 0 1] [0 1 0 1] [0 -1 0 1] [0 0 1 1] [0 0 -1 1]] #aabb [[3 3 3] [4 4 4]]) (math/intersects? #ray [[-2 1 0] [1 0 0]] #sphere [[0 0 0] 1]) (math/intersects? #sphere [[0 0 0] 1] #ray [[-2 2 0] [1 0 0]]) (math/intersects? #ray [[0 5 0] [0 -1 0]] #plane [[0 1 0] 0]) (math/intersects? #ray [[0 5 0] [1 0 0]] #plane [[0 1 0] 0]) (math/intersects? #ray [[0.25 0.25 1] [0 0 -1]] #triangle [[0 0 0] [1 0 0] [0 1 0]]) (math/intersects? #triangle [[0 0 0] [1 0 0] [0 1 0]] #ray [[2 2 1] [0 0 -1]]) (math/intersects? #sphere [[0 0 0] 1] #sphere [[2 0 0] 1]) (math/intersects? #sphere [[0 0 0] 1] #sphere [[2.5 0 0] 1]) (math/intersects? #sphere [[0 1 0] 1] #plane [[0 1 0] 0]) (math/intersects? #plane [[0 1 0] 0] #sphere [[0 3 0] 1]) (math/intersects? #sphere [[0 0 0] 1] #frustum [[1 0 0 1] [-1 0 0 1] [0 1 0 1] [0 -1 0 1] [0 0 1 1] [0 0 -1 1]]) (math/intersects? #frustum [[1 0 0 1] [-1 0 0 1] [0 1 0 1] [0 -1 0 1] [0 0 1 1] [0 0 -1 1]] #sphere [[3 0 0] 1]) (math/intersects? #v3 [0 0 0] #v3 [1 1 1]) (math/intersects? #plane [[0 1 0] 0] #plane [[1 0 0] 0]) (math/intersects? #aabb [[-1 -1 -1] [1 1 1]] [0 0 0]) (math/intersects? #ray [[-1e308 0 0] [1e-300 0 0]] #aabb [[-1 -1 -1] [1 1 1]]) (math/intersects? #ray [[-1.7976931348623157e308 0 0] [1 0 0]] #aabb [[-1 -1 -1] [1 1 1]]) (math/intersects? #ray [[0 1e308 0] [0 -1e-300 0]] #plane [[0 1 0] 0]) (math/intersects? #ray [[0 1.7976931348623157e308 0] [0 -1 0]] #plane [[0 1 0] 0]) (math/intersects? #ray [[0 0 1] [0 0 -1]] #triangle [[-1e308 0 0] [1e308 0 0] [0 1 0]]) (math/intersects? #ray [[-1e300 0 0] [1 0 0]] #sphere [[0 0 0] 1]) (math/intersects? #sphere [[-1e300 0 0] 1] #sphere [[1e300 0 0] 1]) (math/intersects? #aabb [[-1 -1 -1] [1 1 1]] #sphere [[1e300 0 0] 1]) (math/intersects? #plane [[0 1 0] 0] #sphere [[0 1e300 0] 1]) (math/intersects? #sphere [[0 0 0] 1] #frustum [[1e300 1e300 0 1] [-1 0 0 1] [0 1 0 1] [0 -1 0 1] [0 0 1 1] [0 0 -1 1]]) (math/intersects? #frustum [[1e300 0 0 1] [-1 0 0 1] [0 1 0 1] [0 -1 0 1] [0 0 1 1] [0 0 -1 1]] #aabb [[-1e10 -1 -1] [1e10 1 1]])
(math/intersects? #aabb [[-1.0 -1.0 -1.0] [1.0 1.0 1.0]] #aabb [[1.0 1.0 1.0] [2.0 2.0 2.0]]) (math/intersects? #aabb [[-1.0 -1.0 -1.0] [1.0 1.0 1.0]] #aabb [[1.5 0.0 0.0] [2.0 1.0 1.0]]) (math/intersects? #aabb [[-1.0 -1.0 -1.0] [1.0 1.0 1.0]] #ray [[-2.0 0.0 0.0] [1.0 0.0 0.0]]) (math/intersects? #ray [[-2.0 0.0 0.0] [-1.0 0.0 0.0]] #aabb [[-1.0 -1.0 -1.0] [1.0 1.0 1.0]]) (math/intersects? #aabb [[-1.0 -1.0 -1.0] [1.0 1.0 1.0]] #sphere [[2.0 0.0 0.0] 1.0]) (math/intersects? #sphere [[2.5 0.0 0.0] 1.0] #aabb [[-1.0 -1.0 -1.0] [1.0 1.0 1.0]]) (math/intersects? #aabb [[-1.0 -1.0 -1.0] [1.0 1.0 1.0]] #frustum [[1.0 0.0 0.0 1.0] [-1.0 0.0 0.0 1.0] [0.0 1.0 0.0 1.0] [0.0 -1.0 0.0 1.0] [0.0 0.0 1.0 1.0] [0.0 0.0 -1.0 1.0]]) (math/intersects? #frustum [[1.0 0.0 0.0 1.0] [-1.0 0.0 0.0 1.0] [0.0 1.0 0.0 1.0] [0.0 -1.0 0.0 1.0] [0.0 0.0 1.0 1.0] [0.0 0.0 -1.0 1.0]] #aabb [[3.0 3.0 3.0] [4.0 4.0 4.0]]) (math/intersects? #ray [[-2.0 1.0 0.0] [1.0 0.0 0.0]] #sphere [[0.0 0.0 0.0] 1.0]) (math/intersects? #sphere [[0.0 0.0 0.0] 1.0] #ray [[-2.0 2.0 0.0] [1.0 0.0 0.0]]) (math/intersects? #ray [[0.0 5.0 0.0] [0.0 -1.0 0.0]] #plane [[0.0 1.0 0.0] 0.0]) (math/intersects? #ray [[0.0 5.0 0.0] [1.0 0.0 0.0]] #plane [[0.0 1.0 0.0] 0.0]) (math/intersects? #ray [[0.25 0.25 1.0] [0.0 0.0 -1.0]] #triangle [[0.0 0.0 0.0] [1.0 0.0 0.0] [0.0 1.0 0.0]]) (math/intersects? #triangle [[0.0 0.0 0.0] [1.0 0.0 0.0] [0.0 1.0 0.0]] #ray [[2.0 2.0 1.0] [0.0 0.0 -1.0]]) (math/intersects? #sphere [[0.0 0.0 0.0] 1.0] #sphere [[2.0 0.0 0.0] 1.0]) (math/intersects? #sphere [[0.0 0.0 0.0] 1.0] #sphere [[2.5 0.0 0.0] 1.0]) (math/intersects? #sphere [[0.0 1.0 0.0] 1.0] #plane [[0.0 1.0 0.0] 0.0]) (math/intersects? #plane [[0.0 1.0 0.0] 0.0] #sphere [[0.0 3.0 0.0] 1.0]) (math/intersects? #sphere [[0.0 0.0 0.0] 1.0] #frustum [[1.0 0.0 0.0 1.0] [-1.0 0.0 0.0 1.0] [0.0 1.0 0.0 1.0] [0.0 -1.0 0.0 1.0] [0.0 0.0 1.0 1.0] [0.0 0.0 -1.0 1.0]]) (math/intersects? #frustum [[1.0 0.0 0.0 1.0] [-1.0 0.0 0.0 1.0] [0.0 1.0 0.0 1.0] [0.0 -1.0 0.0 1.0] [0.0 0.0 1.0 1.0] [0.0 0.0 -1.0 1.0]] #sphere [[3.0 0.0 0.0] 1.0]) (math/intersects? #v3 [0.0 0.0 0.0] #v3 [1.0 1.0 1.0]) (math/intersects? #plane [[0.0 1.0 0.0] 0.0] #plane [[1.0 0.0 0.0] 0.0]) (math/intersects? #aabb [[-1.0 -1.0 -1.0] [1.0 1.0 1.0]] [0 0 0]) (math/intersects? #ray [[-1e+308 0.0 0.0] [1e-300 0.0 0.0]] #aabb [[-1.0 -1.0 -1.0] [1.0 1.0 1.0]]) (math/intersects? #ray [[-1.7976931348623157e+308 0.0 0.0] [1.0 0.0 0.0]] #aabb [[-1.0 -1.0 -1.0] [1.0 1.0 1.0]]) (math/intersects? #ray [[0.0 1e+308 0.0] [0.0 -1e-300 0.0]] #plane [[0.0 1.0 0.0] 0.0]) (math/intersects? #ray [[0.0 1.7976931348623157e+308 0.0] [0.0 -1.0 0.0]] #plane [[0.0 1.0 0.0] 0.0]) (math/intersects? #ray [[0.0 0.0 1.0] [0.0 0.0 -1.0]] #triangle [[-1e+308 0.0 0.0] [1e+308 0.0 0.0] [0.0 1.0 0.0]]) (math/intersects? #ray [[-1e+300 0.0 0.0] [1.0 0.0 0.0]] #sphere [[0.0 0.0 0.0] 1.0]) (math/intersects? #sphere [[-1e+300 0.0 0.0] 1.0] #sphere [[1e+300 0.0 0.0] 1.0]) (math/intersects? #aabb [[-1.0 -1.0 -1.0] [1.0 1.0 1.0]] #sphere [[1e+300 0.0 0.0] 1.0]) (math/intersects? #plane [[0.0 1.0 0.0] 0.0] #sphere [[0.0 1e+300 0.0] 1.0]) (math/intersects? #sphere [[0.0 0.0 0.0] 1.0] #frustum [[1e+300 1e+300 0.0 1.0] [-1.0 0.0 0.0 1.0] [0.0 1.0 0.0 1.0] [0.0 -1.0 0.0 1.0] [0.0 0.0 1.0 1.0] [0.0 0.0 -1.0 1.0]]) (math/intersects? #frustum [[1e+300 0.0 0.0 1.0] [-1.0 0.0 0.0 1.0] [0.0 1.0 0.0 1.0] [0.0 -1.0 0.0 1.0] [0.0 0.0 1.0 1.0] [0.0 0.0 -1.0 1.0]] #aabb [[-10000000000.0 -1.0 -1.0] [10000000000.0 1.0 1.0]])
true false true false true false true false true false true false true false true false true false true false #err {<mismatch type> message "unsupported geometry intersection pair"} #err {<mismatch type> message "unsupported geometry intersection pair"} #err {<mismatch type> message "intersects? requires geometry values"} #err {<float overflow> message "floating-point overflow"} true #err {<float overflow> message "floating-point overflow"} true #err {<float overflow> message "floating-point overflow"} #err {<float overflow> message "floating-point overflow"} #err {<float overflow> message "floating-point overflow"} #err {<float overflow> message "floating-point overflow"} #err {<float overflow> message "floating-point overflow"} #err {<float overflow> message "floating-point overflow"} #err {<float overflow> message "floating-point overflow"}
19.2.52. math/contains?
Function(math/contains? container point) → boolean
Returns true when an AABB or sphere contains a #v3 point. A point on the
boundary is contained. Other containers produce #err <mismatch type>. A
squared distance from a sphere's center past the Float range produces
#err <float overflow>.
(math/contains? #aabb [[-1 -1 -1] [1 1 1]] #v3 [0 0 0]) (math/contains? #aabb [[-1 -1 -1] [1 1 1]] #v3 [1 1 1]) (math/contains? #aabb [[-1 -1 -1] [1 1 1]] #v3 [1 1 1.5]) (math/contains? #sphere [[0 0 0] 1] #v3 [1 0 0]) (math/contains? #sphere [[0 0 0] 1] #v3 [1 1 0]) (math/contains? #ray [[0 0 0] [1 0 0]] #v3 [0 0 0]) (math/contains? #aabb [[-1 -1 -1] [1 1 1]] #v2 [0 0]) (math/contains? #sphere [[0 0 0] 1] #v3 [1e300 0 0])
(math/contains? #aabb [[-1.0 -1.0 -1.0] [1.0 1.0 1.0]] #v3 [0.0 0.0 0.0]) (math/contains? #aabb [[-1.0 -1.0 -1.0] [1.0 1.0 1.0]] #v3 [1.0 1.0 1.0]) (math/contains? #aabb [[-1.0 -1.0 -1.0] [1.0 1.0 1.0]] #v3 [1.0 1.0 1.5]) (math/contains? #sphere [[0.0 0.0 0.0] 1.0] #v3 [1.0 0.0 0.0]) (math/contains? #sphere [[0.0 0.0 0.0] 1.0] #v3 [1.0 1.0 0.0]) (math/contains? #ray [[0.0 0.0 0.0] [1.0 0.0 0.0]] #v3 [0.0 0.0 0.0]) (math/contains? #aabb [[-1.0 -1.0 -1.0] [1.0 1.0 1.0]] #v2 [0.0 0.0]) (math/contains? #sphere [[0.0 0.0 0.0] 1.0] #v3 [1e+300 0.0 0.0])
true true false true false #err {<mismatch type> message "contains? requires an AABB or sphere"} #err {<mismatch type> message "contains? point must be #v3"} #err {<float overflow> message "floating-point overflow"}
20 Time Functions
The Time library provides typed UTC timestamps and durations, stored as signed
64-bit counts of 100-nanosecond ticks. There are 10000000 ticks per second.
A UTC value counts ticks since 1970-01-01T00:00:00Z, without time-zone or
leap-second state; a duration counts elapsed ticks. These are distinct types
from integers and from each other. No implicit conversion turns a number into a duration.
See DUST for language rules, the core arithmetic reference for shared operators, and the Function Index for all callable entries.
20.1. Range and resolution
One tick is 100 ns, or 0.0000001 s. The signed 64-bit range provides roughly
29,227.7 Gregorian years on either side of the Unix epoch, approximately
27,258 BCE through 31,197 CE. Exact endpoint spellings use astronomical year
numbering, including year zero:
| Payload | Canonical UTC |
|---|---|
-9223372036854775808 ticks |
-27258-04-19T21:11:54.5224192Z |
9223372036854775807 ticks |
31197-09-14T02:48:05.4775807Z |
The range covers recorded history, back to the
first writing in Uruk around
3400 BCE: clay tablets logging deliveries, rations, and labor, the first event logs.
It also leaves room for fictional dates: Dune's
Butlerian Jihad
and the Horus Heresy, whose
official timeline includes events in 005.M31 through 014.M31, around
30,005–30,014 CE. The Dune Encyclopedia dates its Jihad as 200–108 B.G.; a
conversion to a specific Gregorian year is not part of this API.
The resolution remains fine enough to describe fast motion. Using the
approximate Parker Solar Probe speed of 191.2 km/s, a 100 ns tick
corresponds to 191200 × 0.0000001 = 0.01912 m, about 19 mm.
NASA reports its record flyby speed as about 430,000 mph,
which gives the same approximately 19 mm scale per tick.
Windows FILETIME
also uses 100 ns units, with a different epoch. A representation's resolution
does not guarantee that a clock or scheduler measures time that accurately.
Canonical timestamps and durations use at most seven fractional second digits. Text accepts up to nine fractional second digits and is rounded to the nearest tick, with halfway cases rounded away from zero. A nonzero timestamp or duration that would round to zero is represented by one tick in magnitude.
(time/utc -9223372036854775808) (time/utc 9223372036854775807) (time/utc "30005-01-01T00:00:00Z")
#utc "-27258-04-19T21:11:54.5224192Z" #utc "31197-09-14T02:48:05.4775807Z" #utc "30005-01-01T00:00:00Z"
(time/duration -9223372036854775808) (time/duration 9223372036854775807) (time/units "ns" (time/duration 1))
#dur "-P10675199DT2H48M5.4775808S" #dur "P10675199DT2H48M5.4775807S" 100
#utc "2024-02-29T12:34:56.1234567Z" #utc "2024-02-29T12:34:56.1234567Z"
#utc "2024-02-29T12:34:56.1234567Z" #utc "2024-02-29T12:34:56.1234567Z"
20.2. Types and conversion
20.2.1. time/utc
Function(time/utc value) → UTC
An integer supplies a raw count of 100 ns ticks since the Unix epoch. A string
supplies a UTC timestamp ending in Z. A float supplies a Julian day, following SQLite's
Julian-day convention: day 0.0 is -4713-11-24T12:00:00Z, 2440587.5 is the Unix epoch,
and 2451545.0 is 2000-01-01T12:00:00Z.
Integer and float arguments deliberately have different units. Use an integer for exact tick counts; Julian-day floats have ordinary floating-point precision limits. Julian days are rounded to the nearest tick, with exact halfway cases rounded away from the Unix epoch. Invalid or out-of-range timestamp input is an error.
(time/utc 0) (time/utc -1) (time/utc "2024-02-29T12:34:56.1234567Z")
#utc "1970-01-01T00:00:00Z" #utc "1969-12-31T23:59:59.9999999Z" #utc "2024-02-29T12:34:56.1234567Z"
(time/utc 0.0) (time/utc 2440587.5) (time/utc 2451545.0)
#utc "-4713-11-24T12:00:00Z" #utc "1970-01-01T00:00:00Z" #utc "2000-01-01T12:00:00Z"
20.2.2. time/duration
Function(time/duration value) → duration
(time/duration amount unit) → duration
With one argument, a number supplies a raw 100 ns tick count and a string
supplies an ISO duration. A float is rounded to the nearest tick, with halfway
cases rounded away from zero and a minimum of one tick in magnitude for
nonzero values: (time/duration 1.5) is two ticks.
With two arguments, amount is an integer or float and unit is one of
ns, us, µs, ms, s, m, h, d, w, tick, or ticks.
Both tick spellings mean 100 ns. Days and weeks mean fixed elapsed intervals
of 24 hours and seven days. The result is always a typed duration.
Numeric amounts are rounded to the nearest tick, with halfway cases rounded
away from zero. A nonzero amount that rounds to zero is raised to one tick
in magnitude. For example, (time/duration 1 ns) is one tick,
(time/duration 101 ns) is one tick, and (time/duration -1 ns) is minus
one tick. (time/duration 1.5 ticks) is two ticks and
(time/duration 1.5 h) returns #dur PT1H30M.
Years and months are calendar offsets, not fixed duration
units; use time/shift for them.
(time/duration 0) (time/duration -1) (time/duration "PT1H30M")
#dur "PT0S" #dur "-PT0.0000001S" #dur "PT1H30M"
(time/duration 100 "ns") (time/duration 1 "us") (time/duration 1 "µs") (time/duration 1 "ms") (time/duration 1 "s") (time/duration 1 "m") (time/duration 1 "h") (time/duration 1 "d") (time/duration 1 "w") (time/duration 1 "tick") (time/duration 1 "ticks") (time/duration 1.5 "h")
#dur "PT0.0000001S" #dur "PT0.000001S" #dur "PT0.000001S" #dur "PT0.001S" #dur "PT1S" #dur "PT1M" #dur "PT1H" #dur "P1D" #dur "P7D" #dur "PT0.0000001S" #dur "PT0.0000001S" #dur "PT1H30M"
(time/duration 1.5) (time/duration -1.5) (time/duration 1.4)
#dur "PT0.0000002S" #dur "-PT0.0000002S" #dur "PT0.0000001S"
20.2.3. time/units
Function(time/units unit value) → number
Expresses a UTC timestamp or duration in the requested unit. The unit argument comes first. For UTC, the result measures time since the Unix epoch; for a duration, it measures the elapsed interval. The underlying value remains a signed count of 100 ns ticks.
| Unit | Meaning | Result kind |
|---|---|---|
tick, ticks |
100 ns ticks | Integer |
ns |
Nanoseconds | Integer |
us, µs |
Microseconds | Float |
ms |
Milliseconds | Float |
s |
Seconds | Float |
m |
Minutes | Float |
h |
Hours | Float |
d |
24-hour days | Float |
w |
Seven-day weeks | Float |
Float results retain fractional units. For example,
(time/units s #dur PT1.5S) returns 1.5, while
(time/units ns (time/duration 1)) returns integer 100.
Float conversions can lose precision for large values.
Exact tick counts retain the full signed 64-bit range:
(time/units "ticks" (time/utc 1)) (time/units "ticks" (time/duration 1 "ticks")) (time/units "ticks" (time/duration -9223372036854775808))
1 1 -9223372036854775808
Nanosecond results are also integers:
(time/units "ns" #utc "1970-01-01T00:00:00Z") (time/units "ns" #dur "PT1.5S") (time/units "ns" #utc "1969-12-31T23:59:59.9999999Z")
0 1500000000 -100
Larger units retain fractional duration values:
(time/units "us" (time/duration 5)) (time/units "us" (time/duration -5)) (time/units "µs" (time/duration 5)) (time/units "µs" (time/duration -5)) (time/units "ms" (time/duration 2500)) (time/units "ms" (time/duration -2500)) (time/units "s" (time/duration 1250000)) (time/units "s" (time/duration -1250000)) (time/units "m" (time/duration 75000000)) (time/units "m" (time/duration -75000000)) (time/units "h" (time/duration 4500000000)) (time/units "h" (time/duration -4500000000)) (time/units "d" (time/duration 108000000000)) (time/units "d" (time/duration -108000000000)) (time/units "w" (time/duration 756000000000)) (time/units "w" (time/duration -756000000000))
0.5 -0.5 0.5 -0.5 0.25 -0.25 0.125 -0.125 0.125 -0.125 0.125 -0.125 0.125 -0.125 0.125 -0.125
UTC conversions measure fractional units from the Unix epoch:
(time/units "us" (time/utc 5)) (time/units "us" (time/utc -5)) (time/units "µs" (time/utc 5)) (time/units "µs" (time/utc -5)) (time/units "ms" (time/utc 2500)) (time/units "ms" (time/utc -2500)) (time/units "s" (time/utc 1250000)) (time/units "s" (time/utc -1250000)) (time/units "m" (time/utc 75000000)) (time/units "m" (time/utc -75000000)) (time/units "h" (time/utc 4500000000)) (time/units "h" (time/utc -4500000000)) (time/units "d" (time/utc 108000000000)) (time/units "d" (time/utc -108000000000)) (time/units "w" (time/utc 756000000000)) (time/units "w" (time/utc -756000000000))
0.5 -0.5 0.5 -0.5 0.25 -0.25 0.125 -0.125 0.125 -0.125 0.125 -0.125 0.125 -0.125 0.125 -0.125
Conversion to a finer unit can exceed the signed 64-bit range. In particular, expressing ticks as nanoseconds requires multiplication by 100, so a valid timestamp or duration can overflow that conversion. Overflow is checked.
20.2.4. time/utc?
Function(time/utc? value) → boolean
Returns whether the value has the UTC kind. Durations and integers return false.
(time/utc? #utc "1970-01-01T00:00:00Z") (time/utc? #dur "PT0S") (time/utc? 0)
true false false
20.2.5. time/duration?
Function(time/duration? value) → boolean
Returns whether the value has the duration kind. UTC timestamps and integers
return false.
(time/duration? #dur "PT0S") (time/duration? #utc "1970-01-01T00:00:00Z") (time/duration? 0)
true false false
20.2.6. time/format
Function(time/format value) → string
Formats a UTC timestamp or duration as its canonical ISO string, without a
DUST tag prefix. The full 100 ns tick precision is retained. For readable display text,
use the String library's strings/humanize function.
(time/format #utc "1970-01-01T00:00:00Z") (time/format #utc "1969-12-31T23:59:59.9999999Z") (time/format #dur "PT1.5S")
"1970-01-01T00:00:00Z" "1969-12-31T23:59:59.9999999Z" "PT1.5S"
20.3. Temporal arithmetic
The Core library's shared operators accept these explicit temporal combinations. Each result retains its indicated kind. Arithmetic uses exact signed 64-bit ticks and reports overflow rather than wrapping.
| Operation | Result |
|---|---|
| UTC + duration; duration + UTC | UTC |
| Duration + duration | Duration |
| UTC - duration | UTC |
| UTC - UTC; duration - duration | Duration |
| Duration * integer; integer * duration | Duration |
| Duration / integer | Duration, ticks truncated toward zero |
| Duration / duration | Float ratio |
Operations with several operands fold from left to right, so the kind of each intermediate result determines the next operation. Unary addition preserves UTC and duration values. Unary subtraction negates a duration; a timestamp cannot be negated. Unary multiplication preserves a duration, while a duration has no unary reciprocal.
(+ #utc "1970-01-01T00:00:00Z" #dur "PT1S") (+ #dur "PT1S" #utc "1970-01-01T00:00:00Z") (+ #dur "PT1S" #dur "PT2S") (+ #utc "1970-01-01T00:00:00Z") (+ #dur "PT1S")
#utc "1970-01-01T00:00:01Z" #utc "1970-01-01T00:00:01Z" #dur "PT3S" #utc "1970-01-01T00:00:00Z" #dur "PT1S"
(- #utc "1970-01-01T00:00:01Z" #utc "1970-01-01T00:00:00Z") (- #utc "1970-01-01T00:00:01Z" #dur "PT2S") (- #dur "PT3S" #dur "PT1S") (- #dur "PT1S")
#dur "PT1S" #utc "1969-12-31T23:59:59Z" #dur "PT2S" #dur "-PT1S"
(* #dur "PT1.5S" 2) (* 2 #dur "PT1.5S") (* #dur "PT1S") (* 2 #dur "PT3S" 2)
#dur "PT3S" #dur "PT3S" #dur "PT1S" #dur "PT12S"
(/ #dur "PT3S" 2) (/ #dur "PT0.0000001S" -2) (/ #dur "-PT0.0000003S" 2) (/ #dur "PT3S" #dur "PT2S")
#dur "PT1.5S" #dur "PT0S" #dur "-PT0.0000001S" 1.5
math/abs accepts durations. math/min, math/max, and math/clamp accept
matching UTC or duration kinds and preserve the selected value's kind.
They compare all ticks exactly.
(math/abs #dur "-PT1S") (math/abs #dur "PT0S") (math/abs #dur "PT1.5S")
#dur "PT1S" #dur "PT0S" #dur "PT1.5S"
(math/min #dur "PT2S" #dur "PT1S") (math/min #utc "1970-01-02T00:00:00Z" #utc "1970-01-01T00:00:00Z") (math/min #dur "-PT1S" #dur "PT0S")
#dur "PT1S" #utc "1970-01-01T00:00:00Z" #dur "-PT1S"
(math/max #dur "PT2S" #dur "PT1S") (math/max #utc "1970-01-02T00:00:00Z" #utc "1970-01-01T00:00:00Z") (math/max #dur "-PT1S" #dur "PT0S")
#dur "PT2S" #utc "1970-01-02T00:00:00Z" #dur "PT0S"
(math/clamp #dur "PT3S" #dur "PT1S" #dur "PT2S") (math/clamp #utc "1970-01-01T00:00:00Z" #utc "1970-01-02T00:00:00Z" #utc "1970-01-03T00:00:00Z") (math/clamp #dur "PT1.5S" #dur "PT1S" #dur "PT2S")
#dur "PT2S" #utc "1970-01-02T00:00:00Z" #dur "PT1.5S"
20.3.1. Rejected combinations and bounds
UTC plus UTC, duration minus UTC, and numeric additions to durations are type errors. Durations multiply only by integers, and division requires an integer or a duration as the divisor. There is no implicit conversion from seconds or another numeric unit; construct a duration explicitly. Zero divisors are errors.
20.4. Calendar operations
Calendar fields and boundaries use UTC. Week boundaries begin on Monday.
20.4.1. time/parts
Function(time/parts timestamp) → map
Returns integer fields year, month, day, hour, minute, second,
nanosecond, and weekday. Months and days start at one. ISO weekdays run from
one for Monday through seven for Sunday. The nanosecond field is the fractional
part of the second, from zero through 999999900 in multiples of 100.
(time/parts #utc "2024-02-29T12:34:56.1234567Z") (time/parts #utc "1970-01-01T00:00:00Z") (time/parts #utc "1969-12-31T23:59:59.9999999Z")
{day 29 hour 12 minute 34 month 2 nanosecond 123456700 second 56 weekday 4 year 2024} {day 1 hour 0 minute 0 month 1 nanosecond 0 second 0 weekday 4 year 1970} {day 31 hour 23 minute 59 month 12 nanosecond 999999900 second 59 weekday 3 year 1969}
20.4.2. time/start-of
Function(time/start-of timestamp unit) → UTC
Returns the start of the containing UTC calendar unit. The unit is one of
year, month, week, day, hour, minute, or second.
This floors to the earlier boundary, including for times before the Unix epoch.
A week's Monday can fall in the preceding month or year.
(time/start-of #utc "2026-05-06T12:34:56.123Z" "year") (time/start-of #utc "2026-05-06T12:34:56.123Z" "month") (time/start-of #utc "2026-01-01T12:34:56Z" "week") (time/start-of #utc "2026-05-06T12:34:56.123Z" "day") (time/start-of #utc "2026-05-06T12:34:56.123Z" "hour") (time/start-of #utc "2026-05-06T12:34:56.123Z" "minute") (time/start-of #utc "1969-12-31T23:59:59.999Z" "second")
#utc "2026-01-01T00:00:00Z" #utc "2026-05-01T00:00:00Z" #utc "2025-12-29T00:00:00Z" #utc "2026-05-06T00:00:00Z" #utc "2026-05-06T12:00:00Z" #utc "2026-05-06T12:34:00Z" #utc "1969-12-31T23:59:59Z"
20.4.3. time/shift
Function(time/shift timestamp changes) → UTC
Shifts by a map containing integer years, months, and days offsets.
Omitted offsets are zero; negative offsets move backward. Unknown fields and
non-integer offsets are errors.
The year and month offsets are combined into one month shift. The original day
is then clamped to the last valid day of the resulting month, and the day offset
is applied afterward. Time of day and the 100 ns fraction are retained. For example,
January 31 plus one month becomes February 28 or 29. February 29, 2024 plus one
year becomes February 28, 2025. This uses the earlier valid date when the target
month is shorter; SQLite's default ceiling rule
instead resolves that leap-day example to March 1. Combining years 1 and
months -1 shifts February 29, 2024 to January 29, 2025, with only one clamp.
(time/shift #utc "2024-01-31T12:34:56.123Z" {months 1}) (time/shift #utc "2023-01-31T12:00:00Z" {months 1}) (time/shift #utc "2024-01-31T12:00:00Z" {days 1 months 1}) (time/shift #utc "2024-02-29T12:00:00Z" {months -1 years 1}) (time/shift #utc "2024-03-31T12:00:00Z" {months -1}) (time/shift #utc "2024-02-29T12:00:00Z" {years 1})
#utc "2024-02-29T12:34:56.123Z" #utc "2023-02-28T12:00:00Z" #utc "2024-03-01T12:00:00Z" #utc "2025-01-29T12:00:00Z" #utc "2024-02-29T12:00:00Z" #utc "2025-02-28T12:00:00Z"
20.5. Duration quantization
Both arguments must be durations, and the quantum must be strictly positive. A rounded result outside signed 64-bit ticks is an overflow error.
20.5.1. time/truncate
Function(time/truncate duration quantum) → duration
Returns the multiple of quantum reached by truncating toward zero.
For example, 1.9s becomes 1s and -1.9s becomes -1s at a one-second quantum.
(time/truncate #dur "PT1.9S" #dur "PT1S") (time/truncate #dur "-PT1.9S" #dur "PT1S") (time/truncate #dur "PT0.5S" #dur "PT1S")
#dur "PT1S" #dur "-PT1S" #dur "PT0S"
20.5.2. time/round
Function(time/round duration quantum) → duration
Returns the nearest multiple of quantum, with halfway cases rounded away
from zero. At a one-second quantum, 1.5s becomes 2s and -1.5s becomes -2s.
(time/round #dur "PT1.5S" #dur "PT1S") (time/round #dur "-PT1.5S" #dur "PT1S") (time/round #dur "PT1.4S" #dur "PT1S")
#dur "PT2S" #dur "-PT2S" #dur "PT1S"
(time/round (time/duration 9223372036854775807) (time/duration 4))
#err <integer overflow>
20.6. time/now
Function(time/now) → UTC
This function requires the io plugin. It reads the host clock. The clock
setting of the io plugin can stop the calls
(Scheduled reactor settings). A stopped call returns
#err <clock denied>.
Returns the current wall-clock time as a typed UTC value with 100 ns resolution. Takes no arguments. The wall clock can change independently of evaluation; this function does not provide a monotonic elapsed-time clock.
To humanize a timestamp relative to the clock, pass the returned UTC explicitly:
(strings/humanize #utc "2026-10-29T12:00:00Z" {mode "relative" now (time/now)})
Use the String library's strings/humanize function for readable
durations or absolute and relative timestamps. Relative formatting requires an
explicit UTC reference time and never reads the clock implicitly.
21 Filesystem Functions
The fs/ namespace reads and changes the host filesystem.
Embedded hosts enable filesystem access for each evaluation or call.
When access is off, operations that access the filesystem produce #err <fs denied>.
Lexical path operations need only the stdlib plugin and do not require the filesystem grant.
A function does not retain filesystem access from the evaluation that created it.
The fs/ names are reserved.
The stardust command enables access when the io plugin is explicitly selected.
Byte I/O uses Bytes values.
Streaming I/O, pipes, devices, and changes to the process working directory are outside this namespace.
The namespace specifies Linux, macOS, FreeBSD, and Windows behavior.
Behavior that differs between them is stated with each function, and an operation a host cannot perform produces #err <fs unsupported>.
Calls that read or change the filesystem run in evaluation order. Each call observes the filesystem at the time it runs.
These functions are not a filesystem sandbox.
Lexical path operations can change which file a path containing symbolic links reaches, so they do not replace fs/real-path or an access-control check.
21.1. Common contracts
21.1.1. Paths
A path is a nonempty string in the host platform's path syntax.
There is no separate Path or File value.
Use "." for the current directory.
null, an empty string, and a string that contains a NUL character produce #err <invalid value>.
A non-string path produces #err <mismatch type>.
A host filename that cannot be represented losslessly as a Dust string produces an error rather than a lossy path.
The namespace does not expand ~, environment variables, or wildcard patterns.
21.1.2. Arguments and options
Required arguments have fixed positions, and an options map comes last.
An omitted or null options argument means {}.
An unknown option, an option of the wrong type, or a capability that the host does not support produces an error.
Boolean options take true or false only, not other truthy values, and can use tag syntax:
(fs/write "app.log" "message\n" {<append>})
(fs/copy "source" "destination" {<replace-existing>})
Arguments are validated before the filesystem changes.
21.1.3. Links and file kinds
Whole-file readers, writers, and fs/copy operate on regular files and follow symbolic links.
Exclusive creation treats any existing entry as a collision, including a dangling symbolic link.
Deletion and recursive traversal do not follow symbolic links.
Intermediate symbolic links in a supplied path use normal host path resolution.
21.1.4. Failures
A filesystem failure returns an #err value tagged fs and one kind:
| Tags | Raised when |
|---|---|
<fs missing> |
The entry or a parent component does not exist |
<fs exists> |
Exclusive creation found an existing entry |
<fs denied> |
Filesystem access is off, or the host refused access |
<fs not-directory> |
A directory was required |
<fs directory> |
A non-directory was required |
<fs not-empty> |
A directory to remove has entries |
<fs loop> |
Symbolic-link resolution found a cycle |
<fs same-file> |
A copy source and destination are the same file |
<fs replaced> |
A temporary root was replaced before cleanup |
<fs unsupported> |
The host cannot perform the requested operation or setting |
<fs io> |
Any other host failure |
The error map carries the operation name, the relevant paths, and the OS error code as diagnostics.
A permission failure is denied, never missing.
Filesystem calls respect the evaluation's resource and cancellation limits.
Cancellation can be delayed until an operation in progress completes.
Directory traversal goes to any depth. fs/walk and fs/remove-all keep one open descriptor for each directory on the current path, so the host's open-file limit bounds the depth; past it they fail with <fs io>.
Only fs/mkdir-all creates parent directories.
Writes and copies are not transactions: an I/O failure can leave partial output, and success does not promise durability after a crash.
21.2. Paths
Path functions are lexical and do not read the filesystem, except fs/real-path.
fs/abs and fs/rel read the process working directory.
Extension functions examine only the final name component. A leading dot alone does not start an extension:
| Path | fs/ext |
fs/strip-ext |
|---|---|---|
"archive.tar.gz" |
"gz" |
"archive.tar" |
".config.json" |
"json" |
".config" |
".env" |
null |
".env" |
"notes." |
"" |
"notes" |
".." |
null |
".." |
A filename stem is (fs/strip-ext (fs/file-name path)).
21.2.1. fs/join
Function(fs/join part) → string
(fs/join parent child more*) → string
Returns a path formed from the supplied parts.
An absolute child replaces the path before it.
Does not resolve symbolic links or collapse . and .. components.
21.2.2. fs/parent
Function(fs/parent path) → string or null
Returns the lexical parent of path, or null if there is none.
Ignores trailing separators except those that form a root.
21.2.3. fs/file-name
Function(fs/file-name path) → string or null
Returns the final name component of path, or null for a root.
Ignores trailing separators.
21.2.4. fs/ext
Function(fs/ext path) → string or null
Returns the final filename extension without its dot, or null if there is none.
Neither . nor .. has an extension.
A trailing dot gives the empty string.
21.2.5. fs/strip-ext
Function(fs/strip-ext path) → string
Returns path with its final filename extension and dot removed.
Returns path unchanged when it has no extension.
21.2.6. fs/normalize
Function(fs/normalize path) → string
Returns a lexically normalized path.
Removes redundant separators and . components, and reduces .. components that have a preceding name.
Keeps unresolved leading .. components in a relative path.
Returns "." when a relative path reduces to the current directory.
Does not resolve symbolic links.
21.2.7. fs/abs
Function(fs/abs path) → string
Returns an absolute path, using the process working directory when path is relative.
The target need not exist.
Does not resolve symbolic links or normalize dot components.
21.2.8. fs/real-path
Function(fs/real-path path) → string
Returns an absolute path with all symbolic links resolved.
The target must exist.
A broken link produces #err <fs missing>, and a link cycle produces #err <fs loop>.
21.2.9. fs/rel
Function(fs/rel path) → string
(fs/rel base path) → string
Returns a lexical relative path from base to path.
base defaults to the process working directory.
Both inputs are made absolute against the same working directory and normalized.
Returns "." when the normalized paths are equal.
Paths under different host roots, such as two drives, produce #err <invalid value>.
Does not resolve symbolic links or require the paths to exist.
21.3. Files
Write options are append, create-new, and permissions.
append and create-new default to false.
append affects only this write, not a persistent file attribute.
create-new fails if the path already exists, even when append is also true.
When calls compete to create the same path, only one can succeed.
permissions takes a permission map and applies only when the call creates the file.
Text I/O uses UTF-8.
For other encodings, read Bytes with fs/read and decode them.
Content that is neither a string nor Bytes produces #err <mismatch type>.
(fs/write "secret.key" data {<create-new> permissions {user <r w>}})
21.3.1. fs/read
Function(fs/read path) → Bytes
(fs/read path opts) → Bytes or string
Returns the entire file as Bytes. An empty file returns #b64 "".
With {encoding <utf8>}, returns a string and rejects invalid UTF-8 with #err <invalid value>.
Text reads retain line endings and a leading byte-order mark.
21.3.2. fs/write
Function(fs/write path content) → string
(fs/write path content opts) → string
Writes content and returns path. A string is encoded as UTF-8; Bytes are written unchanged.
Creates the file if absent and truncates an existing file unless append is true.
Adds no newline or byte-order mark.
21.3.3. fs/create-file
Function(fs/create-file path) → string
(fs/create-file path opts) → string
Exclusively creates an empty regular file and returns path.
Any existing entry produces #err <fs exists>.
The only option is permissions.
21.3.4. fs/copy
Function(fs/copy source destination) → string
(fs/copy source destination opts) → string
Copies the contents of source to the exact path destination and returns destination.
Options are replace-existing, which defaults to false, and permissions.
An existing destination produces #err <fs exists> unless replace-existing is true.
With replacement, a destination symbolic link is followed to its target, as the write functions do.
When source and destination are the same file, including through a hard or symbolic link, the copy produces #err <fs same-file> before it truncates anything.
Does not recurse, copy metadata, or add a filename when destination is a directory.
21.4. Directories
Directory creation takes only the permissions option.
Listing functions form child paths under the supplied path, keeping it relative or absolute.
They sort siblings by Dust string ordering and include hidden entries.
A listing error returns the error, never a partial list.
21.4.1. fs/mkdir
Function(fs/mkdir path) → string
(fs/mkdir path opts) → string
Creates one directory and returns path.
The parent must exist.
An existing entry produces #err <fs exists>.
21.4.2. fs/mkdir-all
Function(fs/mkdir-all path) → string
(fs/mkdir-all path opts) → string
Creates missing parent directories and the directory at path, and returns path.
An existing directory is accepted, including through a symbolic link.
A conflicting non-directory entry produces #err <fs not-directory>.
permissions applies only to the directories that the call creates.
21.4.3. fs/read-dir
Function(fs/read-dir dir) → list
Returns a list of the immediate child paths of dir.
Excludes the . and .. entries.
An empty directory returns [].
21.4.4. fs/walk
Function(fs/walk root) → list
Returns a depth-first list of root and its descendants.
Each directory comes before its children.
Includes symbolic links but never descends through one, including when the root has trailing separators.
A file or symbolic-link root returns a one-element list.
A missing root or a traversal failure produces an error.
There are no visitor callbacks, glob patterns, or link-following option.
21.5. Inspection
The predicates return false for a missing entry and an error for any other failure.
fs/stat and fs/lstat report the kind of entry as a type member, a tag-only map with one tag:
| Tag | Entry |
|---|---|
file |
Regular file |
dir |
Directory |
symlink |
Symbolic link, reported only by fs/lstat |
block-device |
Block device |
char-device |
Character device |
named-pipe |
Named pipe (FIFO) |
socket |
Unix domain socket |
irregular |
Any other kind that the host reports |
(get (fs/lstat "/dev/null") "type")
; <char-device>
21.5.1. fs/exists?
Function(fs/exists? path) → boolean
Returns true if path resolves to an existing entry.
Returns false if the target or a parent component is absent.
Follows symbolic links, so a dangling link returns false.
21.5.2. fs/file?
Function(fs/file? path) → boolean
Returns true if path resolves to a regular file, following symbolic links.
21.5.3. fs/dir?
Function(fs/dir? path) → boolean
Returns true if path resolves to a directory, following symbolic links.
21.5.4. fs/symlink?
Function(fs/symlink? path) → boolean
Returns true if the final entry is a symbolic link, including a dangling link.
Ignores trailing separators and does not follow the final link.
21.5.5. fs/stat
Function(fs/stat path) → map
Returns metadata for the entry that path reaches, following symbolic links.
A missing target or other failure produces an error.
The result always has the same members:
| Member | Value |
|---|---|
type |
File type tag map with exactly one tag |
size |
Host-reported byte length of a regular file, otherwise null |
modified, accessed, changed, created |
#utc timestamp, or null when unavailable |
permissions |
Permission map, or null when unsupported |
changed is the metadata-change time, not the creation time.
A missing creation time stays null and is not taken from another timestamp.
Host timestamps are rounded down to the 100 ns tick.
type describes the entry found.
Changing the returned map does not change the filesystem.
(fs/stat "run.sh")
; {accessed #utc "2026-11-05T09:12:44.1234567Z"
; changed #utc "2026-11-01T17:03:10Z"
; created null
; modified #utc "2026-11-01T17:03:10Z"
; permissions {group <r x> other <r x> user <r w x>}
; size 412
; type <file>}
21.5.6. fs/lstat
Function(fs/lstat path) → map
Returns the same metadata as fs/stat for the final entry at path, ignoring trailing separators and without following that entry's symbolic link.
21.6. Permissions
A permission map gives the POSIX permission bits as boolean tags.
The members user, group, and other are each a tag-only map of the access bits r, w, and x.
The special bits are the top-level tags setuid, setgid, and sticky.
On a directory, x permits searching the directory.
| Permission map | POSIX mode | Access |
|---|---|---|
{user <r w>} |
0600 |
User read and write |
{group <r> other <r> user <r w>} |
0644 |
User read and write, group and other read |
{user <r w x>} |
0700 |
User read, write, and execute |
{group <r x> other <r x> user <r w x>} |
0755 |
User all, group and other read and execute |
{<setuid> group <r x> other <r x> user <r w x>} |
4755 |
Set-user-ID with the 0755 access bits |
{<sticky> group <r w x> other <r w x> user <r w x>} |
1777 |
Shared directory, such as /tmp |
{} |
0000 |
No bits |
A permission map is the complete mask, not a patch.
An omitted class, bit, or special tag is false, so {} requests zero bits.
A bit can also be written false explicitly, as in {user <r !w>}.
An unknown member, a class that is not a map of booleans, a number, a string, and null produce an error when setting permissions.
A host that cannot represent a requested bit produces #err <fs unsupported>.
Returned permission maps contain only true bits and omit a class with no bits.
This keeps two results with the same mode equal, and lets a program compare a result with a written map:
(= (get (fs/stat "secret.key") "permissions") {user <r w>})
Permission maps do not describe file types, ACLs, or other platform attributes.
File types are the type member of fs/stat.
Host file attributes, such as append-only or immutable flags, are not part of this namespace.
A creation permissions option uses the same map.
On POSIX hosts, creation filters it through the process umask.
When the option is omitted, a file is requested with {group <r w> other <r w> user <r w>} and a directory with {group <r w x> other <r w x> user <r w x>}.
Windows has no POSIX permission bits.
There, fs/stat returns null permissions, creation uses the OS defaults, and an explicit permissions option or fs/chmod produces #err <fs unsupported>.
21.6.1. fs/chmod
Function(fs/chmod path permissions) → string
Sets the permission bits of path to the permission map and returns path.
Follows symbolic links and does not apply the umask.
Windows produces #err <fs unsupported>.
(fs/chmod "script.sh" {group <r x> other <r x> user <r w x>})
(fs/create-file "private.txt" {permissions {user <r w>}})
21.7. Deletion and symbolic links
Deletion does not follow the final symbolic link, and ignores trailing separators, so "link/" removes the link.
Deletion never descends through a symbolic link, including one substituted during traversal.
21.7.1. fs/remove
Function(fs/remove path) → null
Deletes a file, symbolic link, or empty directory and returns null.
A missing entry produces #err <fs missing>, and a nonempty directory produces #err <fs not-empty>.
21.7.2. fs/remove-if-exists
Function(fs/remove-if-exists path) → boolean
Deletes a file, symbolic link, or empty directory.
Returns true if it deleted the entry, or false if the entry was absent.
A nonempty directory or other failure produces an error.
21.7.3. fs/remove-all
Function(fs/remove-all path) → null
Deletes a file, symbolic link, or directory tree and returns null.
An absent path is accepted.
Does not follow symbolic links or change permissions to force deletion.
A host root, such as / or a drive root, produces #err <invalid value>, also when the path reaches it through a link, as link/. does for a link to /.
A failure can leave part of the tree deleted.
21.7.4. fs/symlink
Function(fs/symlink link target) → string
Creates a symbolic link at link that contains target, and returns link.
target need not exist.
A relative target is resolved against the link's parent when the link is followed.
An existing entry at link produces #err <fs exists>.
On Windows, creating a symbolic link can require a privilege or developer mode; a refusal produces #err <fs denied>.
21.7.5. fs/readlink
Function(fs/readlink path) → string
Returns the target text stored in the symbolic link at path.
Does not resolve the target or require it to exist.
A missing entry or an entry that is not a symbolic link produces an error.
21.8. Temporary resources
Temporary-file options are dir, prefix, suffix, and permissions.
Temporary-directory options omit suffix.
dir must already exist and defaults to the host temporary directory.
prefix defaults to "dust-" and suffix to "".
dir, prefix, and suffix must be strings, and a prefix or suffix must not contain a path separator or NUL character.
Creation is exclusive even when a candidate name collides.
Temporary resources are private by default.
On POSIX hosts, a file is requested with {user <r w>} and a directory with {user <r w x>}, filtered through the umask.
On Windows, the resource inherits the access control of dir, and an explicit permissions option produces #err <fs unsupported>.
An explicit permissions option replaces the requested default.
The functions do not arrange deletion at process exit.
21.8.1. fs/create-temp
Function(fs/create-temp) → string
(fs/create-temp opts) → string
Exclusively creates an empty file with a unique name and returns its absolute path.
21.8.2. fs/mkdir-temp
Function(fs/mkdir-temp) → string
(fs/mkdir-temp opts) → string
Exclusively creates a directory with a unique name and returns its absolute path.
21.8.3. fs/with-temp-dir
Function(fs/with-temp-dir f) → value
(fs/with-temp-dir f opts) → value
Creates a temporary directory, calls f with its absolute path, and deletes the tree afterwards.
Takes the same options as fs/mkdir-temp.
It is an ordinary function, not a binding form.
Cleanup runs after f returns, including when f returns an error value, and on cancellation.
Abrupt process termination can leave the directory in place.
Cleanup never follows symbolic links.
Returns the result of f after successful cleanup.
A cleanup failure after a successful call produces an error.
When both f and cleanup fail, the result is the error from f, with the cleanup failure attached as diagnostics.
If the temporary root was replaced, cleanup produces #err <fs replaced> and does not delete the replacement.
(fs/with-temp-dir
(fn [dir]
(fs/write (fs/join dir "input.txt") "hello")
(fs/read (fs/join dir "input.txt") {encoding <utf8>})))
; "hello"
22 Document Codecs
Notation decoders return an immutable Document without evaluating DUST forms. Text decoders accept strings; TRON accepts Bytes. Encoders return text for JSON, DUST, RON and EDN, or Bytes for TRON. Documents preserve types, comments and map order supported by the selected format. JSON uses tagged objects for DUST kinds; TRON preserves integer/float distinctions. Output layout follows each format, so source whitespace is not retained.
| Signature | Result |
|---|---|
(encoding/json/decode text [options]) |
Document |
(encoding/dust/decode text [options]) |
Document |
(encoding/ron/decode text [options]) |
Document |
(encoding/edn/decode text [options]) |
Document |
(encoding/tron/decode bytes [options]) |
Document |
(encoding/json/encode document [options]) |
Text |
(encoding/dust/encode document [options]) |
Text |
(encoding/ron/encode document [options]) |
Text |
(encoding/edn/encode document [options]) |
Text |
(encoding/tron/encode document [options]) |
Bytes |
(documents/from-value value [options]) |
Independent snapshot of a DUST value |
(documents/value document) |
Independent DUST value; changing it leaves the Document unchanged |
(documents/close document) |
Release its storage |
The existing encoding/encode and encoding/decode dispatchers also accept
format names "json", "dust", "ron", "edn" and "tron". Their
three-argument convention is (encoding/decode format input options);
all these functions put optional settings last. Byte/numeric codecs retain
their existing inputs and outputs. Use the form option to distinguish one
DUST value from a file of forms.
A function snapshot retains its definition and documentation as DUST source data. Reading the Document returns that source form without its captured values.
A named schema snapshot retains its finite definition graph, including named references and saved predicate definitions. A simple definition reads back as its canonical source form; a graph retains distinct definitions and their functions. Reconstruct it explicitly with schemas/load, then check candidates with schemas/valid?. Authored namespace source keeps its own comments. Snapshots made from evaluated schema values have no comments and do not include captured runtime state, compiled checkers, caches, or runtime handles.
Options are comments (default true), form (default true), width
(1–65535), order ("source" or "sorted", default sorted), schema and
presentation. With form false, DUST reads/writes a file of forms as a
root list. With form true, a root list keeps its brackets. comments false
omits annotations without changing the source Document or removing ordinary
$comment data fields. Width/order configure DUST and RON; EDN also honors
width. JSON uses compact source order. TRON output is binary.
For DUST and RON, schema is a named schema snapshot and presentation is a
map of explicit JSON Pointer hints. Without an explicit order, a schema
selects its shape declaration order. An explicit source or sorted order takes
precedence and ignores schema presentation. A hint can contain order (a list
of field names) and lines (true to put each child of that collection on its
own line). The empty string names the root path. JSON and TRON keep their
existing encodings.
(defschema Shipment
{pilot string? destination string? spice int?})
(let
[document
(documents/from-value
{spice 80 destination "Arrakeen" pilot "Chani"})
rendered (encoding/dust/encode document {schema Shipment})]
(documents/close document)
rendered)
; Rendered DUST uses Shipment's field order.
Explicit hints override schema order:
(let
[document (documents/from-value {pilot "Chani" spice 80 destination "Arrakeen"})
rendered
(encoding/dust/encode document
{schema Shipment presentation {"" {order ["spice" "pilot" "destination"]}}})]
(documents/close document)
rendered)
Composition rules apply at each nested path. meet keeps the first appearance
of each field, and join uses a common order only when all alternatives agree.
Rendering does not run predicates to select a layout. Boolean members use ordinary
key/value spelling when a leading tag group would violate the chosen field order.
Without presentation overrides, the normal canonical tag grouping is unchanged.
A hint inside a template or dynamic pointer uses its explicit tagged spelling
when the compact text spelling would hide the target collection.
(defschema Shipment {pilot string? destination string? spice int?}) (defschema Person [meet {age int?} {name string?}]) (defschema UnionSame [join {a string? b int?} {a string? b int?}]) (defschema UnionDifferent [join {a string? b int?} {b int? a string?}]) (defschema NestedIntersection [meet {details {z int?}} {details {a int?}}]) (defschema NestedUnion [join {details {a int? z int?}} {details {z int? a int?}}]) (defschema House {name string? children [... House]}) (let [render (fn [value options] (let [document (documents/from-value value) output (encoding/dust/encode document options)] (documents/close document) output)) render-document (fn [document options] (let [output (encoding/dust/encode document options)] (documents/close document) output)) value {spice 80 destination "Arrakeen" pilot "Chani" extra "kept"}] [(render value {schema Shipment}) (render value {schema Shipment presentation {"" {order ["spice" "pilot" "destination"]}}}) (render-document (encoding/dust/decode ""{spice 80 destination "Arrakeen" pilot "Chani" extra "kept"}"") {schema Shipment order "source"}) (render value {schema Shipment order "sorted"}) (render value {presentation {"" {order ["spice" "destination" "pilot"]}}}) (render {steps [{a "x" b 1}]} {presentation {"" {order ["steps"]} /steps <lines> /steps/0 {order ["b" "a"]}}}) (render {name "Paul" age 18} {schema Person}) (render {a "x" b 1} {schema UnionSame}) (render {a "x" b 1} {schema UnionDifferent}) (render {details {a 1 z 2}} {schema NestedIntersection}) (render {details {a 1 z 2}} {schema NestedUnion}) (render [[1 2]] {presentation {/0 <lines>}}) (render ~"hello ,{a 1 z 2}" {presentation {/1/0 {order ["z" "a"] lines true}}}) (render-document (encoding/dust/decode "/x/,{a 1 z 2}" {form true}) {presentation {/1 {order ["z" "a"] lines true}}}) (render {name "Chani" active true} {presentation {"" {order ["name" "active"]}}}) (render {b true a false c true} {presentation {"" {order ["c" "b"]}}}) (render {name "Atreides" children [{name "Paul" children []}]} {schema House}) (render {pilot "Chani"} {schema Shipment}) (render-document (encoding/dust/decode """ {pilot "Chani" ; pilot note destination "Arrakeen"} """ ) {schema Shipment})])
(defschema Shipment {destination string? pilot string? spice int?}) (defschema Person [meet {age int?} {name string?}]) (defschema UnionSame [join {a string? b int?} {a string? b int?}]) (defschema UnionDifferent [join {a string? b int?} {a string? b int?}]) (defschema NestedIntersection [meet {details {z int?}} {details {a int?}}]) (defschema NestedUnion [join {details {a int? z int?}} {details {a int? z int?}}]) (defschema House {children [... House] name string?}) (let [render (fn [value options] (let [document (documents/from-value value) output (encoding/dust/encode document options)] (documents/close document) output)) render-document (fn [document options] (let [output (encoding/dust/encode document options)] (documents/close document) output)) value {destination "Arrakeen" extra "kept" pilot "Chani" spice 80}] [(render value {schema Shipment}) (render value {presentation {"" {order ["spice" "pilot" "destination"]}} schema Shipment}) (render-document (encoding/dust/decode ""{spice 80 destination "Arrakeen" pilot "Chani" extra "kept"}"") {order "source" schema Shipment}) (render value {order "sorted" schema Shipment}) (render value {presentation {"" {order ["spice" "destination" "pilot"]}}}) (render {steps [{a "x" b 1}]} {presentation {"" {order ["steps"]} /steps <lines> /steps/0 {order ["b" "a"]}}}) (render {age 18 name "Paul"} {schema Person}) (render {a "x" b 1} {schema UnionSame}) (render {a "x" b 1} {schema UnionDifferent}) (render {details {a 1 z 2}} {schema NestedIntersection}) (render {details {a 1 z 2}} {schema NestedUnion}) (render [[1 2]] {presentation {/0 <lines>}}) (render ~"hello ,{a 1 z 2}" {presentation {/1/0 {<lines> order ["z" "a"]}}}) (render-document (encoding/dust/decode "/x/,{a 1 z 2}" <form>) {presentation {/1 {<lines> order ["z" "a"]}}}) (render {<active> name "Chani"} {presentation {"" {order ["name" "active"]}}}) (render <!a b c> {presentation {"" {order ["c" "b"]}}}) (render {children [{children [] name "Paul"}] name "Atreides"} {schema House}) (render {pilot "Chani"} {schema Shipment}) (render-document (encoding/dust/decode """ {pilot "Chani" ; pilot note destination "Arrakeen"} """ ) {schema Shipment})])
Shipment Person UnionSame UnionDifferent NestedIntersection NestedUnion House [ """ {pilot "Chani" destination "Arrakeen" spice 80 extra "kept"} """ """ {spice 80 pilot "Chani" destination "Arrakeen" extra "kept"} """ """ {spice 80 destination "Arrakeen" pilot "Chani" extra "kept"} """ """ {destination "Arrakeen" extra "kept" pilot "Chani" spice 80} """ """ {spice 80 destination "Arrakeen" pilot "Chani" extra "kept"} """ """ {steps [ {b 1 a "x"}]} """ """ {age 18 name "Paul"} """ """ {a "x" b 1} """ """ {a "x" b 1} """ """ {details {z 2 a 1}} """ """ {details {a 1 z 2}} """ """ [[ 1 2]] """ """ #template [[ "hello " ""] [{ z 2 a 1}]] """ """ #jsonptr ["x" { z 2 a 1}] """ """ {name "Chani" active true} """ """ <c b !a> """ """ {name "Atreides" children [{name "Paul" children []}]} """ """ {pilot "Chani"} """ """ { ; pilot note pilot "Chani" destination "Arrakeen"} """ ]
JSON and TRON read and write all comments in the root $comment member, and
a $comment below the root is data. A root $comment that is not an object
of pointers to strings, or that names no value, is an error, and so is a
root map with its own $comment key written to JSON or TRON. Unrepresentable data, malformed input and unsupported settings produce
errors; memory/resource limits remain fatal evaluation failures.
Documents cannot be printed or serialized; encode their contents instead.
A session can hold any number of open Documents; only the memory budget
bounds them. Close unused Documents with documents/close, which returns
their memory to the budget. A failed evaluation closes Documents it created. Ending the
session closes the remaining Documents. Documents count toward the memory
budget. A decode takes input of any size. It fails only when the memory budget
runs out or a value passes the value size bound.
No filesystem or OS grant is required.
(let [doc (encoding/json/decode "{\"name\":\"Paul\"}") value (documents/value doc) closed (documents/close doc)] value) (let [value {name "Chani" skills <desert survival> scores [1 2.5]} doc (documents/from-value value) results (map (fn [format] (let [wire (encoding/encode format doc) other (encoding/decode format wire {<comments>}) result (= value (documents/value other)) closed (documents/close other)] result)) ["json" "dust" "ron" "edn" "tron"]) closed (documents/close doc)] results) (let [source {name "Paul"} doc (documents/from-value source) changed (put source "name" "Muad'Dib") value (documents/value doc) closed (documents/close doc)] value) (let [doc (encoding/json/decode (str "{\"$comment\":\"" "{\\\"/name\\\":\\\"note\\\"}" "\",\"name\":\"Paul\"}")) text (encoding/json/encode doc) closed (documents/close doc)] text) (let [doc (encoding/dust/decode "; about Paul\n{name \"Paul\"}\n") text (encoding/json/encode doc) copy (encoding/json/decode text) dust (encoding/dust/encode copy) a (documents/close doc) b (documents/close copy)] dust) (let [doc (encoding/dust/decode "(+ 1 2)") value (encoding/dust/encode doc) closed (documents/close doc)] value) (let [doc (encoding/dust/decode "[1 2]") closed (documents/close doc)] (error? (documents/value doc))) (error? (encoding/json/decode "{")) (let [doc (encoding/json/decode "{\"x\":{\"$comment\":\"literal data\"},\"name\":\"Paul\"}") encoded (encoding/dust/encode doc {comments false}) closed (documents/close doc)] (not (null? (strings/index-of encoded "$comment")))) (let [doc (encoding/dust/decode "; retained note\n{a 1}\n") plain (encoding/dust/encode doc {comments false}) original (encoding/dust/encode doc) closed (documents/close doc)] [(null? (strings/index-of plain "retained note")) (not (null? (strings/index-of original "retained note")))]) (let [doc (encoding/dust/decode "1") refused (error? (encoding/json/encode doc {<comment-roundtrip>})) closed (documents/close doc)] refused) (let [doc (encoding/dust/decode "; Spice math.\n{rates {arrakis 10 caladan 15}\n ; reserve percent\n reserve 10}\n") commented (encoding/json/encode doc) plain (encoding/json/encode doc {comments false}) closed (documents/close doc)] [commented plain])
(let [doc (encoding/json/decode ""{"name":"Paul"}"") value (documents/value doc) closed (documents/close doc)] value) (let [value {name "Chani" scores [1 2.5] skills <desert survival>} doc (documents/from-value value) results (map (fn [format] (let [wire (encoding/encode format doc) other (encoding/decode format wire <comments>) result (= value (documents/value other)) closed (documents/close other)] result)) ["json" "dust" "ron" "edn" "tron"]) closed (documents/close doc)] results) (let [source {name "Paul"} doc (documents/from-value source) changed (put source "name" "Muad'Dib") value (documents/value doc) closed (documents/close doc)] value) (let [doc (encoding/json/decode (str ""{"$comment":""" ""{\u005c"/name\u005c":\u005c"note\u005c"}"" """ ","name":"Paul"} """ )) text (encoding/json/encode doc) closed (documents/close doc)] text) (let [doc (encoding/dust/decode """ ; about Paul {name "Paul"} """ ) text (encoding/json/encode doc) copy (encoding/json/decode text) dust (encoding/dust/encode copy) a (documents/close doc) b (documents/close copy)] dust) (let [doc (encoding/dust/decode "(+ 1 2)") value (encoding/dust/encode doc) closed (documents/close doc)] value) (let [doc (encoding/dust/decode "[1 2]") closed (documents/close doc)] (error? (documents/value doc))) (error? (encoding/json/decode "{")) (let [doc (encoding/json/decode ""{"x":{"$comment":"literal data"},"name":"Paul"}"") encoded (encoding/dust/encode doc <!comments>) closed (documents/close doc)] (not (null? (strings/index-of encoded "$comment")))) (let [doc (encoding/dust/decode """ ; retained note {a 1} """ ) plain (encoding/dust/encode doc <!comments>) original (encoding/dust/encode doc) closed (documents/close doc)] [(null? (strings/index-of plain "retained note")) (not (null? (strings/index-of original "retained note")))]) (let [doc (encoding/dust/decode "1") refused (error? (encoding/json/encode doc <comment-roundtrip>)) closed (documents/close doc)] refused) (let [doc (encoding/dust/decode """ ; Spice math. {rates {arrakis 10 caladan 15} ; reserve percent reserve 10} """ ) commented (encoding/json/encode doc) plain (encoding/json/encode doc <!comments>) closed (documents/close doc)] [commented plain])
{name "Paul"} [true true true true true] {name "Paul"} ""{"$comment":"{\u005c"/name\u005c":\u005c"note\u005c"}","name":"Paul"}"" """ ; about Paul {name "Paul"} """ """ (+ 1 2) """ true true true [true true] true [ ""{"$comment":"{\u005c"\u005c":\u005c"Spice math.\u005c",\u005c"/reserve\u005c":\u005c"reserve percent\u005c"}","rates":{"arrakis":10,"caladan":15},"reserve":10}"" ""{"rates":{"arrakis":10,"caladan":15},"reserve":10}""]
23 Processes, Streams and Script Utilities
stardust run FILE -- ARG... executes a script with filesystem, process, stream,
network and terminal access. It prints only explicit output; it is
stardust eval --quiet, and stardust eval also prints the result of each
form. A returned #err ends the script with status 1; (processes/exit 7)
ends it with status 7. A shebang on the first line is accepted. A script uses
a library file with import: (import {nrepl "lib/nrepl"}) in
tools/client.dust names tools/lib/nrepl.dust (Files).
These features also work with database storage (Script runner). Plugin selection controls which services
are available, including secure randomness.
The io plugin enables these services in eval, run, repl and nrepl.
The CLI selects it, with its capabilities, unless --config names a
configuration without it. Embedded hosts select grants for
each evaluation. Captured functions and retained handles do not retain grants.
These grants permit OS access; they are not a filesystem or process sandbox.
Process, I/O, TCP and terminal operations currently support Linux.
Process creation requires Linux 5.11 or later.
Other hosts return #err <script unsupported>. Pure utilities remain available.
23.1. Processes
| Signature | Result |
|---|---|
(processes/run argv [options]) |
Captured output and final status; closes the child |
(processes/start argv [options]) |
A process record with opaque process, stdin, stdout and stderr handles |
(processes/poll child) |
Current status without waiting |
(processes/wait child [options]) |
Exit status, or timeout without killing the child |
(processes/communicate child [input [options]]) |
Concurrent input/output and final status; closes the child |
(processes/close child) |
Kill its remaining process group, reap, close its pipes |
(processes/signal child number) |
Send signal 1–64 to the child |
(processes/kill child) |
Send SIGKILL to the child |
(processes/signal-group positive-group-id number) |
Signal an OS process group |
(processes/exit [code]) |
End script evaluation, default status 0 |
(processes/on-exit f) |
Register a zero-argument shutdown hook; return null |
(processes/shell/quote text) |
One quoted POSIX shell argument; does not execute it |
argv is a nonempty list of strings, passed directly without a shell.
Use an explicit shell argv when needed. processes/shell/quote quotes one POSIX
shell argument; it does not execute it.
Start/run options are cwd, env, clear-env, stdin, stdout, stderr,
session, terminal and disable-core-dumps. Boolean options accept booleans
or tag syntax, such as {<clear-env>}. env is a map of text values; null
removes an inherited name. clear-env defaults to false. Executables without
slashes are resolved using the child's PATH. cwd defaults to the session's
current directory. Child core dumps are disabled by default.
A stream option attaches an existing opaque stream instead of creating a pipe.
terminal must be a PTY handle and also creates a session with that controlling
terminal. Every child has its own process group. terminals/start-session has
the same arguments as processes/start and always creates a session.
Only processes/run also accepts input and timeout in its options.
processes/communicate accepts input separately. Input is text or Bytes; output
is always Bytes. Input cannot be combined with an attached stdin stream.
Both drain stdout and stderr while writing input, avoiding the
usual full-pipe deadlock. They return status, pid, code, signal, stdout
and stderr. status is <exited>, <signaled> or <timeout>; poll can also
return <running>. code or signal is null when unavailable. Timeout output
contains the bytes captured so far; cleanup kills any remaining group members.
wait and communicate options contain only timeout, a nonnegative duration.
No timeout means wait until completion or cancellation; zero means an immediate
deadline. A timed-out wait leaves the process usable. wait alone does not
drain pipes: use communicate when output could fill them. poll and wait
retain the exit status until close or communicate releases the child.
(def child (processes/start ["/bin/sh" "-c" "cat; printf diagnostic >&2"]))
; communicate feeds input while draining both outputs. It closes the child.
(def result (processes/communicate child "Arrakis\n" {timeout #dur "PT60S"}))
(tests/equal <exited> (get result "status"))
(tests/equal 0 (get result "code"))
(io/stdout/print (encoding/decode "utf8" (get result "stdout")))
(io/stderr/println (encoding/decode "utf8" (get result "stderr")))
| Signature | Behavior |
|---|---|
(processes/env/get name) |
Text or null if absent |
(processes/env/all) |
Snapshot of the host environment |
(processes/cwd/get) |
Current session directory |
(processes/cwd/set path) |
Validate and set session directory; return its absolute path |
The current directory belongs to the session. It affects child creation and
relative fs/ paths without changing the host process directory. Environment
operations only read the host environment; overrides are per child.
23.1.1. Shutdown hooks
(processes/on-exit f) registers a zero-argument function and returns null.
stardust eval and stardust run call hooks in reverse registration order before closing streams
and terminating owned child processes. Hooks run after normal completion,
processes/exit, evaluation errors, and handled INT, TERM, HUP or QUIT signals.
They retain captured values and the script's OS access.
(processes/on-exit (fn [] (io/stdout/println "first")))
(processes/on-exit (fn [] (io/stdout/println "second")))
(io/stdout/println "body")
This prints body, then second, then first. A hook error is reported and
the remaining hooks still run. An otherwise successful script then exits with
status 1; an existing nonzero status or terminating signal is preserved.
Registering hooks or calling processes/exit during shutdown is an error.
The complete shutdown phase shares a one-second wall-time and CPU budget, or the script's lower configured CPU budget. The script's memory budget still applies. Exhaustion or cancellation can stop the remaining hooks. Blocking file/device operations can delay cancellation until they return. SIGKILL and other forced process termination cannot run hooks.
23.2. Streams and TCP
| Signature | Behavior |
|---|---|
(io/read stream count [options]) |
At most count Bytes, null at EOF |
(io/write stream text-or-bytes [options]) |
Number of bytes written, possibly partial |
(io/wait-readable stream [options]) |
Boolean; EOF also counts as readable |
(io/close stream) |
Close the handle |
(io/open path) |
Open a file as a read-only stream |
(io/stdin/open) |
Open a persistent standard-input stream |
(io/stdin/read [count [options]]) |
Read standard input; default maximum 65536 Bytes |
(io/stdout/print values...) |
Concatenate str representations to stdout |
(io/stdout/println values...) |
As print, followed by newline |
(io/stderr/print values...) |
As print, to stderr |
(io/stderr/println values...) |
As println, to stderr |
(net/tcp/connect host port [options]) |
A bidirectional stream |
Options contain only timeout. A read/write timeout is #err <script timeout>;
wait-readable instead returns false. A zero-count read returns empty Bytes,
not EOF. Each call writes at most 4096 bytes; loop over the remaining
bytes. Text is UTF-8; Bytes can contain arbitrary octets. TCP supports literal
IPv4, literal IPv6 and "localhost", with a separate port 1–65535. DNS lookup
is not implemented. TCP connection timeout also returns a script timeout error.
23.2.1. Buffered readers
Use a buffered reader to process input incrementally. It retains unread bytes between calls instead of reading the whole input into a list.
| Signature | Behavior |
|---|---|
(io/reader [source [options]]) |
Buffer a stream or file path; omitted or null source opens stdin |
(io/read reader count [options]) |
At most count Bytes; consume buffered bytes first |
(io/read-line reader [options]) |
Next UTF-8 line without its terminator; null at EOF |
(io/peek reader count [options]) |
Up to count Bytes without consuming them; null at EOF |
(io/discard reader count [options]) |
Consume up to count bytes; return the number discarded |
(io/reduce-lines f initial reader [options]) |
Call (f accumulator line) for each remaining line |
(io/close reader) |
Release buffered data and close an owned source |
Constructor options contain only buffer-size, a positive byte count; the
default is 65536. peek requires a count no larger than buffer-size and
returns fewer bytes only at EOF. Zero-count read and peek return empty Bytes.
Discard returns zero at EOF. Counts must be integers from 0 through 2147483647.
Read-line accepts LF, CRLF and CR terminators. Blank lines return an empty string. A final unterminated line is returned once; a final terminator does not create another line. Lines can exceed the buffer size and are bounded by the session's memory budget. Invalid UTF-8 returns an error; byte reads accept any octets. A line terminator, including both bytes of CRLF, is consumed before the next read, peek or discard.
Operation options contain only timeout, applied separately to each underlying
read. A timed-out line read retains its partial line for a retry. Discard can
advance before a timeout. A reducer returns its final accumulator or stops at
an error returned by f. It does not close the reader.
A reader opened from a path or stdin owns its stream. A reader constructed from an existing stream borrows it; closing that reader leaves the stream open. Use the reader exclusively while it is active: direct reads from its source would bypass buffered bytes. Close the reader before closing or draining its source through process operations. Readers cannot be serialized or moved to another session. File paths follow the session's current directory and require filesystem access as well as stream access.
This script counts standard-input lines without retaining their contents:
; Count lines incrementally without retaining a list of their contents.
(def reader (io/reader))
(def total (io/reduce-lines (fn [n line] (+ n 1)) 0 reader))
(io/close reader)
(io/stdout/println total)
For a file, use (io/reader "names.txt"). For subprocess output, use
(io/reader (get child /stdout)). The same operations accept a reader over a
TCP stream returned by net/tcp/connect.
23.2.2. Framed input
Import lib/nrepl.dust, as (import {nrepl "../lib/nrepl"}) does in a script
of tools/. It exports:
| Signature | Result |
|---|---|
(nrepl/read-frame reader [options]) |
The next wire dictionary as Bytes, or null at EOF |
(nrepl/read-message reader [options]) |
The next dictionary as a map with UTF-8 text values |
(nrepl/write-message writer message [options]) |
Send a dictionary, completing partial writes |
Readers and writers follow the bencode stream rules above. Options contain
timeout. Reading never consumes the next frame; a buffered reader keeps any
bytes fetched ahead. One request can produce multiple replies: read through
the reply whose status contains "done". These helpers do not close streams.
This example sends an evaluation to a local nREPL server. Pass its port as the
script argument and load lib/nrepl.dust:
; Run with a local nREPL server's port.
(import {nrepl "../../lib/nrepl"})
(def port (int (get (cli/args) 0)))
(def socket (net/tcp/connect "127.0.0.1" port {timeout #dur "PT60S"}))
(def reader (io/reader socket))
(tests/assert (> (nrepl/write-message socket {op "eval" id "example" code "(+ 1 2 3)"}) 0))
(def value (nrepl/read-message reader {timeout #dur "PT60S"}))
(tests/equal "example" (get value /id))
(tests/equal "6" (get value /value))
(def complete (nrepl/read-message reader {timeout #dur "PT60S"}))
(tests/equal ["done"] (get complete /status))
(io/close reader)
(io/close socket)
(io/stdout/println "6")
23.3. Terminal and job control
| Signature | Behavior |
|---|---|
(terminals/pty/open) |
{master handle slave handle} |
(terminals/start-session argv [options]) |
Start a process in a new session |
(terminals/foreground-group stream [group-id]) |
Get/set foreground process group |
(terminals/attributes stream [attributes]) |
Get/update termios attributes |
(terminals/resize stream dimensions) |
Set rows and columns, each 1–65535 |
(terminals/character-width text) |
Grapheme display width |
Attributes are input, output, control and local integer flag words,
input-speed and output-speed OS baud constants, and controls Bytes.
The getter returns a complete map suitable for restoration. A setter changes
only the supplied fields. Setting a foreground group requires membership in
that terminal's session, as enforced by the OS. PTY operations change that terminal, not the host's
interactive terminal. character-width requires no terminal capability.
(def pty (terminals/pty/open))
(def original (terminals/attributes (get pty "slave")))
(terminals/resize (get pty "master") {rows 24 columns 80})
(def child
(terminals/start-session ["/bin/sh" "-c" "test -t 0 && printf Ready"]
{terminal (get pty "slave")
stdin (get pty "slave")
stdout (get pty "slave")
stderr (get pty "slave")}))
(io/close (get pty "slave"))
(tests/equal "Ready" (encoding/decode "utf8" (io/read (get pty "master") 5 {timeout #dur "PT60S"})))
(tests/equal 0 (get (processes/wait child {timeout #dur "PT60S"}) "code"))
(processes/close child)
(io/close (get pty "master"))
23.4. Resource ownership and interruption
Each session permits at most 128 streams and 32 child processes.
Handles cannot be serialized or used in another session.
Close is explicit; a second close is an error. Unattached standard streams
are private pipes. Attaching an existing stream does not transfer its ownership.
communicate and process cleanup close only the private pipes they created.
Ending a session closes its streams and terminates its child process groups. A failed evaluation releases resources it created; earlier resources remain open until closed or the session ends. Filesystem changes and other OS effects already performed remain in place. I/O buffers count toward the memory budget. Cancellation can wait for a file or device operation to complete.
The CLI forwards INT, TERM, HUP and QUIT to owned groups and waits for each
child to exit. A child that has not exited after 2 seconds receives SIGKILL.
The CLI then terminates by that signal.
23.5. Arguments, timing and checks
| Signature | Behavior |
|---|---|
(cli/args) |
Script arguments, excluding executable and script path |
(scripts/path) |
Absolute script path, or empty text outside a configured script |
(cli/parse specification [argv]) |
{options {...} arguments [...]}; argv defaults to cli/args and requires io when omitted |
(cli/command specification [argv]) |
Named positional arguments and options in one map; handles help and usage exits |
(cli/format-opts options) |
Sorted option help, including descriptions, defaults and the reserved help option |
(time/monotonic) |
Monotonic duration for elapsed-time subtraction |
(time/sleep duration) |
Cancellable nonnegative delay |
(formats/csv/row values) |
CSV row with quoting and CRLF terminator |
(stats/median numbers) |
Sorted-copy median, preserving input |
(tests/assert value [message]) |
Value on success; fatal assertion on false, null or error |
(tests/equal expected actual [message]) |
True or fatal assertion |
(tests/fail [message]) |
Fatal assertion |
Each cli/parse option has type (<string> by default, <int>, <float>
or <boolean>), optional one-character short, default, required and
multiple. desc supplies help text. Multiple options collect a list and cannot have a default.
Long options accept --count=10 or --count 10; short options can cluster,
such as -vn10. -- ends option parsing. Unknown, missing and repeated
non-multiple options are errors. Int parsing checks the full signed 64-bit
range; float parsing rejects infinities and NaNs.
cli/command adds the script entry-point behavior. Its specification has a
required name and optional doc, args (positional names), variadic and
options (the same specification as cli/parse). Positional names are required;
with <variadic>, the last name collects one or more remaining arguments.
Names must be unique across options and positional arguments. The returned
map contains named arguments and parsed option values together.
(cli/command
{name "verify.dust"
args ["directory" "logs"]
<variadic>
options {count {short "n" type <int> default 3 desc "Repetitions"}}}
["-n5" "suite" "first.log" "second.log"])
; {count 5 directory "suite" logs ["first.log" "second.log"]}
Omit argv in a script to read its command-line arguments. -h and --help
print generated usage, documentation and option help, then exit with status 0.
They are reserved by cli/command. -- ends option parsing, allowing a literal
--help positional argument. Argument errors print a diagnostic and usage to
stderr and exit with status 2. Invalid command definitions produce ordinary
errors; resource limits remain fatal. cli/parse continues to return errors
without printing or requesting an exit.
An option's validate field accepts an ordinary function or a map containing
pred and an optional message. Validation runs after all type conversions
succeed, in option-name order. It checks defaults and false boolean values;
missing optional values and absent repeated options are skipped. A repeated
option supplies its complete list to the predicate.
(cli/command
{name "generate.dust"
options {iterations {type <int>
default 100
validate {pred (fn [n] (and (> n 0) (= 0 (rem n 2))))
message "must be positive and even"}}}}
["--iterations" "10"])
; {iterations 10}
A false or null predicate result rejects the value. For example,
--iterations 3 reports --iterations: must be positive and even; got 3,
prints usage, and requests exit status 2. Without a custom message, the text
is validation failed. An error returned by the predicate propagates through
cli/parse; cli/command reports it as an argument failure. Assertions,
cancellation and resource failures remain fatal and retain their original
status. Predicates can capture lexical bindings.
cli/format-opts shows option descriptions and defaults without running them.
{typed (cli/parse {count {type <int> validate (fn [n] (> n 0))}} ["--count" "5"]) default (cli/parse {count {type <int> default 4 validate (fn [n] (= 0 (rem n 2)))}} []) rejected-default (cli/parse {count {type <int> default 3 validate {pred (fn [n] (= 0 (rem n 2))) message "must be even"}}} []) rejected (cli/parse {count {type <int> validate (fn [n] (> n 0))}} ["--count" "0"]) predicate-error (cli/parse {count {type <int> validate (fn [n] (/ n 0))}} ["--count" "5"]) callback-closure (let [minimum 3] (cli/parse {count {type <int> validate (fn [n] (> n minimum))}} ["--count" "5"])) missing (let [calls []] [(cli/parse {count {type <int> validate (fn [n] (lists/append calls n) true)}} []) calls]) false-default (cli/parse {flag {type <boolean> validate (fn [value] (not value))}} []) multiple (cli/parse {item {<multiple> validate (fn [values] (= 2 (count values)))}} ["--item" "Paul" "--item" "Chani"]) bad-predicate (cli/parse {count {validate {pred 42}}} []) bad-message (cli/parse {count {validate {pred :int? message 42}}} []) unknown (cli/parse {count {validate {pred :int? typo true}}} []) command (cli/command {name "example" options {count {type <int> default 4 validate {pred (fn [n] (= 0 (rem n 2))) message "must be even"}}}} []) type-before-predicate (let [calls []] [(cli/parse {count {type <int> validate (fn [n] (lists/append calls n) true)}} ["--count" "wrong"]) calls]) false-message (cli/parse {count {validate {pred :int? message false}}} []) missing-multiple (let [calls []] [(cli/parse {item {<multiple> validate (fn [xs] (lists/append calls xs) true)}} []) calls])}
{bad-message (cli/parse {count {validate {message 42 pred :int?}}} []) bad-predicate (cli/parse {count {validate {pred 42}}} []) callback-closure (let [minimum 3] (cli/parse {count {type <int> validate (fn [n] (> n minimum))}} ["--count" "5"])) command (cli/command {name "example" options {count {default 4 type <int> validate {message "must be even" pred (fn [n] (= 0 (rem n 2)))}}}} []) default (cli/parse {count {default 4 type <int> validate (fn [n] (= 0 (rem n 2)))}} []) false-default (cli/parse {flag {type <boolean> validate (fn [value] (not value))}} []) false-message (cli/parse {count {validate {<!message> pred :int?}}} []) missing (let [calls []] [(cli/parse {count {type <int> validate (fn [n] (lists/append calls n) true)}} []) calls]) missing-multiple (let [calls []] [(cli/parse {item {<multiple> validate (fn [xs] (lists/append calls xs) true)}} []) calls]) multiple (cli/parse {item {<multiple> validate (fn [values] (= 2 (count values)))}} ["--item" "Paul" "--item" "Chani"]) predicate-error (cli/parse {count {type <int> validate (fn [n] (/ n 0))}} ["--count" "5"]) rejected (cli/parse {count {type <int> validate (fn [n] (> n 0))}} ["--count" "0"]) rejected-default (cli/parse {count {default 3 type <int> validate {message "must be even" pred (fn [n] (= 0 (rem n 2)))}}} []) type-before-predicate (let [calls []] [(cli/parse {count {type <int> validate (fn [n] (lists/append calls n) true)}} ["--count" "wrong"]) calls]) typed (cli/parse {count {type <int> validate (fn [n] (> n 0))}} ["--count" "5"]) unknown (cli/parse {count {validate {<typo> pred :int?}}} [])}
{bad-message #err {<mismatch type> message "validation message must be a string"} bad-predicate #err {<expected function> message "expected a function value"} callback-closure {arguments [] options {count 5}} command {count 4} default {arguments [] options {count 4}} false-default {arguments [] options <!flag>} false-message #err {<mismatch type> message "validation message must be a string"} missing [{arguments [] options {count null}} []] missing-multiple [{arguments [] options {item []}} []] multiple {arguments [] options {item ["Paul" "Chani"]}} predicate-error #err {<division integer zero> message "division by zero"} rejected #err {<invalid value> message "--count: validation failed; got 0"} rejected-default #err {<invalid value> message "--count: must be even; got 3"} type-before-predicate [#err {<invalid value> message "invalid command-line option value"} []] typed {arguments [] options {count 5}} unknown #err {<invalid value> message "unknown validation field"}}
{ case0 (cli/command {name "check" args ["directory" "logs"] <variadic> options {count {type <int> short "n" default 3 desc "Repetitions"}}} ["-n5" "suite" "one.log" "two.log"]) case1 (cli/command {name "check" args ["input"] options {verbose {type <boolean> short "v"}}} ["-v" "file.dust"]) case2 (cli/command {name "check" args ["input"]} ["--" "--help"]) case3 (cli/format-opts {count {type <int> short "n" default 3 desc "Repetitions"}}) case4 (cli/command {name "check" args ["same" "same"]} []) case5 (cli/command {name "check" args ["input"] options {input {}}} []) case6 (cli/command {name "check" <variadic>} []) case7 (cli/command {name "check" options {help {}}} []) case8 (cli/command {name "check" options {verbose {short "h"}}} []) case9 (cli/command {name "check" variadic "yes"} []) case10 (cli/format-opts {count {desc 42}}) case11 (cli/parse {count {desc "Repetitions" type <int>}} ["--count" "5"]) }
{case0 (cli/command {<variadic> args ["directory" "logs"] name "check" options {count {default 3 desc "Repetitions" short "n" type <int>}}} ["-n5" "suite" "one.log" "two.log"]) case1 (cli/command {args ["input"] name "check" options {verbose {short "v" type <boolean>}}} ["-v" "file.dust"]) case10 (cli/format-opts {count {desc 42}}) case11 (cli/parse {count {desc "Repetitions" type <int>}} ["--count" "5"]) case2 (cli/command {args ["input"] name "check"} ["--" "--help"]) case3 (cli/format-opts {count {default 3 desc "Repetitions" short "n" type <int>}}) case4 (cli/command {args ["same" "same"] name "check"} []) case5 (cli/command {args ["input"] name "check" options {input {}}} []) case6 (cli/command {<variadic> name "check"} []) case7 (cli/command {name "check" options {help {}}} []) case8 (cli/command {name "check" options {verbose {short "h"}}} []) case9 (cli/command {name "check" variadic "yes"} [])}
#cases [{output {count 5 directory "suite" logs ["one.log" "two.log"]} select "case0"} {output {<verbose> input "file.dust"} select "case1"} {output {input "--help"} select "case2"} {output " -n, --count VALUE Repetitions (default: 3)\n -h, --help Show this help" select "case3"} {output #err <invalid value> select "case4"} {output #err <invalid value> select "case5"} {output #err <invalid value> select "case6"} {output #err <invalid value> select "case7"} {output #err <invalid value> select "case8"} {output #err <mismatch type> select "case9"} {output #err <mismatch type> select "case10"} {output {arguments [] options {count 5}} select "case11"}]
median requires a nonempty list of one numeric kind. An odd median preserves
the kind; an even median returns a float. CSV cells may be text, numbers,
booleans or null. Use the existing format function for numeric precision.
Assertions and processes/exit terminate evaluation even inside ordinary
error-handling forms; embedded hosts receive a evaluation error, never OS exit.
(cli/parse {count {short "n" type <int> default 3} verbose {short "v" type <boolean>}} ["-vn10" "dune.dust"]) (processes/shell/quote "Paul's book") (formats/csv/row ["Atreides, Paul" 42 true null]) (stats/median [9 1 5]) (format "%.3f" (stats/median [1.0 2.0])) (terminals/character-width "é界😀") (tests/equal 3 (stats/median [5 3 1]))
(cli/parse {count {default 3 short "n" type <int>} verbose {short "v" type <boolean>}} ["-vn10" "dune.dust"]) (processes/shell/quote "Paul's book") (formats/csv/row [ "Atreides, Paul" 42 true null]) (stats/median [9 1 5]) (format "%.3f" (stats/median [1.0 2.0])) (terminals/character-width "é界😀") (tests/equal 3 (stats/median [5 3 1]))
{arguments ["dune.dust"] options {<verbose> count 10}} "'Paul'\\''s book'" """ "Atreides, Paul",42,true,\r """ 5 "1.500" 5 true
Appendix A: Function Index
- != — Is another name for comparisons/not=. It takes the same
arguments and returns the same results and errors.
(!= value more*) → boolean - * — Returns the product of its arguments.
(*) → integer
(* value) → value
(* value other more*) → value - + — Returns the sum of its arguments.
(+) → integer
(+ value) → value
(+ value other more*) → value - - — With one argument, returns its negation.
With additional arguments, subtracts each from the running result in order.
At least one argument is required. Numeric operands follow the arithmetic rules
above; temporal operands use the combinations in the table.
Integer overflow and non-finite floating-point results are errors, including
when negating the minimum integer.
Unary subtraction also negates durations; UTC timestamps cannot be negated.
(- value more*) → value - / — Returns
ndivided bydand each additional divisor inmore, or the reciprocal ofnwhen called with one argument.(/ n) → float
(/ value divisor more*) → value - < — Returns whether the arguments are strictly increasing.
(< first second more*) → boolean - <= — Returns whether the arguments are nondecreasing.
(<= first second more*) → boolean - = — Returns
trueif all supplied values are equal, otherwisefalse.(= x) → boolean
(= x y) → boolean
(= x y more*) → boolean - == — Is another name for the equality function. It takes the same
arguments and returns the same results and errors.
(== x) → boolean
(== x y) → boolean
(== x y more*) → boolean - > — Returns whether the arguments are strictly decreasing.
(> first second more*) → boolean - >= — Returns whether the arguments are nonincreasing.
(>= first second more*) → boolean - Secure random generators — Creates a generator backed by the operating system's secure entropy source.
Use it with
random/int,random/float,random/choose,random/shuffleandrandom/bytes, with the same bounds and validation as a seeded generator:(crypto/random) → generator - aabb? — Returns
truefor a#aabbvalue, an AABB, otherwisefalse. Another packed kind with the same number of components, or a list of the components, is not one.(aabb? value) → boolean - and — Evaluates forms once each, from left to right, and returns the first falsey
value without evaluating later forms; an
#errvalue is falsey, soandreturns it. If every form is truthy, returns the last value. With no forms, returnstrue.(and forms*) → value - apply — Calls a function value with the elements of a list as its arguments.
(apply function arguments) → value - bitset? — Returns
truefor a Bitset, otherwisefalse.(bitset? value) → boolean - bitsets/add — Add one or more members. Adding a present member has no effect.
(bitsets/add set member ... more) → bitset - bitsets/and — Intersect two or more sets.
(bitsets/and a b ... more) → bitset - bitsets/and-count — Count the intersection without constructing a result set.
(bitsets/and-count a b) → integer - bitsets/and-not — Remove every member of b and the later sets from a.
(bitsets/and-not a b ... more) → bitset - bitsets/contains? — Test whether the set contains member.
(bitsets/contains? set member) → boolean - bitsets/intersects? — Test whether a and b share any member.
(bitsets/intersects? a b) → boolean - bitsets/max — Return the largest member, or null for an empty set.
(bitsets/max set) → integer or null - bitsets/min — Return the smallest member, or null for an empty set.
(bitsets/min set) → integer or null - bitsets/of — Build a set from a list of integer members. Duplicate members appear once.
(bitsets/of values) → bitset - bitsets/or — Union two or more sets.
(bitsets/or a b ... more) → bitset - bitsets/range — Build the half-open interval from start through end−1. Equal bounds make an empty set.
(bitsets/range start end) → bitset - bitsets/rank — Count members less than or equal to member.
(bitsets/rank set member) → integer - bitsets/remove — Remove one or more members. Removing an absent member has no effect.
(bitsets/remove set member ... more) → bitset - bitsets/select — Return the member at a zero-based index, or null when the index is outside the set.
(bitsets/select set index) → integer or null - bitsets/slice — Keep only members in the half-open interval [start, end).
(bitsets/slice set start end) → bitset - bitsets/subset? — Test whether every member of a belongs to b.
(bitsets/subset? a b) → boolean - bitsets/xor — Take the symmetric difference of two or more sets, from left to right.
(bitsets/xor a b ... more) → bitset - blackholes/audit — Returns the audits in transaction order.
optionsis a map with optionalafter(a transaction) andlimit(a positive integer). Withoutlimit, the list has every audit afterafter. Each audit is also the value of astardust/blackholefact that queries can read.(blackholes/audit options?) → list - blackholes/execute — Applies a previewed blackhole.
approvalis the preview's invocation map withdigest,confirm,actorandreasonadded.digestis the preview's digest andconfirmis its confirmation text. A commit after the preview gives an error with theconflictcode. Execute is refused inside a mutation or a reactor.(blackholes/execute approval) → map - blackholes/preview — Plans a blackhole and changes nothing.
invocationis the map{namespace name args};argsis optional. The result hasdigest,targets,matched,replacements,removals,confirm,affectedandsamples.(blackholes/preview invocation) → map - blackholes/status — Returns
{enabled audits recovering backups}.(blackholes/status) → map - boolean — Returns
falseifvalueisnullorfalse, otherwisetrue.(boolean value) → boolean - boolean? — Returns
trueifbis eithertrueorfalse, otherwisefalse.(boolean? b) → boolean - bytes/and — Returns the bitwise AND of two or more Bytes values of equal length. Values
of different lengths are an error.
(bytes/and a b more*) → bytes - bytes/concat — Returns the bytes of every argument joined in order. Without arguments it
returns
#b64 "". Anullargument adds no bytes.(bytes/concat buffers*) → bytes - bytes/index-of — Returns the index of the first occurrence of the Bytes
needleinbat or afterstart, ornullif there is none.startdefaults to zero and is limited to the range from zero to the byte count, as instrings/index-of. An emptyneedleis found at the limitedstart.(bytes/index-of b needle) → integer
null
(bytes/index-of b needle start) → integer
null - bytes/not — Returns
bwith every bit inverted.(bytes/not b) → bytes - bytes/of — Returns Bytes with one byte for each integer in the list
values.nullis an empty list. Each element must be an integer from 0 to 255; any other element is an error, and no value is truncated. An element is a byte value, not a number to store:(bytes/of [1.5])is an error. The encoding library writes a number as its 8 bytes.(bytes/of values) → bytes - bytes/or — Returns the bitwise OR of two or more Bytes values of equal length. Values of
different lengths are an error.
(bytes/or a b more*) → bytes - bytes/shift-left — Returns
bshifted left bynbits as one number, with the first byte most significant. The byte count stays the same. Bits shifted past the first byte are lost, and the vacated bits are zero.nmust be a nonnegative integer. A shift of the bit length or more returns all zero bytes, and a shift of zero returns equal Bytes.(bytes/shift-left b n) → bytes - bytes/shift-right — Returns
bshifted right bynbits as one number, with the first byte most significant. The shift is logical: the vacated bits are zero. The byte count stays the same, and bits shifted past the last byte are lost.nmust be a nonnegative integer. A shift of the bit length or more returns all zero bytes.(bytes/shift-right b n) → bytes - bytes/slice — Returns the bytes from index
startup to, but not including, indexend.enddefaults to the byte count. The bounds must be integers with 0 ≤start≤end≤(count b). Any other bounds produce#err <bounds index>; a slice never returns fewer bytes than its bounds name.(bytes/slice b start) → bytes
(bytes/slice b start end) → bytes - bytes/xor — Returns the bitwise exclusive OR of two or more Bytes values of equal length.
Values of different lengths are an error.
(bytes/xor a b more*) → bytes - bytes? — Returns
trueifvalueis a Bytes value, otherwisefalse.(bytes? value) → boolean - collections/copy — Returns a copy of
valuethat changes to either leave the other unchanged. Copies every list and map reachable fromvalue. A list or map reached more than once is copied once, so collections shared withinvaluestay shared within the copy, and cycles stay cycles. With the modeshallow, copies only the top-level list or map; its members are shared. Other values do not change and are returned as they are.(collections/copy value) → value
(collections/copy value shallow) → value - collections/update — Replaces the value at
pathinrootwith the result of callingfon that value andargs, in place, and returns the same root collection. Stores the result asputdoes, including container creation and list growth. A missing entry suppliesnulltof.(collections/update root path f args*) → collection - compare — Returns
-1,0, or1whenfirstsorts before, ties with, or sorts aftersecond, usingsortordering.(compare first second) → integer - comparisons/identical? — Returns
trueif its operands refer to the same value, otherwisefalse. Errors raised at the same place with the same tags and message may be the same value.(comparisons/identical? a b) → boolean - comparisons/not= — Returns the negation of the corresponding equality call. This means that not all
arguments are equal, rather than requiring every pair to differ. One argument
returns
false; no arguments is an error. Equality retains its matching-kind checks and stops comparing after the first unequal pair.(comparisons/not= value more*) → boolean - cond — Chooses among pairs of tests and result expressions.
(cond test result ...) - const? — Returns
trueifvis a constant reference, such as the quoted form`:name, otherwisefalse. A local and a constant with the same name are not equal.(const? v) → boolean - contains? — Returns
trueifpathselects a value inroot, includingnullorfalse, otherwisefalse.(contains? root path) → boolean - count — Returns the number of list elements, pointer segments, map members, Unicode string code points,
or bytes of a Bytes value. For
null, returns zero.(count collection) → integer - db/reactors —
(db/reactors)returns the saved reactors and their work since the database opened. Each entry has these members:(db/reactors) → map - def — Defines top-level locals: bindings that the later top-level forms of the
same file, or of the same REPL session, read as their names.
(def name value? ...) → local reference - defblackhole — Defines a blackhole in a saved namespace. The parameters are locals in the
query and in the expressions.
queryis a query map withoutas-of: a saved query cannot select an earlier snapshot. A blackhole rewrites every earlier version of a selected field, also when its current value is retracted. Adistinctquery keeps its own tuples: the variables that the patch reads do not make more rows.patchmaps query variables that bind entities tonull, which erases every field of the entity, or to a map of fields. A field'snullerases each version; an expression computes a replacement for each version.links {incoming remove}removes links to erased entities from other fields.(defblackhole name doc? [params*] {query patch links?}) → name - defcron — A scheduled reactor is a mutation that the database runs at UTC times. Save
it in a namespace. When the root configuration has the tag
<scheduled-reactors>, the database runs the mutation at each minute that its schedule selects. Each run is a separate write transaction.(defcron name doc? map) → name - defmacro — Defines a macro for the later forms of the file or session.
(defmacro name doc-or-meta? [params*] body*) → name - defmutation — Define a mutation with
defmutationand call it with an open database. The result containstxandids. These examples run in order against a separate new database.(defmutation name [params*] mutation-map) → name - defn — Defines a top-level function using the existing
defandfnsemantics. The name is a declaration. Documentation, metadata, parameter rules, contracts, multiple arities and variadic clauses followfn. The result is the binding name, as withdef. Nesteddefnforms are errors.(defn name doc-or-meta? [params*] body*) → name - defquery — Defines a named function that queries the database snapshot attached to its
evaluation. A result contract may follow the parameter list. Calling the
function returns a list of maps unless the query requests positional tuples.
(defquery name [params*] query-map) → name - defreactor — A reactor is a mutation that the database runs. Save it in a namespace. Each
later write that changes a field that the reactor reads or writes then runs
the reactor before the write commits. The facts that the reactor writes
commit in the same transaction as the facts that caused them, so a query at
that transaction sees both.
(defreactor name doc? options? mutation-map) → name - defresponder — Defines a responder in a saved namespace. A request call on a subject that
patternmatches callsfnwith{subject data}, and its value is the reply. A responder answers before any host worker. A save that defines a responder with the pattern of another saved responder, written the same, fails with#err <conflict name>, with a message such as"math/add already answered by app/math/add". Different patterns that match one subject make the call fail with#err <conflict>, which names both responders.nameis also bound tofn.(defresponder name pattern fn) → name - defsubscription — Defines a subscription in a saved namespace. For each publication whose
subject
patternmatches, the database callsfnwith{subject data}before the publish returns, in publication order.fnmay write, publish and call; its writes run their ownonhandlers. A publication that the body makes runs its subscriptions after the current ones, so a chain runs in order without a limit on its length. A failed body never undoes the publication: the publish result lists it underfailures.nameis also bound tofn.(defsubscription name pattern fn) → name - distinct — Returns a fresh list retaining the first occurrence of each distinct typed
value. Collections compare structurally, with map member order ignored.
Kinds remain distinct: integer
1and float1.0are separate values. Functions compare by identity. Positive and negative floating zero compare equal.(distinct list) → list - do — Evaluates the
exprforms in order and returns the last result.(do expr*) → value - duration? — Returns
truefor a duration, otherwisefalse. It is the kind predicate thattime/duration?also provides.(duration? value) → boolean - empty? — Returns whether
countis zero. Lists, pointers, maps, strings, bytes, andnullare accepted.(empty? collection) → boolean - encoding/decode — Reverses
encoding/encodeforcodec.hextakes a string of hexadecimal digit pairs of either case and returns Bytes; an odd length or any other character is an error.utf8takes Bytes and returns a string.(encoding/decode codec value) → value
(encoding/decode codec value options) → value - encoding/encode — Encodes
valuewithcodec.hextakes Bytes and returns two lowercase hexadecimal digits for each byte.utf8takes a string and returns its bytes. No codec defines an option for encoding.(encoding/encode codec value) → string
bytes
(encoding/encode codec value options) → string
bytes - error? — Returns
trueifvalueis an error andfalseotherwise.error?receives an error argument; a call of most other functions returns it (see Evaluation).(error? value) → boolean - errors/data — Returns the error's payload. For a map payload, returns a new map with the
same keys and member values. Nested values remain shared. Other payloads
are returned unchanged.
(errors/data error) → value - errors/message — Returns the error's message: the
messagemember of its payload when that is text, the payload itself when the payload is text, and otherwisenull. Use it to log an error, sincestrof an error is the error.(errors/message error) → string
null - errors/tags — Returns the error's tags: the boolean members of its payload, as a tag group
map such as
<division integer zero>. If the payload is not a map, the result is{}. Compare the result with a tag group, or read one tag withget.(errors/tags error) → map - events/call — Sends
dataas a request onsubjectand returns the reply. A saved responder that matches answers at once. Otherwise a host worker (events/accept) must answer: the call waits, and the wait counts against the evaluation's CPU budget and ends when the evaluation is cancelled. While it waits, plugin requests run on the database's other workers, so a call that needs a host worker fails with#err <denied events>when the database has one worker. Without a worker, it fails withno_worker.(events/call subject data) → value - events/cancel — Ends the exchange behind
handle; the other side readscancel.(events/cancel handle) → map - events/finish — Ends this side's stream of the exchange behind
handle.(events/finish handle) → map - events/publish — Publishes
dataonsubjectand returns{delivered dropped}: the subscriptions it reached, saved ones included, and those whose queue allocation failed. The saved subscriptions run before it returns; a failed body adds an entry{namespace name subject error}tofailures.(events/publish subject data) → map - events/send — Sends
datato the other side of the exchange behindhandle, as theevents/sendrequest does.(events/send handle data) → map - events/status — Returns
{subscriptions registrations rpcs queued runs failures}: the open subscriptions, workers and exchanges, the queued notices, and the saved handler runs and failures since the database opened.(events/status) → map - export — Names the top-level locals that a library file provides. When code
imports the file, as
(import {s "lib/shapes"})does, each named local becomes the constant:s/name. Its value is the value of the local after the file runs. The other locals of the file stay private. The file's functions read them, not the locals of the code that calls them.(export name*) → list - false? — Returns
trueifvalueis the booleanfalse, otherwisefalse.(false? value) → boolean - first — Returns the first element or pointer segment, or
nullwhen empty.(first list) → value - float — Converts an integer to a float, returns a float unchanged, or parses a signed
decimal string with an optional decimal point and exponent. Integer conversion
can lose precision; for example, integer
9007199254740993converts to9007199254740992.0. Whitespace, hexadecimal notation, NaN, and infinity are rejected. Overflow is an error; underflow to zero is permitted. Booleans, null, and nominal types such as links are rejected.(float value) → float - float? — Returns
trueifnis a floating-point number, otherwisefalse.(float? n) → boolean - fn — Creates a function.
(fn name? doc-or-meta? [params*] body*) → function
(fn name? doc-or-meta? ([params*] body*)+) → function - fn? — Returns
trueiffis a function, otherwisefalse.(fn? f) → boolean - for — Evaluates a body for each combination of collection values and returns a list of the results.
(for [name collection ...] body) - format — Returns a string by substituting
argsinto the conversion specifications intemplate.(format template args*) → string - from-pairs — Returns a fresh map from
[key value]pairs inlist. Later duplicate keys win.(from-pairs list) → map - frustum? — Returns
truefor a#frustumvalue, a frustum, otherwisefalse. Another packed kind with the same number of components, or a list of the components, is not one.(frustum? value) → boolean - fs/abs — Returns an absolute path, using the process working directory when
pathis relative. The target need not exist. Does not resolve symbolic links or normalize dot components.(fs/abs path) → string - fs/chmod — Sets the permission bits of
pathto the permission map and returnspath. Follows symbolic links and does not apply the umask. Windows produces#err <fs unsupported>.(fs/chmod path permissions) → string - fs/copy — Copies the contents of
sourceto the exact pathdestinationand returnsdestination. Options arereplace-existing, which defaults tofalse, andpermissions. An existing destination produces#err <fs exists>unlessreplace-existingistrue. With replacement, a destination symbolic link is followed to its target, as the write functions do. Whensourceanddestinationare the same file, including through a hard or symbolic link, the copy produces#err <fs same-file>before it truncates anything. Does not recurse, copy metadata, or add a filename whendestinationis a directory.(fs/copy source destination) → string
(fs/copy source destination opts) → string - fs/create-file — Exclusively creates an empty regular file and returns
path. Any existing entry produces#err <fs exists>. The only option ispermissions.(fs/create-file path) → string
(fs/create-file path opts) → string - fs/create-temp — Exclusively creates an empty file with a unique name and returns its absolute path.
(fs/create-temp) → string
(fs/create-temp opts) → string - fs/dir? — Returns
trueifpathresolves to a directory, following symbolic links.(fs/dir? path) → boolean - fs/exists? — Returns
trueifpathresolves to an existing entry. Returnsfalseif the target or a parent component is absent. Follows symbolic links, so a dangling link returnsfalse.(fs/exists? path) → boolean - fs/ext — Returns the final filename extension without its dot, or
nullif there is none. Neither.nor..has an extension. A trailing dot gives the empty string.(fs/ext path) → string or null - fs/file-name — Returns the final name component of
path, ornullfor a root. Ignores trailing separators.(fs/file-name path) → string or null - fs/file? — Returns
trueifpathresolves to a regular file, following symbolic links.(fs/file? path) → boolean - fs/join — Returns a path formed from the supplied parts.
An absolute child replaces the path before it.
Does not resolve symbolic links or collapse
.and..components.(fs/join part) → string
(fs/join parent child more*) → string - fs/lstat — Returns the same metadata as
fs/statfor the final entry atpath, ignoring trailing separators and without following that entry's symbolic link.(fs/lstat path) → map - fs/mkdir — Creates one directory and returns
path. The parent must exist. An existing entry produces#err <fs exists>.(fs/mkdir path) → string
(fs/mkdir path opts) → string - fs/mkdir-all — Creates missing parent directories and the directory at
path, and returnspath. An existing directory is accepted, including through a symbolic link. A conflicting non-directory entry produces#err <fs not-directory>.permissionsapplies only to the directories that the call creates.(fs/mkdir-all path) → string
(fs/mkdir-all path opts) → string - fs/mkdir-temp — Exclusively creates a directory with a unique name and returns its absolute path.
(fs/mkdir-temp) → string
(fs/mkdir-temp opts) → string - fs/normalize — Returns a lexically normalized path.
Removes redundant separators and
.components, and reduces..components that have a preceding name. Keeps unresolved leading..components in a relative path. Returns"."when a relative path reduces to the current directory. Does not resolve symbolic links.(fs/normalize path) → string - fs/parent — Returns the lexical parent of
path, ornullif there is none. Ignores trailing separators except those that form a root.(fs/parent path) → string or null - fs/read — Returns the entire file as Bytes. An empty file returns
#b64 "". With{encoding <utf8>}, returns a string and rejects invalid UTF-8 with#err <invalid value>. Text reads retain line endings and a leading byte-order mark.(fs/read path) → Bytes
(fs/read path opts) → Bytes or string - fs/read-dir — Returns a list of the immediate child paths of
dir. Excludes the.and..entries. An empty directory returns[].(fs/read-dir dir) → list - fs/readlink — Returns the target text stored in the symbolic link at
path. Does not resolve the target or require it to exist. A missing entry or an entry that is not a symbolic link produces an error.(fs/readlink path) → string - fs/real-path — Returns an absolute path with all symbolic links resolved.
The target must exist.
A broken link produces
#err <fs missing>, and a link cycle produces#err <fs loop>.(fs/real-path path) → string - fs/rel — Returns a lexical relative path from
basetopath.basedefaults to the process working directory. Both inputs are made absolute against the same working directory and normalized. Returns"."when the normalized paths are equal. Paths under different host roots, such as two drives, produce#err <invalid value>. Does not resolve symbolic links or require the paths to exist.(fs/rel path) → string
(fs/rel base path) → string - fs/remove — Deletes a file, symbolic link, or empty directory and returns
null. A missing entry produces#err <fs missing>, and a nonempty directory produces#err <fs not-empty>.(fs/remove path) → null - fs/remove-all — Deletes a file, symbolic link, or directory tree and returns
null. An absent path is accepted. Does not follow symbolic links or change permissions to force deletion. A host root, such as/or a drive root, produces#err <invalid value>, also when the path reaches it through a link, aslink/.does for a link to/. A failure can leave part of the tree deleted.(fs/remove-all path) → null - fs/remove-if-exists — Deletes a file, symbolic link, or empty directory.
Returns
trueif it deleted the entry, orfalseif the entry was absent. A nonempty directory or other failure produces an error.(fs/remove-if-exists path) → boolean - fs/stat — Returns metadata for the entry that
pathreaches, following symbolic links. A missing target or other failure produces an error.(fs/stat path) → map - fs/strip-ext — Returns
pathwith its final filename extension and dot removed. Returnspathunchanged when it has no extension.(fs/strip-ext path) → string - fs/symlink — Creates a symbolic link at
linkthat containstarget, and returnslink.targetneed not exist. A relative target is resolved against the link's parent when the link is followed. An existing entry atlinkproduces#err <fs exists>. On Windows, creating a symbolic link can require a privilege or developer mode; a refusal produces#err <fs denied>.(fs/symlink link target) → string - fs/symlink? — Returns
trueif the final entry is a symbolic link, including a dangling link. Ignores trailing separators and does not follow the final link.(fs/symlink? path) → boolean - fs/walk — Returns a depth-first list of
rootand its descendants. Each directory comes before its children. Includes symbolic links but never descends through one, including when the root has trailing separators. A file or symbolic-link root returns a one-element list. A missing root or a traversal failure produces an error. There are no visitor callbacks, glob patterns, or link-following option.(fs/walk root) → list - fs/with-temp-dir — Creates a temporary directory, calls
fwith its absolute path, and deletes the tree afterwards. Takes the same options asfs/mkdir-temp. It is an ordinary function, not a binding form.(fs/with-temp-dir f) → value
(fs/with-temp-dir f opts) → value - fs/write — Writes
contentand returnspath. A string is encoded as UTF-8; Bytes are written unchanged. Creates the file if absent and truncates an existing file unlessappendistrue. Adds no newline or byte-order mark.(fs/write path content) → string
(fs/write path content opts) → string - functions/comp — Returns a function composing its inputs right to left, passing all call arguments to the rightmost function and each result to the next.
With no inputs, returns
functions/identity. With one, returnsf.(functions/comp) → function
(functions/comp f) → function
(functions/comp f g functions*) → function - functions/complement — Returns a function that calls
fwith its arguments and negates the result as a boolean.(functions/complement f) → function - functions/constantly — Returns a function that ignores its arguments and returns
value.(functions/constantly value) → function - functions/fnull — Returns a function that calls
f, replacingnullin its first three argument positions with the supplied defaultsx,y, andz. Preservesfalseand does not supply missing arguments.(functions/fnull f x) → function
(functions/fnull f x y) → function
(functions/fnull f x y z) → function - functions/identity — Returns
valueunchanged.(functions/identity value) → value - functions/juxt — Returns a function that applies
fandfunctionsto the same arguments and returns their results in order as a list.(functions/juxt f functions*) → function - functions/partial — Returns a function that calls
fwithargsfollowed by its call-time arguments. With no fixed arguments, returnsf.(functions/partial f args*) → function - gensym — Returns a new name that no source form contains.
(gensym) → name
(gensym prefix) → name - get — Returns the value selected by
pathinroot, ordefaultif an entry is missing. Withoutdefault, a missing entry returnsnull. A selected value ofnullorfalseis returned unchanged, not replaced bydefault.getdoes not modifyrootor copy the selected value. A map or list in callee position callsgetwith itself asroot: see Calling a map or list. In a packed math value, an index selects a part and a string swizzles a vector: see Destructuring and lookup.(get root path) → value
(get root path default) → value - hash? — Returns
truefor a#hashdigest, otherwisefalse.(hash? value) → boolean - hashes/digest — Returns a
#hashofvalueunderalgorithm, a name from this table:(hashes/digest algorithm value) → hash - if — Selects a branch according to the truthiness of a test.
(if test then)
(if test then else) - int — Returns an integer unchanged, truncates a float toward zero, or parses a signed
decimal string exactly. String input accepts an optional ASCII sign followed
by ASCII decimal digits, including leading zeros. Whitespace, decimal points,
exponents, and hexadecimal notation are rejected. Values outside signed 64-bit
range are errors. Booleans, null, and nominal types such as links are rejected.
(int value) → integer - int? — Returns
trueifnis an integer, otherwisefalse. A link scalar is not an integer.(int? n) → boolean - invoke? — Returns
truefor an invocation form, such as`(f 1), otherwisefalse.(invoke? value) → boolean - jsonptr — Converts RFC 6901 text to a pointer. The empty string gives the root pointer;
a nonempty string must start with
/and contain only valid~0and~1escapes. Invalid text gives#err <invalid value>; a non-string gives#err <mismatch type>.(jsonptr text) → pointer - jsonptr? — Returns
truefor a pointer andfalsefor other values. A pointer is not a list, even though the list functions accept it.(jsonptr? value) → boolean - keys — Returns the map's string keys in ascending Unicode order.
(keys map) → list - let — Introduces local bindings and evaluates a body in their scope.
(let [bindings*] exprs*) - link? — Returns
truefor a link, otherwisefalse.(link? value) → boolean - list? — Returns
trueifxsis a list, otherwisefalse.(list? xs) → boolean - lists/any? — Returns
trueat the first truthy predicate result without visiting later elements. Returnsfalsefor an empty list.(lists/any? predicate list) → boolean - lists/append — Appends
valuestolistin place as individual elements and returns the same list. Values are stored without copying. With no additional values, leaveslistunchanged.listmust be a list, notnullor a pointer.(lists/append list values*) → list - lists/concat — Returns a fresh list containing the elements of each input list, in order.
With no inputs, returns an empty list.
(lists/concat lists*) → list - lists/drop — Returns a fresh list excluding the first
nelements oflist.(lists/drop n list) → list - lists/drop-while — Returns
listfrom the first element for whichpredicateis falsey, skipping the preceding elements.(lists/drop-while predicate list) → list - lists/every? — Returns
falseat the first falsey predicate result without visiting later elements. Returnstruefor an empty list.(lists/every? predicate list) → boolean - lists/filter — Calls
predicateon each element, from left to right, and returns the elements whose results are truthy. Retains their input order.(lists/filter predicate list) → list - lists/find-first — Returns the first element of
listfor whichpredicateis truthy, ordefaultif none matches. The default isnull.(lists/find-first predicate list) → value
(lists/find-first predicate list default) → value - lists/flatten — Returns a list of the non-list elements in
list, recursively expanding nested lists in order. Empty lists contribute no elements. Non-list elements, including maps, strings, andnull, are kept unchanged.listmust be a list, otherwise produces#err <mismatch type>. Missing or extra arguments produce#err <arity mismatch>.(lists/flatten list) → list - lists/frequencies — Counts each string in the input list and returns a map from strings to integer
counts. Non-string elements are errors; integer
1is never coerced to string"1".(lists/frequencies strings) → map - lists/group-by — Calls
functionon each element, from left to right. Each result must be a string and becomes a map key. Each map value is the list of input elements with that key, preserving their input order. Non-string keys are errors.(lists/group-by function list) → map - lists/interleave — Returns a fresh list taking one element from each input list in turn, stopping at the shortest list.
Returns
[]with no inputs and a shallow copy with one.(lists/interleave) → list
(lists/interleave list) → list
(lists/interleave list1 list2) → list
(lists/interleave list1 list2 lists*) → list - lists/interpose — Returns a fresh list with
separatorbetween adjacent elements oflist.(lists/interpose separator list) → list - lists/keep — Returns the results of applying
fto each element oflist, excludingnullbut preservingfalseand input order.(lists/keep f list) → list - lists/last — Returns the last element, or
nullfor an empty list.(lists/last list) → value - lists/mapcat — Applies
fto corresponding elements oflistand any additionallists, then concatenates the result lists one level deep. Stops at the shortest input list.(lists/mapcat f list lists*) → list - lists/nth — Returns the element at the nonnegative, zero-based integer
index. An out-of-range index returnsdefaultif supplied; otherwise it is an error. A negative index is an error even when a default is supplied.(lists/nth list index default?) → value - lists/partition — Returns groups of up to
nelements fromlist, startingstepelements apart and including short trailing groups.stepdefaults ton.(lists/partition n list) → list
(lists/partition n step list) → list - lists/partition-by — Returns consecutive groups from
list, starting a new group wheneverfreturns a different value.(lists/partition-by f list) → list - lists/range — Returns integers from
startup to, but excluding,end, incrementing bystep. The defaults are zero forstartand one forstep. A negative step produces a descending range. A zero step is an error. All arguments must be integers.(lists/range end) → list
(lists/range start end step?) → list - lists/repeat — Returns a list containing
valuethe specified number of times.countmust be a nonnegative integer. Values are reused rather than deep copied.(lists/repeat count value) → list - lists/reverse — Reverses
listin place and returns the same list, without copying the elements.listmust be a list, notnullor a pointer.(lists/reverse list) → list - lists/second — Returns the second element of
list, ornulliflisthas fewer than two elements.(lists/second list) → value - lists/slice — Returns a fresh list from
startup to, but excluding,end. Indexes are nonnegative, zero-based integers. An omitted end means the list's length. Indexes beyond the length are clamped, and an end before the start produces an empty list.(lists/slice list start end?) → list - lists/some — Returns the first truthy result of applying
fto elements oflist, without visiting later elements, ornullif none matches.(lists/some f list) → value - lists/sort-by — Sorts
listin place, stably, by the keys returned byf, and returns the same list. The list's order changes only after key extraction and all comparisons succeed.listmust be a list, notnullor a pointer. Callsfonce per element, from left to right, before making comparisons. The key function must be an ordinary function and must not change the input list or its elements. Usessortordering, or the suppliedcomparatorapplied to the keys. Equal keys keep their input order. Elements are shared without copying. Key-function errors stop processing and are returned.(lists/sort-by f list) → list
(lists/sort-by f comparator list) → list - lists/take — Returns a fresh list of the first
nelements oflist, or all elements if fewer are available.(lists/take n list) → list - lists/take-while — Returns the leading elements of
listfor whichpredicateis truthy, stopping at the first falsey result.(lists/take-while predicate list) → list - local? — Returns
trueifvis a local reference, such as the quoted form`name, otherwisefalse.(local? v) → boolean - m22? — Returns
truefor a#m22value, a 2 by 2 matrix, otherwisefalse. Another packed kind with the same number of components, or a list of the components, is not one.(m22? value) → boolean - m33? — Returns
truefor a#m33value, a 3 by 3 matrix, otherwisefalse. Another packed kind with the same number of components, or a list of the components, is not one.(m33? value) → boolean - m44? — Returns
truefor a#m44value, a 4 by 4 matrix, otherwisefalse. Another packed kind with the same number of components, or a list of the components, is not one.(m44? value) → boolean - macroexpand — Applies
macroexpand-1to the head again and again until it is not a macro call.(macroexpand form) → form - macroexpand-1 — Expands one macro call and returns the resulting form.
(macroexpand-1 form) → form - map — Returns a list of the results of applying
fto corresponding elements ofxsand any additionallists.(map f xs) → list
(map f xs lists*) → list - map? — Returns
trueifmis a map, otherwisefalse.(map? m) → boolean - maps/select-keys — Returns a fresh map containing the literal top-level keys in
keysthat are present inmap.(maps/select-keys map keys) → map - maps/zipmap — Returns a fresh map pairing string
keyswithvalues, stopping at the shorter list. Later duplicate keys win.(maps/zipmap keys values) → map - math/aabbs/aabb — Returns an AABB from two
#v3values.(math/aabbs/aabb minimum maximum) → aabb - math/aabbs/aabb? — Returns
truefor#aabbvalues.(math/aabbs/aabb? value) → boolean - math/aabbs/transform — Transforms an AABB with a
#m44matrix and returns its axis-aligned bounds.(math/aabbs/transform box matrix) → aabb - math/abs — Returns the absolute value, preserving integer or float kind. The absolute
value of the minimum integer overflows and is an error.
Durations are also accepted and return a duration; the minimum tick
duration likewise overflows. UTC timestamps are rejected.
(math/abs value) → value - math/acos — Returns the arc cosine of
nin radians, in the range from zero to pi.(math/acos n) → float - math/acosh — Returns the nonnegative inverse hyperbolic cosine of
n.(math/acosh n) → float - math/asin — Returns the arc sine of
nin radians, in the range from negative pi/2 to pi/2.(math/asin n) → float - math/asinh — Returns the inverse hyperbolic sine of
n.(math/asinh n) → float - math/atan — Returns the arc tangent of
nin radians, in the range from negative pi/2 to pi/2.(math/atan n) → float - math/atan2 — Returns the angle of the point
(x, y)in radians, in the range from negative pi to pi, using both signs to select the quadrant.(math/atan2 y x) → float - math/atanh — Returns the inverse hyperbolic tangent of
n.(math/atanh n) → float - math/cbrt — Returns the real cube root of
n, with the same sign asn.(math/cbrt n) → float - math/ceil — Returns the least integral-valued float greater than or equal to
nafter conversion to a float.(math/ceil n) → float - math/clamp — Returns
valuelimited to the inclusive interval fromlowthroughhigh. All three arguments must have the same numeric or temporal kind, andlowmust not exceedhigh.(math/clamp value low high) → value - math/contains? — Returns
truewhen an AABB or sphere contains a#v3point. A point on the boundary is contained. Other containers produce#err <mismatch type>. A squared distance from a sphere's center past the Float range produces#err <float overflow>.(math/contains? container point) → boolean - math/copy-sign — Returns the absolute value of
magnitudewith the sign ofsign, including the sign of floating-point zero.(math/copy-sign magnitude sign) → float - math/cos — Returns the cosine of
anglein radians.(math/cos angle) → float - math/cosh — Returns the hyperbolic cosine of
n.(math/cosh n) → float - math/even? — Returns
trueif integernis even, otherwisefalse.(math/even? n) → boolean - math/exp — Returns e raised to
n.(math/exp n) → float - math/exp2 — Returns two raised to
n.(math/exp2 n) → float - math/expm1 — Returns e raised to
nminus one, computed without the loss of precision from subtracting one frommath/exp's rounded result near zero.(math/expm1 n) → float - math/floor — Returns the greatest integral-valued float less than or equal to
nafter conversion to a float.(math/floor n) → float - math/floor-div — Returns the integer quotient of
ndivided byd, rounded toward negative infinity.(math/floor-div n d) → integer - math/floor-mod — Returns the integer remainder of
ndivided bydusing a quotient rounded toward negative infinity.(math/floor-mod n d) → integer - math/frustums/frustum — Returns a frustum from six
#planevalues.(math/frustums/frustum left right bottom top near far) → frustum - math/frustums/frustum? — Returns
truefor#frustumvalues.(math/frustums/frustum? value) → boolean - math/hypot — Returns the square root of
x*x + y*ywithout intermediate overflow or underflow.(math/hypot x y) → float - math/intersects? — Tests these unordered geometry pairs: AABB with AABB, ray, sphere, or frustum;
ray with sphere, plane, or triangle; and sphere with sphere, plane, or frustum.
Other pairs produce
#err <mismatch type>. A test value that passes the Float range, such as the distance along a ray almost parallel to a plane, produces#err <float overflow>.(math/intersects? a b) → boolean - math/inverse-lerp — Returns the fraction locating
valuebetweenstartandend, without clamping. Equal endpoints are an error.(math/inverse-lerp start end value) → float - math/lerp — Returns
start + (end - start) * fractionas a float. The fraction is not clamped, so values outside zero through one extrapolate beyond the endpoints.(math/lerp start end fraction) → float - math/log — Returns the natural logarithm of
n, or its logarithm in the suppliedbase. Whenbaseis supplied, both numbers must have the same type. The base must be positive and cannot be one.(math/log n) → float
(math/log n base) → float - math/log10 — Returns the base-ten logarithm of
n.(math/log10 n) → float - math/log1p — Returns the natural logarithm of one plus
n, computed without the loss of precision from rounding1 + nnear zero.(math/log1p n) → float - math/log2 — Returns the base-two logarithm of
n.(math/log2 n) → float - math/matrices/m22 — Returns a row-major 2 by 2 matrix.
(math/matrices/m22 m00 m01 m10 m11) → m22 - math/matrices/m33 — Returns a row-major 3 by 3 matrix.
(math/matrices/m33 m00 m01 m02 m10 m11 m12 m20 m21 m22) → m33 - math/matrices/m44 — Returns a row-major 4 by 4 matrix.
(math/matrices/m44 m00 m01 m02 m03 m10 m11 m12 m13 m20 m21 m22 m23 m30 m31 m32 m33) → m44 - math/matrices/matrix? — Returns
truefor#m22,#m33, and#m44values.(math/matrices/matrix? value) → boolean - math/max — Returns the greatest argument. Requires at least one argument, and all arguments
must have the same numeric or temporal kind. Integer and temporal comparisons
retain full 64-bit precision.
(math/max value more*) → value - math/min — Returns the least argument. Requires at least one argument, and all arguments
must have the same numeric or temporal kind. Integer and temporal comparisons
retain full 64-bit precision.
(math/min value more*) → value - math/noise/perlin2 — Returns deterministic two-dimensional Perlin noise for a
#v2point. The noise hash reduces each coordinate modulo 289. Past about1e160that reduction can pass the Float range, which produces#err <float overflow>.(math/noise/perlin2 point) → float - math/odd? — Returns
trueif integernis odd, otherwisefalse.(math/odd? n) → boolean - math/planes/plane — Returns a plane from a
#v3normal and a numeric distance.(math/planes/plane normal distance) → plane - math/planes/plane? — Returns
truefor#planevalues.(math/planes/plane? value) → boolean - math/pow — Returns
baseraised toexponent.(math/pow base exponent) → float - math/quaternions/quaternion — Returns
#quat [x y z w].(math/quaternions/quaternion x y z w) → quat - math/quaternions/quaternion? — Returns
truefor#quatvalues.(math/quaternions/quaternion? value) → boolean - math/rays/intersect-sphere — Returns the near and far ray distances. Returns
nullwhen there is no hit. A zero ray direction does not intersect.(math/rays/intersect-sphere ray sphere) → list
null - math/rays/ray — Returns a ray from two
#v3values. The direction need not have unit length.(math/rays/ray origin direction) → ray - math/rays/ray? — Returns
truefor#rayvalues.(math/rays/ray? value) → boolean - math/remap — Maps
valuefrom the input interval to the output interval, without clamping. Equal input endpoints are an error. Reversed intervals are accepted.(math/remap input-start input-end output-start output-end value) → float - math/rint — Returns the integral-valued float nearest to
nafter conversion to a float, choosing the even integer in halfway cases.(math/rint n) → float - math/round — Returns the integer nearest to
n, rounding halfway cases away from zero.(math/round n) → integer - math/sign — Returns integer
-1,0, or1according to the argument's sign.(math/sign number) → integer - math/signum — Returns
-1.0for negativen,1.0for positiven, or zero withn's sign for zero.(math/signum n) → float - math/sin — Returns the sine of
anglein radians.(math/sin angle) → float - math/sinh — Returns the hyperbolic sine of
n.(math/sinh n) → float - math/spheres/sphere — Returns a sphere from a
#v3center and a numeric radius.(math/spheres/sphere center radius) → sphere - math/spheres/sphere? — Returns
truefor#spherevalues.(math/spheres/sphere? value) → boolean - math/sqrt — Returns the square root of
n.(math/sqrt n) → float - math/tan — Returns the tangent of
anglein radians.(math/tan angle) → float - math/tanh — Returns the hyperbolic tangent of
n.(math/tanh n) → float - math/triangles/triangle — Returns a triangle from three
#v3points.(math/triangles/triangle a b c) → triangle - math/triangles/triangle? — Returns
truefor#trianglevalues.(math/triangles/triangle? value) → boolean - math/trunc — Returns
nconverted to a float with its fractional part discarded, rounding toward zero.(math/trunc n) → float - math/vectors/normalize — Returns a vector with unit length. The vector is a
#v2,#v3,#v4or#vf. Only the zero vector returns a zero vector. The vector is divided by its largest component magnitude first, so no intermediate value leaves the Float range for a finite input.(math/vectors/normalize vector) → v2
v3
v4
vf - math/vectors/swizzle — Returns the components of a
#v2,#v3or#v4thatpatternnames, in its order. The pattern is one to four letters, all fromxyzwor all fromrgba, and letters can repeat. One letter returns a Float; two to four return the vector of that width.(v pattern)is the same swizzle. A literal pattern compiles to direct component reads.(math/vectors/swizzle vector pattern) → float
v2
v3
v4 - math/vectors/transform — Transforms a
#v3point with a#m44matrix. The operation uses an implicit fourth component of one.(math/vectors/transform point matrix) → v3 - math/vectors/v2 — Returns
#v2 [x y].(math/vectors/v2 x y) → v2 - math/vectors/v3 — Returns
#v3 [x y z].(math/vectors/v3 x y z) → v3 - math/vectors/v4 — Returns
#v4 [x y z w].(math/vectors/v4 x y z w) → v4 - math/vectors/vector? — Returns
truefor#v2,#v3, and#v4values.(math/vectors/vector? value) → boolean - math/vectors/vf — Returns a
#vfwith the numbers of a list as its lanes. An Integer becomes the nearest Float. A#viargument becomes a#vfwith the same numbers, and a#vfargument is returned as it is.(math/vectors/vf numbers) → vf - math/vectors/vi — Returns a
#viwith the Integers of a list as its lanes. A Float in the list is an error. A#viargument is returned as it is.(math/vectors/vi integers) → vi - math/zero? — Returns
trueifnis zero, otherwisefalse.(math/zero? n) → boolean - not — Returns
trueifvalueisnullorfalse, otherwisefalse.(not value) → boolean - null? — Returns
trueifxisnull, otherwisefalse.(null? x) → boolean - number? — Returns
trueifnis an integer or a float, otherwisefalse. A link scalar is not a number.(number? n) → boolean - or — Evaluates forms once each, from left to right, and returns the first truthy
value without evaluating later forms. If every form is falsey, returns the
last value. With no forms, returns
null.(or forms*) → value - pack — Builds a map from locals that have the same names as its keys.
(pack members) → map - pairs — Returns
[key value]pairs in the same ascending key order used bykeys.(pairs map) → list - patch — Applies JSON Merge Patch member semantics to
mapin place and returns the same map. All arguments must be maps, checked before any patch is applied. With no changes maps, returnsmapunchanged.(patch map changes*) → map - peg? — Returns
truefor a compiled PEG, otherwisefalse.(peg? value) → boolean - plane? — Returns
truefor a#planevalue, a plane, otherwisefalse. Another packed kind with the same number of components, or a list of the components, is not one.(plane? value) → boolean - put — Stores
valueatpathinrootin place and returns the same root collection. Inserts or replaces a map entry, or replaces an existing list element. A list index equal to its length appends one element. Larger indices are errors. Values replace rather than merge, andnullis stored rather than deleted. Creates maps, never lists, for missing ornullintermediate values. Integer path segments require an existing list.(put root path value) → collection - quasiquote — Constructs data while evaluating unquotes at the matching nesting depth.
List-element splices insert the elements of their evaluated list.
See Quotation forms for prefix syntax and encoding.
#quasiquote form - quasiquote? — Returns
truefor a quasiquote form, such as the value of`~x, otherwisefalse.(quasiquote? value) → boolean - quat? — Returns
truefor a#quatvalue, a quaternion, otherwisefalse. Another packed kind with the same number of components, or a list of the components, is not one.(quat? value) → boolean - quote — Returns the enclosed form as data without evaluating it.
References, invocations, and collection contents retain their form representation.
See Quotation forms for prefix syntax and encoding.
#quote form - quote? — Returns
truefor a quote form, such as the value of``x, otherwisefalse.(quote? value) → boolean - random/bytes — Returns Bytes of
countuniform random bytes. Each generator output gives eight bytes, least significant byte first. The bytes that the last output has left over are discarded, so two calls for four bytes each do not return the same bytes as one call for eight.countmust be a nonnegative integer; a count of zero returns#b64 ""and leaves the generator unchanged.(random/bytes generator count) → bytes - random/choose — Returns one item of
list, each with the same chance. An empty list ornullproduces#err <invalid value>.(random/choose generator list) → value - random/float — Returns a float
xwithlo <x < hi=. Both bounds are floats. The function takes the top 53 bits of the next output asuin [0, 1), and maps it tolo + u * (hi - lo). Whenhi - lois too large for a float, it useslo * (1 - u) + hi * u. A result that rounds up tohiis drawn again.(random/float generator lo hi) → float - random/int — Returns an integer
xwithlo <x < hi=, uniform over the range. The range can span all 64-bit integers. Integers use Lemire's multiply-and-reject method, so no value is more likely than another.(random/int generator lo hi) → integer - random/seeded — Returns a new generator for the integer
seed. Every integer is a seed, negative ones included.(random/seeded seed) → generator - random/shuffle — Returns a new list with the items of
listin a uniform random order, and leaveslistunchanged. The order comes from a Fisher–Yates shuffle that swaps each positioni, from the last down to the second, with a position from0toi.nullshuffles to[].(random/shuffle generator list) → list - ray? — Returns
truefor a#rayvalue, a ray, otherwisefalse. Another packed kind with the same number of components, or a list of the components, is not one.(ray? value) → boolean - reduce — Starts with
initialand callsfunctionwith the accumulator and each list element, in list order. Each call's result becomes the next accumulator. Returns the final accumulator. An empty list ornullreturnsinitialwithout calling the function. The first argument must be an ordinary function value and the third must be a list, pointer, bytes, ornull. Errors stop reduction immediately: a call that returns an#errvalue ends the reduction, and that value is the result.(reduce function initial list) → value - regex-matcher? — Returns
truefor a compiled regular expression matcher, otherwisefalse.(regex-matcher? value) → boolean - regex? — Returns
truefor a regular expression, otherwisefalse. A compiled matcher is not a regular expression; seeregex-matcher?.(regex? value) → boolean - regexes/find — Returns the next match from
matcher, or the first match ofrein strings. Returnsnullif there is no match.(regexes/find matcher [opts]) → string, list, map, or null
(regexes/find re s [opts]) → string, list, map, or null - regexes/find-all — Returns an eager list of successive, non-overlapping matches of
rein strings. Each item uses the capture format ofregexes/groups. Returns an empty list if there are no matches. After an empty match, the search first tries a nonempty match at the same position; if there is none, it advances by one code point.(regexes/find-all re s [opts]) → list - regexes/groups — Returns the current match from
matcherwithout advancing it. Without options and with no capture groups, returns the matched string. Otherwise, returns a list containing the full match followed by each capture in group-number order. An unmatched group isnull. Without a current match, produces an error.(regexes/groups matcher [opts]) → string, list, or map - regexes/matcher — Returns a new mutable matcher for
rein strings, for use withregexes/findandregexes/groups. A matcher can be used across evaluations in the same session. It cannot be serialized or used in another session. The current match is cleared when a search reaches the end without a match.(regexes/matcher re s) → matcher - regexes/matches — Returns the match if
rematches the entire strings, otherwisenull. Results use the capture format ofregexes/groups.(regexes/matches re s [opts]) → string, list, map, or null - regexes/pattern — Returns a regex value for string
s, orsunchanged if it is already a pattern. Invalid patterns produce an error.(regexes/pattern s) → pattern - regexes/quote-replacement — Returns string
replacementescaped for literal use withregexes/replaceorregexes/replace-first.(regexes/quote-replacement replacement) → string - regexes/replace — Returns string
swith all non-overlapping matches ofrereplaced byreplacement.(regexes/replace s re replacement [opts]) → string - regexes/replace-first — Returns string
swith the first match ofrereplaced byreplacement. Uses the replacement rules ofregexes/replace.(regexes/replace-first s re replacement [opts]) → string - regexes/split — Returns a list of parts of string
ssplit on matches ofre. The integerlimitdefaults to zero. A positive limit permits at most that many parts, with the unsplit suffix in the last part. Zero omits trailing empty strings. A negative limit preserves them. A zero-width match at the start ofsdoes not create a leading empty part. If no split occurs, the result containssas its only part.(regexes/split s re) → list
(regexes/split s re limit) → list - rem — Returns the remainder with the sign of the dividend. Two integers produce an
exact integer remainder; otherwise the result is a float. A zero divisor is an
error. The minimum integer divided by
-1has remainder zero.(rem dividend divisor) → number - remove — Removes the entry selected by
pathfromrootin place and returns the same root collection. Removes a map member or a list element, shifting later list elements left. Empty parent collections are not removed. A missing key, out-of-range nonnegative index, or missing ornullintermediate value leavesrootunchanged. No containers are created.(remove root path) → collection - rest — Returns a fresh sequence without the first element. A pointer produces a
pointer; an empty list produces
[]and an empty pointer produces the root pointer.(rest list) → list - schemas/check — Generates isolated calls from a declared contract or an exact inferred signature.
The default options are
{seed 0 cases 1000 size 8192}.casesmust be from 1 through 1,000,000;sizemust be from 1 through 8,192 choices per case. A declared contract is an obligation to test, not proof of correct behavior. Approximate inference alone returns<unsupported>.(schemas/check function) → report
error
(schemas/check function options) → report
error - schemas/explain — Returns
nullwhenvaluematchesschema. A mismatch returns a structured#err <schema-mismatch>value. An invalid schema returns a separate#err <invalid schema>value.(schemas/explain schema value) → null
error - schemas/fakerize — Makes a random value that matches
schema. The function advances the supplied random generator. Equal generator states and equal schemas produce equal values.(schemas/fakerize generator schema) → value
error
(schemas/fakerize generator schema options) → value
error - schemas/join — Returns a schema accepting values from any operand.
(schemas/join schemas*) → schema - schemas/load — Reconstructs a named schema from definition data returned by
documents/value. A self-contained definition is a(defschema name description)source form. A definition that refers to other named schemas or predicate functions uses a finite graph with explicit definition identities and reference bindings. Same-named definitions in different namespaces remain distinct.(schemas/load definition) → schema - schemas/match — Evaluates
candidateonce. It checks branches in source order and selects the first matching pattern with a true guard.(schemas/match candidate (pattern [when guard] body...) ...) - schemas/materialize — Creates a concrete value only when the schema determines one. It can select a
literal, a forced value, or a
defaultpreference. It does not convert values. Defaults do not restrict accepted values;schemas/valid?ignores them. Write a preference beside its constraint, for example[meet int? [default 8080]].(schemas/materialize schema) → value
error - schemas/meet — Returns the intersection of its operands. Incompatible builtin constraints
reduce to
never:(schemas/meet int? string?)and(schemas/meet int? [not int?])arenever. Open shapes without a name meet field by field, so(schemas/meet {active [is = true]} {name string?})is one shape with both fields. A field stays optional only when it is optional in every shape.(schemas/meet schemas*) → schema - schemas/simplify — Returns a simplified schema without changing its input. It reduces supported
combinations at the root and within map fields, lists and collection constraints.
(schemas/simplify schema) → schema - schemas/valid? — Tests a value against a schema without converting it. A schema is one of four
things:
(schemas/valid? schema value) → boolean - seq — Returns the elements of a list, pointer, Bytes or Bitset as a list. A Bitset
supplies its members in ascending order.
nullgives an empty list.(seq value) → list - sort — Sorts
listin place, stably, and returns the same list, without copying its elements. The list's order changes only after all comparisons succeed.listmust be a list, notnullor a pointer. By default, sorts in ascending order and requires all elements to have the same kind. Orderable kinds are null, boolean, integer, float, string, link, UTC, duration, SHA-256, and pointer. Pointer segments compare lexicographically, with an index before a key; a shorter prefix sorts before its extension. Integers and nominal integer payloads compare exactly. Strings compare by Unicode code point order, booleans putfalsebeforetrue, and SHA-256 values compare their bytes. Null values tie.(sort list) → list
(sort comparator list) → list - sphere? — Returns
truefor a#spherevalue, a sphere, otherwisefalse. Another packed kind with the same number of components, or a list of the components, is not one.(sphere? value) → boolean - str — Converts zero or more
valuesto strings and concatenates them in argument order. It inserts no spaces or other separators. With no arguments, returns the empty string.(str values*) → string - string? — Returns
trueifsis a string, otherwisefalse.(string? s) → boolean - strings/blank? — Returns
trueifsisnull, empty, or contains only whitespace, otherwisefalse.(strings/blank? s) → boolean - strings/case — Converts
valuewith one case selector or a list of selectors. A list applies the conversions from left to right. An empty list returns the input unchanged. The selector and input must be strings. Unknown selectors produce an error.(strings/case case value) → string
(strings/case cases value) → string - strings/ends-with? — Returns whether the string ends with the literal
suffix. Every string ends with the empty string.(strings/ends-with? string suffix) → boolean - strings/escape — Escapes text for the specified mode. With only a mode, returns a unary function
that escapes its argument, for use as a template's
escapeoption. The function prints and hashes as its call, such as(strings/escape "html-text"), and renders a template argument before escaping it.(strings/escape mode text) → string
(strings/escape mode) → function - strings/humanize — Formats an integer, float, duration, or UTC value as readable text. Options are
a map with string keys. Unknown options and options irrelevant to the value's
kind are errors.
(strings/humanize value options?) → string - strings/includes? — Returns whether the string contains the literal
search. Every string includes the empty string.(strings/includes? string search) → boolean - strings/index-of — Returns the first index of the string
valueinsat or afterstart, ornullif not found.(strings/index-of s value) → integer or null
(strings/index-of s value start) → integer or null - strings/join — Joins a list of strings with
separatorbetween consecutive elements. An empty list produces the empty string. Elements and the separator must be strings.(strings/join strings separator) → string - strings/last-index-of — Returns the last index of the string
valueinsat or beforestart, ornullif not found.(strings/last-index-of s value) → integer or null
(strings/last-index-of s value start) → integer or null - strings/normalize — Returns
snormalized to the Unicode normalizationform, defaulting toNFC.(strings/normalize s) → string
(strings/normalize s form) → string - strings/of — Returns the string formed by the Unicode scalar values in the list
points, in order.(strings/of points) → string - strings/replace — Replaces non-overlapping literal occurrences of
search, from left to right. An empty search insertsreplacementbefore, between, and after the input's Unicode code points:(strings/replace ab "" x)returnsxaxbx.(strings/replace string search replacement) → string - strings/replace-first — Returns
swith the first occurrence ofmatchreplaced byreplacement.(strings/replace-first s match replacement) → string - strings/split — Splits at each literal occurrence of
separator, preserving empty fields. An empty separator splits into Unicode code points; splitting an empty string with an empty separator returns a list containing the empty string.(strings/split string separator) → list
(strings/split string separator limit) → list - strings/split-lines — Returns the lines of
sseparated by LF or CRLF, without their line endings.(strings/split-lines s) → list - strings/starts-with? — Returns whether the string begins with the literal
prefix. Every string starts with the empty string.(strings/starts-with? string prefix) → boolean - strings/substring — Returns the code points from
startup to, but excluding,end. Withoutend, returns the rest of the string. Both indices must be integers between zero and the string length, andstartmust not exceedend. Other indices produce#err <bounds index>.(strings/substring string start) → string
(strings/substring string start end) → string - strings/trim — Returns
swith whitespace ortextremoved from the ends selected byopts.(strings/trim s opts) → string
(strings/trim s text opts) → string - strings/trim-prefix — Returns
swithoutprefixwhensstarts with it, otherwises. It removes one match. An emptyprefixleavessunchanged.(strings/trim-prefix s prefix) → string - strings/trim-suffix — Returns
swithoutsuffixwhensends with it, otherwises. It removes one match. An emptysuffixleavessunchanged.(strings/trim-suffix s suffix) → string - strings/unescape — Decodes text for the same modes as
strings/escape. With only a mode, returns a unary decoding function that prints and hashes as its call, such as(strings/unescape "url-query-value"). Invalid JSON Pointer, URL percent, CSV, and quoted string escapes produce#err <invalid value>, as do URL percent escapes whose bytes are not UTF-8, since strings are always Unicode text. HTML decoding recognizes semicolon-terminated named and numeric character references.(strings/unescape mode text) → string
(strings/unescape mode) → function - strings/words — Splits text at runs of Unicode WhiteSpace, omitting empty fields. Leading and
trailing whitespace need no separate trim. Empty or whitespace-only text
returns
[]. Punctuation remains part of each word.(strings/words text) → list - tagged? — Returns
truefor a tagged value, otherwisefalse. An error is not tagged data:error?tests for one.(tagged? value) → boolean - template? — Returns
trueifvalueis a string template, otherwisefalse.(template? value) → boolean - time/duration — With one argument, a number supplies a raw 100 ns tick count and a string
supplies an ISO duration. A float is rounded to the nearest tick, with halfway
cases rounded away from zero and a minimum of one tick in magnitude for
nonzero values:
(time/duration 1.5)is two ticks.(time/duration value) → duration
(time/duration amount unit) → duration - time/duration? — Returns whether the value has the duration kind. UTC timestamps and integers
return
false.(time/duration? value) → boolean - time/format — Formats a UTC timestamp or duration as its canonical ISO string, without a
DUST tag prefix. The full 100 ns tick precision is retained. For readable display text,
use the String library's
strings/humanizefunction.(time/format value) → string - time/now — This function requires the
ioplugin. It reads the host clock. Theclocksetting of theioplugin can stop the calls (Scheduled reactor settings). A stopped call returns#err <clock denied>.(time/now) → UTC - time/parts — Returns integer fields
year,month,day,hour,minute,second,nanosecond, andweekday. Months and days start at one. ISO weekdays run from one for Monday through seven for Sunday. The nanosecond field is the fractional part of the second, from zero through999999900in multiples of 100.(time/parts timestamp) → map - time/round — Returns the nearest multiple of
quantum, with halfway cases rounded away from zero. At a one-second quantum,1.5sbecomes2sand-1.5sbecomes-2s.(time/round duration quantum) → duration - time/shift — Shifts by a map containing integer
years,months, anddaysoffsets. Omitted offsets are zero; negative offsets move backward. Unknown fields and non-integer offsets are errors.(time/shift timestamp changes) → UTC - time/start-of — Returns the start of the containing UTC calendar unit. The unit is one of
year,month,week,day,hour,minute, orsecond. This floors to the earlier boundary, including for times before the Unix epoch. A week's Monday can fall in the preceding month or year.(time/start-of timestamp unit) → UTC - time/truncate — Returns the multiple of
quantumreached by truncating toward zero. For example,1.9sbecomes1sand-1.9sbecomes-1sat a one-second quantum.(time/truncate duration quantum) → duration - time/units — Expresses a UTC timestamp or duration in the requested unit. The unit argument
comes first. For UTC, the result measures time since the Unix epoch; for a
duration, it measures the elapsed interval. The underlying value remains a
signed count of 100 ns ticks.
(time/units unit value) → number - time/utc — An integer supplies a raw count of 100 ns ticks since the Unix epoch. A string
supplies a UTC timestamp ending in
Z. A float supplies a Julian day, following SQLite's Julian-day convention: day0.0is-4713-11-24T12:00:00Z,2440587.5is the Unix epoch, and2451545.0is2000-01-01T12:00:00Z.(time/utc value) → UTC - time/utc? — Returns whether the value has the UTC kind. Durations and integers return
false.(time/utc? value) → boolean - triangle? — Returns
truefor a#trianglevalue, a triangle, otherwisefalse. Another packed kind with the same number of components, or a list of the components, is not one.(triangle? value) → boolean - true? — Returns
trueifvalueis the booleantrue, otherwisefalse.(true? value) → boolean - unquote — Evaluates the enclosed form within its matching quasiquote and substitutes
the resulting value. Outside quasiquote, this is an error.
See Quotation forms for prefix syntax and encoding.
#unquote form - unquote-splicing — Evaluates the enclosed list within its matching quasiquote and inserts its
elements into the surrounding list. A non-list result or a splice outside a
list-element position is an error.
See Quotation forms for prefix syntax and encoding.
#unquote-splicing form - unquote-splicing? — Returns
truefor an unquote-splicing form, such as the value of`,@x, otherwisefalse.(unquote-splicing? value) → boolean - unquote? — Returns
truefor an unquote form, such as the value of`,x, otherwisefalse.(unquote? value) → boolean - utc? — Returns
truefor a UTC timestamp, otherwisefalse. It is the kind predicate thattime/utc?also provides.(utc? value) → boolean - uuid? — Returns
truefor a UUID, otherwisefalse. A string that spells a UUID is not one.(uuid? value) → boolean - v2? — Returns
truefor a#v2value, a two-dimensional vector, otherwisefalse. Another packed kind with the same number of components, or a list of the components, is not one.(v2? value) → boolean - v3? — Returns
truefor a#v3value, a three-dimensional vector, otherwisefalse. Another packed kind with the same number of components, or a list of the components, is not one. As a schema,v3?accepts a#v3field value.(v3? value) → boolean - v4? — Returns
truefor a#v4value, a four-dimensional vector, otherwisefalse. Another packed kind with the same number of components, or a list of the components, is not one.(v4? value) → boolean - values — Returns map values in the same ascending key order used by
keys.(values map) → list - vf? — Returns
truefor a#vfvalue, a packed vector of Float lanes, otherwisefalse. A#vivalue, a fixed packed value such as#v3, or a list of numbers is not one.(vf? value) → boolean - vi? — Returns
truefor a#vivalue, a packed vector of Integer lanes, otherwisefalse. A#vfvalue or a list of integers is not one.(vi? value) → boolean - when — Runs a body when its test is truthy.
(when test body...) - when-not — Runs a body when its test is falsey.
(when-not test body...)
Footnotes:
Because DUST forms have a JSON representation, keys are always (always!) strings.