[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"project-107786":3},{"id":4,"name":5,"fullName":6,"owner":7,"repo":5,"description":8,"homepage":9,"htmlUrl":9,"language":10,"languages":9,"totalLinesOfCode":9,"stars":11,"forks":12,"watchers":13,"openIssues":14,"contributorsCount":15,"subscribersCount":15,"size":15,"stars1d":16,"stars7d":17,"stars30d":18,"stars90d":15,"forks30d":15,"starsTrendScore":19,"compositeScore":20,"rankGlobal":9,"rankLanguage":9,"license":21,"archived":22,"fork":22,"defaultBranch":23,"hasWiki":24,"hasPages":22,"topics":25,"createdAt":9,"pushedAt":26,"updatedAt":27,"readmeContent":28,"aiSummary":29,"trendingCount":15,"starSnapshotCount":15,"syncStatus":16,"lastSyncTime":30,"discoverSource":31},107786,"zed","zedlanguage\u002Fzed","zedlanguage","A reactive dataflow programming language for the AI era, with automatic parallelization and very high standards of static verification",null,"Rust",200,7,5,1,0,2,12,131,11,62.71,"MIT License",false,"main",true,[],"2026-11-23 20:29:35","2026-11-23 06:49:06","> [!NOTE]\n> **Zed is still under construction and is not yet ready for use, but it is coming soon.**\n> Releases will be announced at [x.com\u002Fzedlang](https:\u002F\u002Fx.com\u002Fzedlang). This page describes the language as it will be when finished.\n\n\u003Cp align=\"center\">\n  \u003Cimg src=\"docs\u002Fassets\u002Fbanner.svg\" alt=\"Zed\" width=\"512\">\n\u003C\u002Fp>\n\nZed is a programming language that looks like ordinary code, but has no variables you overwrite and no statement order you have to get right. A Zed program is a set of definitions: each value says what it depends on, and the compiler works out the rest. Because the compiler can see that whole graph of dependencies, it can run your code in parallel, free memory without a garbage collector, recompute only what changed when an input changes and reject many bugs before the program runs.\n\n- [Notation](#notation): the syntax, words and terms used on this page\n- [A first program](#a-first-program)\n- [The basics](#the-basics): bindings, functions, numbers, strings, structs, unions, generics, modules\n- [Failure is a value](#failure-is-a-value)\n- [Collections](#collections): maps, grouping, remapping, reducing, pushing, joins, chunks, matrices\n- [Time and repetition](#time-and-repetition): recurrences, loops, methods, running only what's needed\n- [The outside world](#the-outside-world): ports, retries, databases, incremental updates\n- [Checks at compile time](#checks-at-compile-time): ranges, units, taint, cost\n- [Code that runs at build time](#code-that-runs-at-build-time): partial evaluation, reflection, grammars, symbolic math\n- [Tests, laws and proofs](#tests-laws-and-proofs)\n- [Under the hood](#under-the-hood): error messages, C, memory, parallelism, targets\n\n## Notation\n\nThis section lists all the syntax, words and terms the examples on this page use, so you can look up anything you don't recognize. Most of them come back with an example in the tour. If you'd rather start with code, [skip to the first program](#a-first-program) and come back when you need to.\n\n### Conventions on this page\n\n| Form | Meaning |\n|---|---|\n| `\u002F\u002F text` | A comment. |\n| `\u002F\u002F ✗ rejected` | A commented-out line that the compiler rejects, with the reason. |\n| `...` in a **Syntax** line, `x`, `T`, `op`, `pattern`, `fallback`, `#someFailure` | Placeholders for code you would write. In real code, `...` has the one meaning given below. |\n| `before:`, `after:` | The inputs and results of the example, in the plain-text blocks and tables below each one. They are not Zed code. |\n\n### Definitions and functions\n\n| Syntax | Meaning |\n|---|---|\n| `name = value;` | A *binding*: gives a name to a value, once. Definitions can come in any order. |\n| `name: T = value;` | A binding with a stated type. |\n| `name: T;` | Declares a name and its type, with the value given elsewhere: an input, a foreign function, or a map filled by pushes. |\n| `f(x) = expression;` | A function whose body is one expression. |\n| `f(x) -> T { ... }`, `f(x) { ... }`, `f(x) -> T = expression;` | A function with a stated result type, a block body or both. The last expression, or `return`, gives the result. |\n| `positional x` | A parameter passed by position. Other parameters are passed by name, as in `f(x: 1)`. |\n| `y = default` in a parameter list | A parameter that can be left out. |\n| `(T) -> U` | The type of a function from `T` to `U`. |\n| `x -> expression` | An unnamed function (a lambda). With a type: `(x: rat) -> x + 1r`. |\n| `a.f(b)`, `5.double` | A call with the dot: `a.f(b)` is `f(a, b)`, and `5.double` is `double(5)`. |\n| `f(x, ...)` | A call that leaves the remaining named parameters open, and gives back a function that takes them. |\n| `(+)` | An operator used as a function. |\n| `x, y = e;` | Binds each name to a part of a result that has several parts. |\n| `field:` in `{ mean:, sd: }` or `Circle(radius:)` | Short for `field: field`. In a pattern it reads the field into a name of the same spelling. |\n| `this` | Inside a method: the value the method was called on. |\n| `return e;` | Ends a block body with the result `e`. |\n| `if c { a } else { b }` | A choice between two values. |\n| `match x { pattern -> value, ... }` | Picks the arm whose pattern fits `x`. The arms must cover every case. |\n| `for x in a { ... }`, `for x in a, y in b where c { ... }` | Builds a map with one entry per element, or per combination the `where` lets through. |\n| `loop { ... }`, `loop t { ... }` | A repeated step, with `t` as its optional step counter. The loop is a value holding the final state and the history. |\n| `until c;`, `while c;` | Stop conditions of a loop: `until` is tested after each step, `while` before it. |\n| `x' = e` | The value of `x` in the next step of a loop or the next version of a struct. |\n| `x' = e with x = start` | The same, with the value of `x` before the first step. |\n| `x[i] = e with x[-1] = start;` | A recurrence: an array defined by an equation, with its boundary value at the index just below the first. |\n| `i in 0..` inside `d[i in 0..]` | This entry is defined for every `i` in the range. |\n| `x*.method()` | A call in a loop body that also replaces `x` in the next step. |\n| `test { input -> output, ... }` | A table of test cases attached to a definition, run at build time. |\n| `law name(x: T) = expression;` | A claim that a `bool` expression holds for every `x`. |\n| `import a.b;`, `import a.b as c;`, `import a.b.{x, y};` | Imports a module whole, under another name, or by listing names. |\n| `local` | Keeps a definition private to its file. |\n| `main(input: T) -> (output: U) { ... }` | A program's entry point. Its parameters are input ports and its results are output ports. |\n| `@name` | An annotation: a claim or request the compiler acts on or checks. They are listed below. |\n\n### Operators\n\n| Syntax | Meaning |\n|---|---|\n| `+ - *` | Arithmetic. `*` also scales a vector or matrix by a number. |\n| `\u002F` | Division on `f64` and `rat`. It does not apply to `int`. |\n| `a div b`, `a mod b` | Integer quotient and remainder. |\n| `**` | Power. |\n| `== != \u003C \u003C= > >=` | Comparison. `==` compares structure, by value. |\n| `\\|\\|` | Logical or. |\n| `a ++ b` | Joins two strings or lists. |\n| `x in s` | True if `x` is a member of `s`. |\n| `x is T`, `x is not T` | Tests whether a value has a type. |\n| `m[k]`, `p.x`, `f(x)` | Lookups, in a map, a struct and a function. |\n| `x::word` | Reads a fact about `x`, such as its length or its type's fields. The facts are listed below. |\n| `x else d` | Gives `d` in place of a failure. `x else #a -> d` replaces only the atom `#a`. |\n| `x?.field` | Reads a field if there is one, and passes a failure along if there isn't. |\n| `m >\u003C op` | *Reduces* the innermost level of `m` with the operator `op`. |\n| `m >\u003C op else d` | The same, with `d` as the answer for an empty collection. |\n| `unordered` after `m >\u003C op` | Gives up the fixed floating-point result in exchange for speed. |\n| `m as (pattern) into (pattern)` | A *remap*: names the shape `m` has and the shape you want. |\n| `k >\u003C op` inside a pattern | Collapses the level `k` with `op`. |\n| `desc k`, `asc k` | Orders by `k`, high to low or low to high. |\n| `_` in a pattern | Drops the value at that place. |\n| `name \u003C- v`, `name[k] \u003C- v` | Pushes a value out of a port, or into one key of a map. |\n| `e with name(args)` | Attaches a *facet* or a port setting to a value or type. They are listed below. |\n| `x with { field = value }` | A copy of a struct with some fields changed. |\n\n### Values and literals\n\n| Syntax | Meaning |\n|---|---|\n| `42`, `1.5`, `3r`, `2n` | An `int`, an `f64`, a `rat`, and a generic number that takes whichever number type is expected. |\n| `\"text\"`, `\"${e}\"` | A `Utf8String`, with `e` written into it. |\n| `#name`, `#name(args)` | An *atom*: a constant that is its own name, with or without a payload. |\n| `[a, b, c]` | An array, whose keys are `0`, `1`, `2`. |\n| `{ k -> v, ... }` | A map, written out. |\n| `{ a, b }` | A set. |\n| `{ x: 1, y: 2 }`, `Name(x: 1)` | A struct value, without and with a declared name. |\n| `(a, b)` | A tuple. |\n| `a..\u003Cb`, `a..=b`, `a..` | Ranges: excluding `b`, including `b`, and with no upper end. |\n\n### Types\n\n| Syntax | Meaning |\n|---|---|\n| `int` | A mathematical integer. It can't overflow. |\n| `char32` | A Unicode code point, distinct from an integer. `char32(\"Z\")` constructs one. |\n| `int[a..=b]`, `int[a..]` | An integer in a range. |\n| `f64`, `rat`, `bool`, `u8` | A 64-bit float, an exact rational, true or false, and an integer from 0 to 255. |\n| `Utf8String`, `U8String`, `Utf16String`, `Utf32String` | String types, one per encoding. String literals are `Utf8String`. |\n| `K -> V` | A map with a value at every key of `K`. A function type too. |\n| `K ->? V` | A map that may lack some keys of `K`, so a lookup can give `#notFound`. |\n| `a -> b -> v` | A nested map: `a -> (b -> v)`. Each arrow adds one *level* of keys. |\n| `[T]` | An array of `T`. |\n| `[T; n]`, `[T; r, c]` | A vector of length `n` and a matrix of `r` rows and `c` columns. |\n| `A \\| B` | A *union*: a value that is either an `A` or a `B`. Its *members* are `A` and `B`. |\n| `T` (capitalized and otherwise undefined) | A type variable, when used at least twice in a signature, or in the signature and the body. |\n| `struct Name { field: T, field: T = default }` | A record type. Its fields can have defaults. |\n| `Name.method = e;`, `Name.method() { ... }` | A method: a function with an implicit first parameter, whose fields are in scope. |\n| `type Name = T;`, `type Name(T) = ...;` | A name for a type, with or without type parameters. |\n| `interface Name { ... }` | A list of fields and laws. Any value that has them fits it. |\n| `grammar { ... }` | A parser and serializer in one definition, on a struct or after `matching`. |\n| `T matching grammar { ... }` | The values of `T` that a grammar accepts. |\n| `\"(\"`, `x: T`, `a sep b`, `a*`, `digit` in a grammar | Literal text, a field, a list of `a` separated by `b`, zero or more of `a`, and one decimal digit. |\n| `Files`, `Lines`, `Stream(T)` | Port types: files by path, lines of text, and a sequence of values over time. |\n\n### Failure atoms\n\n| Atom | Meaning |\n|---|---|\n| `#notFound` | A lookup found no entry. |\n| `#none` | There is nothing here: an empty selection, or the missing side of a left join. |\n| `#empty` | A reduction with nothing to reduce. |\n| `#collision` | Two entries landed on one key, where a claim that the key is unique was wrong. |\n| `#divByZero` | A division by zero: `div` or `mod`, or `\u002F` on `rat`. |\n| `#inexact` | A number conversion that can't keep the exact value. |\n| `#invalid` | A value failed a `refine` or a type check at run time. |\n| `#syntaxError`, `#parseError` | Text doesn't parse. |\n| `#ioError`, `#dbError`, `#timeout` | A port failed, a database failed, or a deadline passed. |\n\nOther atoms on the page, such as `#red` or `#goNs`, are data the examples define. `#left`, `#orderId`, `#fixed`, `#big`, `#clean` and `#userInput` are arguments to the words they follow. `#block`, `#dropOldest` and `#full` say what a full queue does, and `#unbounded` is what a cost reads when no bound could be proved.\n\n### Words from the standard library\n\n| Word | Meaning |\n|---|---|\n| `m.map(x -> e)` | Replaces each value and keeps the keys. |\n| `m.where(x -> c)` | Keeps the entries whose value passes, with their keys. |\n| `m.group(x -> key)` | Adds a level of keys above the existing ones. |\n| `m.rekey(x -> key)` | Replaces the key. The compiler needs evidence that the new key is unique. |\n| `m.sort(desc x -> x)` | Orders by the given key. |\n| `m.rank` | Flattens an ordered nested map into one list numbered in that order. |\n| `m.chunkBy(x -> key)` | Splits an ordered collection wherever the key changes. |\n| `m.flatMap(x -> list)` | Maps each value to a list, with the list's positions as a new level. |\n| `a.join(b, on: #field, kind: #left)` | Pairs entries of `a` and `b` on a field. |\n| `a.diff(b, on: #field)` | The entries of `a` that have no match in `b`. |\n| `.count`, `.sum` | Reduces the innermost level to its number of entries, or to their sum. |\n| `.first`, `.last` | The value at the lowest or highest key, in the collection's order. |\n| `.foldl(init, op)`, `.foldr` | A fold from the left or the right, for an operator that can't be regrouped. |\n| `m.allOk` | `m` if no entry holds a failure, and otherwise the failures. |\n| `.image`, `.union` | The set of a map's values, and the union of two sets. |\n| `p.implies(q)` | Logical implication. |\n| `x.refine(p)` | `x`, or `#invalid` if the condition `p` fails. |\n| `min`, `max`, `sqrt`, `log`, `pi` | The usual math functions and constant. `min` and `max` work as operators for `>\u003C`. |\n| `fs[path]`, `read(path)` | Reads a file from the port `fs`; `read` is short for that lookup. |\n| `.split`, `.lower`, `.len` | Splits a string on a separator, lowers its case, and gives a length. |\n| `a.matmul(b)`, `dot`, `cross` | Matrix product, dot product and cross product. |\n| `f64(n)`, `int(s)`, `char32(\"Z\")` | Checked conversions between types. |\n| `stdout` | The port for standard output. `\u003C-` writes to it. |\n| `x.patch(edit)` | Applies an edit to a map or document and gives the new version. |\n| `T.parse(s)`, `x.serialize` | A grammar's parser and serializer. |\n| `Json.decode(s)` | Decodes JSON into the type expected at the call. |\n| `expand`, `derivative`, `compile` | Rewrites a function's source, differentiates it, and turns source back into a function. |\n\n### Facts read with `::`\n\n| Syntax | Meaning |\n|---|---|\n| `x::len` | The number of entries, or of steps in a loop. |\n| `run::frames` | Every step of a loop. |\n| `text::codepoints`, `text::u8` | A string viewed by code point or by UTF-8 unit. |\n| `T::fields`, `T::shape`, `T::values` | A type's fields, its structure, and the members of a set of atoms. |\n| `x::constraints` | What the compiler knows about a value. |\n| `f::source` | A function's source, as a value. |\n| `f::cost`, `f::depth` | Upper bounds on a function's work and parallel depth. |\n\n### Annotations\n\n| Annotation | Meaning |\n|---|---|\n| `@associative`, `@commutative` | Claims that an operator can be regrouped or reordered. |\n| `@ensure` | Forbids a run-time check in this definition: the condition has to be proved instead. |\n| `@injective` | Claims that a function never gives two inputs the same result. |\n| `@memoized` | The build fails if this value isn't kept for reuse. |\n| `@cost(b)`, `@fused`, `@noalloc`, `@preallocated` | Performance claims the build checks: a work bound, no intermediate collection, no memory beyond registers, a bounded footprint reserved at entry. |\n| `@exhaustive` | Run the tests on every input of a finite domain. |\n| `@proved`, `@strict`, `--strict` | Make the build fail on a law that isn't proved. `--strict` is a compiler flag. |\n| `@foreign(\"lib\", \"symbol\")`, `@export(\"c\", \"symbol\")` | Calls a C function, and makes a Zed function callable from C. |\n| `@stateless` | A promise that a foreign function has no state, so it can be retried. |\n| `@hash` | The content hash that pins an import. |\n\n### Facets and port settings, written with `with`\n\n| Word | Meaning |\n|---|---|\n| `units(\"m\u002Fs\")` | A physical unit, checked through arithmetic. |\n| `taint(#label)` | A label that follows a value through the program. |\n| `reducer(op)` | How values pushed to one key of a map merge. |\n| `store(...)`, `postgres(...)`, `kv(...)`, `sql(...)` | Makes a map a stored table: in Postgres, in a key-value store, with a schema read from an SQL file. |\n| `timeout(d)`, `retry(n, backoff: b)`, `bound(n, overflow: policy)` | A deadline, repeat attempts, and a queue's size limit with what happens when it is full. |\n| `bits(n)`, `endian(#big)`, `length(n)` | Binary layout in a grammar: a field's width, its byte order, its element count. |\n\n### Terms\n\n| Term | Meaning |\n|---|---|\n| key, value, entry | A map sends each *key* to a *value*, and a key with its value is an *entry*. |\n| level | One layer of keys in a nested map. `a -> b -> v` has the two levels `a` and `b`. |\n| keypath | The chain of keys that leads to a value, such as `(a, b)`. |\n| rank | A position in an order: a key `0`, `1`, `2`, and so on. Values that tie share a rank when `desc` or `asc` adds the level. |\n| remap | Changing a map's shape by moving, adding or dropping levels. |\n| reduce, reduction, fold | Merging the values of a level into one, with an operator. |\n| failure | An atom in a value's type that says the operation didn't give a result. |\n| domain | The keys or inputs a map or function is defined on. |\n| bounds check | The run-time test that an index is in range. |\n| rope | A string or list stored as a tree of pieces, so joining two takes constant time. |\n| facet | An extra fact about a value, tracked through every operation at compile time. |\n| taint | A label for where a value came from, such as user input. |\n| port | A declared channel to the outside world: a file, socket, clock or database. |\n| wave | A batch of new input values passing through the program's graph. |\n| work, parallel depth | *Work* is the total number of operations. *Parallel depth* is the longest chain of them that must run one after another. |\n| effect system | Type annotations that record a function's side effects. |\n| memoize | Keep a result so that later uses don't compute it again. |\n| law | A claim about your code, which the compiler tries to prove and otherwise tests. |\n| associative, commutative | `(a op b) op c == a op (b op c)`; and `a op b == b op a`. |\n| identity | A value that leaves the other operand unchanged, such as 0 for addition or 1 for multiplication. |\n| `Monoid`, `CommRing` | Interfaces from the library for algebraic structures: an associative operator with an identity; and addition with multiplication, where multiplication commutes. |\n| grade | How far the compiler got with a law: for example proved, tested or assumed. |\n| partial evaluation | Running the parts of a program whose inputs are known at build time. |\n| specialize | Produce a version of a function for known types or values, with the generic steps gone. |\n| proof checker | A small program that validates a proof step by step. |\n| decidable | Answerable by an algorithm that always finishes. |\n| linear arithmetic | Sums of variables times constants, with comparisons. |\n| SMT solver | A general automated theorem prover, as used by many verification tools. |\n| fixpoint | A value that one more step doesn't change. |\n| model checking | Checking a property on every state a system can reach. TLC is a widely used model checker. |\n| liveness, fairness | *Liveness*: something good eventually happens. *Fairness*: an assumption that no ready action is put off forever. |\n| safe to repeat, idempotence | Doing it twice has the same effect as doing it once. |\n| hedged request, circuit breaker, failover | Sending a second copy of a slow request; refusing calls for a while after repeated failures; switching to a replacement server. |\n| scan, parallel scan | A computation that gives each running result, such as the running totals of a list. A parallel scan does this on many cores at once. |\n| hash join, merge join | Two standard ways to compute a join without comparing every pair. |\n| exact reference counting | Freeing a value when a count of its users reaches zero, with no count left too high by cycles. |\n| arena | A block of memory whose contents are all freed together. |\n| id-indexed graph | A graph whose nodes are stored in a table and refer to each other by key. |\n| intermediate representation | The form a compiler holds a program in, between source code and machine code. |\n| kernel | The small core that the rest of a compiler is built on. |\n| distributed dataflow | Running a program across many machines, with data sent between them along its dependency graph. |\n| back end | The part of a compiler that produces code for one target. |\n| MLIR, LLVM, Clang | Standard compiler infrastructure, and the C compiler built on LLVM. |\n| WebAssembly | A portable binary format that runs in browsers and elsewhere. |\n| hardware synthesis | Producing a circuit design in place of machine code. |\n\n## A first program\n\nHere is a complete program. It splits a file on spaces, counts each word, and prints the counts, most common first.\n\n```zed\nmain(fs: Files) -> (stdout: Lines) {\n  text = fs[\"input.txt\"] else \"\";\n  counts = text.split(\" \").group(w -> w.lower).count;\n  lines = counts as (w -> n) into (desc n -> w -> \"${w}: ${n}\");\n  stdout \u003C- lines.rank;\n}\n```\n\n`group` collects the words by their lowercase form, and `.count` turns each group into its size. The `as ... into ...` line reshapes that table: `desc n` sorts by count, `w` stays as a level below it so equal counts don't collide, and each value becomes a line of text. `.rank` flattens the nested table into a list numbered in that order, and `\u003C-` writes the lines out.\n\nThese tables show the data after each step, for a file whose whole text is `to be or not to be`. Each column but the last is one level of keys, and the last column holds the values. Where a table has several columns after its keys, they are parts of one value, or an input shown beside its result. A key is printed once and covers every row inside its box, and rows are listed in key order. This page draws most of its data-shaping examples this way.\n\n```text\nafter text.split(\" \")    after .group(w -> w.lower)    after .count\n+---+-----+              +---------+---+-----+         +-----+---+\n| i | w   |              | w.lower | i | w   |         | w   | n |\n+===+=====+              +=========+===+=====+         +=====+===+\n| 0 | to  |              | be      | 1 | be  |         | be  | 2 |\n| 1 | be  |              |         | 5 | be  |         | not | 1 |\n| 2 | or  |              +---------+---+-----+         | or  | 1 |\n| 3 | not |              | not     | 3 | not |         | to  | 2 |\n| 4 | to  |              +---------+---+-----+         +-----+---+\n| 5 | be  |              | or      | 2 | or  |\n+---+-----+              +---------+---+-----+\n                         | to      | 0 | to  |\n                         |         | 4 | to  |\n                         +---------+---+-----+\n\nafter as (w -> n) into (desc n -> w -> \"${w}: ${n}\")    after .rank\n+------+-----+--------+                                 +---+--------+\n| rank | w   | line   |                                 | i | line   |\n+======+=====+========+                                 +===+========+\n| 0    | be  | be: 2  |                                 | 0 | be: 2  |\n|      | to  | to: 2  |                                 | 1 | to: 2  |\n+------+-----+--------+                                 | 2 | not: 1 |\n| 1    | not | not: 1 |                                 | 3 | or: 1  |\n|      | or  | or: 1  |                                 +---+--------+\n+------+-----+--------+\n```\n\nThe program doesn't mention threads, locks or allocation. The compiler can run the grouping on all your cores, and the output is the same, bit for bit, on one core or on sixty-four. A missing file can't crash the program either: the type of `fs[\"input.txt\"]` says the read can fail, and the `else` says what to do when it does.\n\nThree more short examples from the tour below:\n\n```zed\n\u002F\u002F Two values landing on one key is a compile error, never a silent overwrite.\n\u002F\u002F totals = sales as (region -> sku -> amount) into (region -> amount);   \u002F\u002F ✗ rejected\n\u002F\u002F Say how they merge: add the amounts for each region.\ntotals = sales as (region -> sku -> amount) into (region -> sku >\u003C (+) -> amount);\n\n\u002F\u002F Edit distance: the equation and its boundary. The compiler picks the table and the fill order.\nd[i][j] = min(d[i-1][j] + 1, d[i][j-1] + 1, d[i-1][j-1] + cost(a[i], b[j]))\n  with d[-1][j in -1..\u003Cb::len] = j + 1, d[i in 0..][-1] = i + 1;\n\n\u002F\u002F A database table, checked against its SQL schema at build time.\norders: OrderId ->? { total: rat, note: Utf8String | #none }\n  with store(postgres(dbUrl, table: \"orders\", schema: sql(\"db\u002Forders.sql\")));\n```\n\nZed exists because many systems already recover a graph of values from ordinary code: spreadsheets, optimizing compilers, Spark, build systems, reactive UI frameworks and out-of-order CPUs. In Zed the graph is the program, so one compiler handles parallel scheduling, memory management, incremental updates and many correctness checks from one structure. This doesn't have to make programs longer: the word-count program above is about as long as the same program in Python.\n\nThe rest of this page is a tour of the language. Each stop opens with a line saying what the feature does and lists its syntax. Most then give an example, explain it and show its inputs and results. Snippets stand alone unless they say otherwise, and a name a snippet doesn't define is an input you can assume. A commented-out line marked ✗ is one the compiler rejects.\n\n## The basics\n\n### Bindings\n\nA binding gives a name to a value.\n\n**Syntax:** `name = value;` or `name: type = value;`\n\n```zed\ntotal = price * quantity;\nprice = 12;\nquantity = 3;\nport: int[1..=65535] = 8080;\n```\n\n```text\nbefore: price = 12, quantity = 3\nafter:  total = 36, port = 8080\n```\n\nA name is bound once. It can't be reassigned, and it can be used above the line that defines it, as `price` is here: the order of definitions doesn't matter, only what depends on what. The type is optional, and it can be more exact than in most languages. `int[1..=65535]` means an integer in that range, and the compiler checks it.\n\n### Functions\n\nA function is a definition with parameters, and a call can name its arguments, chain with dots or leave some open.\n\n**Syntax:** `f(positional x, y = default) = expression;` or `f(...) -> type { ... }`\n\n```zed\ndouble(positional x) = x * 2;\n\nclamp(positional v, positional lo, positional hi) -> int {\n  if v \u003C lo { lo } else if v > hi { hi } else { v }\n}\n\ngreet(positional name: Utf8String, punct = \"!\") = \"Hi, \" ++ name ++ punct;\n\na = 5.double.clamp(0, 8);        \u002F\u002F 8\nb = greet(\"Ann\", punct: \"?\");    \u002F\u002F \"Hi, Ann?\"\nhi = greet(\"Ann\", ...);          \u002F\u002F a function still waiting for punct\n```\n\n```text\nbefore: 5, \"Ann\", \"?\"\nafter:  a = 8, because 5.double is 10 and clamp(0, 8) caps it\n        b = \"Hi, Ann?\"\n        hi(punct: \".\") = \"Hi, Ann.\"\n        hi() = \"Hi, Ann!\"\n```\n\nParameters are passed by name unless you mark them `positional`, so a call site says what its arguments mean. Any function can be called with a dot, so `5.double` is `double(5)`, and pipelines read left to right. A `...` in a call leaves the remaining named parameters open and gives you back a function. Parameter types can usually be left out, and the compiler infers them from how the body uses the parameter. `x * 2` takes an `int`; `x * 2n` would take any number type.\n\n### Numbers\n\nZed has exact integers and rationals as well as floats, and it never converts between them on its own.\n\n**Syntax:** `42`, `1.5`, `3r`, `a \u002F b`, `a div b`, `f64(n)`\n\n```zed\nbig = 2 ** 100;              \u002F\u002F no overflow; this is the exact integer\nthird = 1r \u002F 3r;             \u002F\u002F an exact rational\nhalf = 1.0 \u002F 2.0;            \u002F\u002F f64\nq = 7 div 2;                 \u002F\u002F 3\nratio = f64(q) \u002F 2.0;        \u002F\u002F conversions are written out\n\u002F\u002F bad = q + 1.5;            \u002F\u002F ✗ rejected: int + f64\n```\n\n```text\nbefore: 2, 100, 1r, 3r, 1.0, 2.0, 7\nafter:  big   = 1267650600228229401496703205376\n        third = exactly one third\n        half  = 0.5, q = 3, ratio = 1.5\n```\n\nAn `int` is a mathematical integer. It can't overflow, because the compiler picks its machine representation from the range it can prove, and that is a plain machine word wherever a word is enough. `\u002F` works on fractional types, and integers divide with `div` and `mod`. `r` marks an exact rational, so `0.1r + 0.2r == 0.3r` is true. Zed never converts a number for you: mixing `int` and `f64` is a compile error until you write `f64(n)`. That cast is checked, so its type also includes `#inexact` unless the compiler can show the value fits exactly.\n\n### Strings\n\nA string is a sequence in one stated encoding, and you say what you index it by.\n\n**Syntax:** `\"text\"`, `\"${expression}\"`, `a ++ b`, `text::codepoints[i]`\n\n```zed\nname = \"Zed\";\nline = \"total: ${2 + 3}\";            \u002F\u002F \"total: 5\"\ntitle = \"never\" ++ \"the\" ++ \"less\";\nz = name::codepoints[0];             \u002F\u002F the first code point\n```\n\n```text\nbefore: name = \"Zed\"\nafter:  line = \"total: 5\", title = \"nevertheless\", z = char32(\"Z\")\n```\n\nString literals are UTF-8. Encodings are separate types (`U8String`, `Utf8String`, `Utf16String`, `Utf32String`), and you pick what you index by, such as code points or UTF-8 units, through a named view like `text::codepoints` or `text::u8`. `++` builds a rope in O(1), so joining strings in a loop doesn't go quadratic.\n\n### Structs\n\nA struct is a record of named fields, compared by value and copied with changes.\n\n**Syntax:** `struct Name { field: type, field: type = default }`, `Name(field: value)`, `x with { field = value }`, `Name.method = expression;`\n\n```zed\nstruct Point { x: f64, y: f64 }\nstruct Circle { center: Point, radius: f64 = 1.0 }\n\np = Point(x: 1.0, y: 2.0);\nmoved = p with { x = 3.0 };\nunit = Circle(center: p);\n\nPoint.norm = (x * x + y * y).sqrt;\nsize = p.norm;\n```\n\n```text\nbefore: p    = Point(x: 1.0, y: 2.0)\nafter:  p    = Point(x: 1.0, y: 2.0), unchanged\n        moved = Point(x: 3.0, y: 2.0)\n        unit = Circle(center: Point(x: 1.0, y: 2.0), radius: 1.0)\n        size = the square root of 5.0, about 2.236\n```\n\nConstructors take their arguments by name. `with` makes a copy with some fields changed, and when the compiler can see the original isn't used again, the copy is an update in place with no allocation. A method like `norm` is a function with an implicit first parameter whose fields are in scope. Structs compare by value, and two struct declarations with the same fields are the same type. There are no classes, no inheritance and no object identity.\n\n### Atoms, unions and match\n\nAn atom is a constant named by itself, a union is a choice of types, and `match` takes a union apart.\n\n**Syntax:** `#name`, `#name(args)`, `type T = A | B`, `match x { pattern -> value, ... }`\n\n```zed\nstruct Rect { lo: Point, hi: Point }\ntype Shape = Circle | Rect;\ntype Light = #red | #amber | #green;\n\narea(s: Shape) = match s {\n  Circle(radius:) -> pi * radius * radius,\n  Rect(lo:, hi:) -> (hi.x - lo.x) * (hi.y - lo.y),\n};\n\nnext(positional l: Light) = match l {\n  #red -> #green,\n  #green -> #amber,\n  #amber -> #red,\n};\n```\n\n```text\nbefore: Circle with radius 2.0, Rect from (0.0, 0.0) to (3.0, 2.0), #red\nafter:  area of the Circle = 4 pi, about 12.566\n        area of the Rect   = 6.0\n        next(#red)         = #green\n```\n\nAn atom needs no declaration. A union says a value is one of several things, and atoms with payloads such as `#c(f64) | #f(f64)` tell apart values of the same shape. A `match` must cover every case. If the compiler can't establish that, it shows a value no arm handles or the region it could not resolve. An arm that earlier arms already cover is also rejected.\n\n### Generics and interfaces\n\nGeneric code uses type variables with no declaration, and an interface describes what a value must have.\n\n**Syntax:** `type Name(T) = ...`, `interface Name { ... }`\n\n```zed\ntype Stack(T) = [T];\npush(s: Stack(T), x: T) = s ++ [x];\ntop(s: Stack(T)) -> T | #none = s.last;\n\ninterface Named { name: Utf8String }\nhello(positional n: Named) = \"Hi, ${n.name}\";\n```\n\n```text\nbefore: s = [1, 2], x = 3, n = { name: \"Ann\" }\nafter:  push(s: [1, 2], x: 3) = [1, 2, 3]\n        top(s: [1, 2, 3])     = 3\n        top(s: [])            = #none\n        hello(n)              = \"Hi, Ann\"\n```\n\nAn unbound capitalized name that is used at least twice in a signature, or in the signature and the body, is a type variable, with nothing to declare. Written only once, it is treated as a typo and rejected. Interfaces are structural: any value on which `name` resolves to a `Utf8String` fits `Named`, with no `implements` clause. An interface can also hold laws, so the algebra behind `>\u003C` (the parallel reduction covered below), from `Monoid` to `CommRing`, is ordinary library code.\n\n### Modules\n\nEach file is a module, and an import names what it brings in.\n\n**Syntax:** `import a.b;`, `import a.b as c;`, `import a.b.{x, y};`, `local`\n\n```zed\nimport geometry.shapes.{Point, dist};\n\nfar = dist(Point(x: 0.0, y: 0.0), Point(x: 3.0, y: 4.0));\n```\n\n```text\nbefore: the points (0.0, 0.0) and (3.0, 4.0)\nafter:  far = 5.0, if geometry.shapes defines dist as straight-line distance\n        (the snippet doesn't show that module)\n```\n\nEverything in a file is exported unless marked `local`, and there are no wildcard imports, so you can always tell by reading where a name came from. The build pins each import to the content hash of what it resolved to, with `@hash`.\n\n## Failure is a value\n\n### `else` and `?.`\n\nA function that can fail returns a union with a failure atom in it, and these two forms handle that atom.\n\n**Syntax:** `T | #someFailure`, `x else fallback`, `x?.field`\n\n```zed\nparse: (Utf8String) -> Config | #syntaxError(pos: int);\n\nconf = parse(text) else defaultConfig;\nport = parse(text)?.server?.port else 8080;\n```\n\n```text\nbefore: text parses, with server.port = 9000\nafter:  conf = the parsed Config, port = 9000\n\nbefore: text gives #syntaxError(pos: 3)\nafter:  conf = defaultConfig, port = 8080\n```\n\nThere are no exceptions and no null. A function that can fail says so in its return type, by returning a union with an atom in it. `else` replaces a failure with a fallback, and `?.` reads a field if there is one and passes the failure along if there isn't. An atom of a named union, such as `Light`, is data and not a failure, so `else` keeps it unless you name it: `x else #red -> #green`.\n\nA `Config | #syntaxError` is not a `Config`. Arithmetic and calls on a failure pass it along, so `1 + m[k]` has type `int | #notFound`. The failure stays in the type until you handle it. A reduction is stricter: it is rejected if its operator might be applied to a failure it does not handle, since failures at many keys can't become one result unless you say how.\n\nThe compiler also adds failures only where they can really happen. `a div b` has type `int` when `b` can be shown never to be zero, and `int | #divByZero` when it can't. `xs[i]` is plain `T` when `i` is known to be in range. Prove the bound, and the failure and its run-time check both disappear.\n\n### Failures in a pipeline\n\nFailures sit in collections as ordinary values, so you can test for them and choose what to do with them.\n\n**Syntax:** `r is T`, `r is not T`, `m.allOk`\n\n```zed\nresults = files.map(f -> read(f)).map(b -> parse(b));\n\ngood = results.where(r -> r is Config);\nbad = results.where(r -> r is not Config);\n```\n\n```text\nbefore: files    after: results\n+---+-------+    +---+----------------------+\n| i | file  |    | i | value                |\n+===+=======+    +===+======================+\n| 0 | a.cfg |    | 0 | Config               |\n| 1 | b.cfg |    | 1 | #ioError(...)        |\n| 2 | c.cfg |    | 2 | #syntaxError(pos: 3) |\n+---+-------+    +---+----------------------+\n\nafter: good       after: bad\n+---+--------+    +---+----------------------+\n| i | value  |    | i | value                |\n+===+========+    +===+======================+\n| 0 | Config |    | 1 | #ioError(...)        |\n+---+--------+    | 2 | #syntaxError(pos: 3) |\n                  +---+----------------------+\n```\n\nA file that fails to read or parse doesn't stop the others. A failure is an ordinary value, sitting in the collection next to the successes under the same key, so you can split them, count them or report them. Each one stays under its file's key, and the read puts details such as the path in the failure's own fields (`#ioError(op:, path:, why:)`), so you don't have to thread that information through by hand.\n\nWhat you can't do is ignore them by accident:\n\n```zed\namounts = files.map(f -> int(read(f)));\n\u002F\u002F sum = amounts >\u003C (+);                        \u002F\u002F ✗ rejected: some amounts may be failures\n```\n\nYou say what you mean instead:\n\n```zed\nsum1 = amounts.where(a -> a is int) >\u003C (+);     \u002F\u002F skip the failures\nsum2 = amounts.map(a -> a else 0) >\u003C (+);       \u002F\u002F count them as zero\nsum3 = amounts.allOk >\u003C (+);                    \u002F\u002F the sum, or all the failures\n```\n\n```text\nbefore: amounts = 3, #ioError(...), 4\nafter:  sum1 = 7\n        sum2 = 7\n        sum3 = #ioError(...)\n\nbefore: amounts = 3, 5, 4\nafter:  sum1 = sum2 = sum3 = 12\n```\n\n## Collections\n\n### Everything is a map\n\nArrays, sets, structs and functions are all maps from keys to values, and you write them and read them in the same way.\n\n**Syntax:** `[a, b, c]`, `{ k -> v }`, `{ a, b }`, `m[k]`\n\n```zed\nxs = [3, 1, 4, 1, 5];                  \u002F\u002F int[0..\u003C5] -> int\nages = { \"Ann\" -> 36, \"Bob\" -> 41 };   \u002F\u002F exact keys {\"Ann\", \"Bob\"}, int values\ntags = { #red, #green };               \u002F\u002F a set: a map from each member to itself\n\nfirst = xs[0];                         \u002F\u002F 3: the index is known to be in range\nann = ages[\"Ann\"];                     \u002F\u002F 36: the key is known to be there\n\u002F\u002F carol = ages[\"Carol\"];              \u002F\u002F ✗ rejected: this key can't be there\nage = ages[name] else 0;               \u002F\u002F name is known only at run time\n\ntens = xs.map(x -> x * 10);            \u002F\u002F the same keys, new values\nbig = tens.where(x -> x > 20);         \u002F\u002F the keys that pass keep their values: 0, 2, 4\nsorted = tens.sort(desc x -> x);       \u002F\u002F new keys 0 to 4; equal values stay in their old order\n```\n\n```text\nbefore: name = \"Ann\", then name = \"Zed\"\nafter:  first = 3, ann = 36, tags = { #green, #red }\n        age = 36, then age = 0\n```\n\nThe last three lines, drawn the same way:\n\n```text\nbefore: xs    after: tens    after: big    after: sorted\n+---+---+     +---+----+     +---+----+    +------+----+\n| i | x |     | i | x  |     | i | x  |    | rank | x  |\n+===+===+     +===+====+     +===+====+    +======+====+\n| 0 | 3 |     | 0 | 30 |     | 0 | 30 |    | 0    | 50 |\n| 1 | 1 |     | 1 | 10 |     | 2 | 40 |    | 1    | 40 |\n| 2 | 4 |     | 2 | 40 |     | 4 | 50 |    | 2    | 30 |\n| 3 | 1 |     | 3 | 10 |     +---+----+    | 3    | 10 |\n| 4 | 5 |     | 4 | 50 |                   | 4    | 10 |\n+---+---+     +---+----+                   +------+----+\n```\n\nAn array is a map whose keys are `0..\u003Cn`, a set is a map from each key to itself, a struct is a map from field names to values, and a function is a map too. So `xs[i]`, `f(x)` and `p.x` are all lookups, and the same operations work on all of them, except that an operation that visits every key needs a finite set of keys: a function over all of `int` can be called, but `group` or `==` on it is rejected. `K -> V` has a value at every key of `K`, while `K ->? V` may lack some keys, so a lookup can give `#notFound`. Nested maps are the normal way to hold tables: `Region -> Product -> rat` is a table of sales by region and product, stored in whichever layout suits the code that reads it.\n\n### Grouping\n\n`group` buckets the entries of a map by a key you compute, and `rekey` replaces the key.\n\n**Syntax:** `m.group(x -> key)`, `m.rekey(x -> key)`\n\n```zed\n\u002F\u002F users : UserId -> User\nbyCity = users.group(u -> u.city);      \u002F\u002F City ->? (UserId -> User)\n\u002F\u002F byId = users.rekey(u -> u.id);       \u002F\u002F ✗ rejected unless id is known to be unique\n```\n\nWith three sample users, `group` adds the `city` level above the keys that were already there:\n\n```text\nbefore: users         after: byCity\n+----+-----------+    +------+----+-----------+\n| id | user      |    | city | id | user      |\n+====+===========+    +======+====+===========+\n| 1  | Ann, Oslo |    | Lima | 2  | Bob, Lima |\n| 2  | Bob, Lima |    +------+----+-----------+\n| 3  | Cid, Oslo |    | Oslo | 1  | Ann, Oslo |\n+----+-----------+    |      | 3  | Cid, Oslo |\n                      +------+----+-----------+\n```\n\n`group` adds a level, so nothing can be lost. The inner map keeps the users' original keys, exactly those of that city's users, which is why the inner arrow is `->`. Only cities with users occur, and each group is nonempty. `rekey` replaces the key, and that can make two entries land on one key, so the compiler demands evidence that the new key is unique, such as a function it can see never collides. If it can't see that, the error names the key expression and the evidence that would make it legal. A claim it can't prove, such as `@injective` or a database's unique constraint, is checked at run time instead, and the result type gains `#collision`. When two entries really do collide, it shows both. No value ever silently overwrites another in Zed.\n\n### Remapping\n\nA remap states the shape a map has and the shape you want, and the compiler does the moving.\n\n**Syntax:** `m as (pattern) into (pattern)`\n\n```zed\ntransposed = matrix as (r -> c -> v) into (c -> r -> v);\nranking = scores as (name -> s) into (desc s -> name -> s);\n\n\u002F\u002F totals = sales as (region -> sku -> amount) into (region -> amount);   \u002F\u002F ✗ rejected\ntotals = sales as (region -> sku -> amount) into (region -> sku >\u003C (+) -> amount);\n```\n\nOn small sample tables, with `rank` the level that `desc s` adds:\n\n```text\nbefore: matrix    after: transposed\n+---+---+---+     +---+---+---+\n| r | c | v |     | c | r | v |\n+===+===+===+     +===+===+===+\n| 0 | 0 | 1 |     | 0 | 0 | 1 |\n|   | 1 | 2 |     |   | 1 | 4 |\n|   | 2 | 3 |     +---+---+---+\n+---+---+---+     | 1 | 0 | 2 |\n| 1 | 0 | 4 |     |   | 1 | 5 |\n|   | 1 | 5 |     +---+---+---+\n|   | 2 | 6 |     | 2 | 0 | 3 |\n+---+---+---+     |   | 1 | 6 |\n                  +---+---+---+\n\nbefore: scores    after: ranking\n+------+----+     +------+------+----+\n| name | s  |     | rank | name | s  |\n+======+====+     +======+======+====+\n| Ann  | 90 |     | 0    | Ann  | 90 |\n| Bob  | 70 |     |      | Cid  | 90 |\n| Cid  | 90 |     +------+------+----+\n+------+----+     | 1    | Bob  | 70 |\n                  +------+------+----+\n\nbefore: sales                after: totals\n+--------+-----+--------+    +--------+--------+\n| region | sku | amount |    | region | amount |\n+========+=====+========+    +========+========+\n| East   | A1  | 5      |    | East   | 8      |\n|        | B2  | 3      |    | West   | 2      |\n+--------+-----+--------+    +--------+--------+\n| West   | A1  | 2      |\n+--------+-----+--------+\n```\n\nIn `transposed`, a value at row `r` and column `c` moves to row `c` and column `r`. A remap is another way of writing what `group`, `rekey` and `sort` do, and both forms compile to the same thing. In the `ranking` line, putting `desc s` in key position sorts by score, and keeping `name` as a level below it means that two people with the same score can't collide. A remap can move keys around, add levels or drop whole entries, but it can't overwrite a value. If you ask it to, as in the rejected `totals` line, you get an error that lists the ways out, and the last `totals` line is one of them. A shortened version of the error, where a keypath is the chain of keys that leads to a value:\n\n```text\nerror: this remap would map one key to many values\n  the `(region, sku)` keypaths collapse onto `region`, but their values survive.\n  drop the values too:         into (region -> sku -> _)\n  or keep the inner key:       into (region -> sku -> amount)\n  or say how the values merge: into (region -> sku >\u003C op -> amount)\n```\n\n### Reducing\n\nA reduction merges the values of one level into one value, using an operator you name.\n\n**Syntax:** `m >\u003C op`, `m >\u003C op else fallback`, `(pattern >\u003C op -> value)`, `m.foldl(init, op)`\n\n```zed\ntotal = readings >\u003C (+);\nlongest = words.map(w -> w.len) >\u003C max else 0;\npivot = sales as (i -> s) into (s.region -> s.product -> i >\u003C (+) -> s.amount);\n```\n\nOn small sample data:\n\n```text\nbefore: readings    after: total\n+---+-------+       +-------+\n| i | value |       | total |\n+===+=======+       +=======+\n| 0 | 2     |       | 10    |\n| 1 | 5     |       +-------+\n| 2 | 3     |\n+---+-------+\n\nbefore: words    after .map(w -> w.len)    after: longest\n+---+-----+      +---+-----+               +---------+\n| i | w   |      | i | len |               | longest |\n+===+=====+      +===+=====+               +=========+\n| 0 | to  |      | 0 | 2   |               | 3       |\n| 1 | be  |      | 1 | 2   |               +---------+\n| 2 | not |      | 2 | 3   |\n+---+-----+      +---+-----+\n\nbefore: sales           after: pivot\n+---+--------------+    +--------+---------+--------+\n| i | sale         |    | region | product | amount |\n+===+==============+    +========+=========+========+\n| 0 | East, pen, 5 |    | East   | ink     | 3      |\n| 1 | West, pen, 2 |    |        | pen     | 9      |\n| 2 | East, ink, 3 |    +--------+---------+--------+\n| 3 | East, pen, 4 |    | West   | pen     | 2      |\n+---+--------------+    +--------+---------+--------+\n```\n\nThe `pivot` line builds a table of sales by region and product. `i >\u003C (+)` collapses the level `i`, adding the amounts that land on the same region and product.\n\nMerging is always written out, with `>\u003C` or a named form such as `.sum`, `.count` or `foldl`. `>\u003C` runs in parallel, so except on floating-point values, which have their own rule below, it needs an operator that is safe to regroup: `+` and `max` are known to be, and for your own operators you state the law.\n\n```zed\nstruct Moments { n: int, sum: rat }\n\n@associative @commutative\ncombine(positional a: Moments, positional b: Moments) =\n  Moments(n: a.n + b.n, sum: a.sum + b.sum);\n\n\u002F\u002F values : [rat]\nm = values.map(x -> Moments(n: 1, sum: x)) >\u003C combine else Moments(n: 0, sum: 0r);\n```\n\nWith three values:\n\n```text\nbefore: values    after .map(x -> Moments(n: 1, sum: x))\n+---+----+        +---+------------------------+\n| i | x  |        | i | value                  |\n+===+====+        +===+========================+\n| 0 | 1r |        | 0 | Moments(n: 1, sum: 1r) |\n| 1 | 2r |        | 1 | Moments(n: 1, sum: 2r) |\n| 2 | 3r |        | 2 | Moments(n: 1, sum: 3r) |\n+---+----+        +---+------------------------+\n\nafter: m\n+------------------------+\n| m                      |\n+========================+\n| Moments(n: 3, sum: 6r) |\n+------------------------+\n```\n\nFor `combine`, the compiler derives both laws from `+` on the fields. In general, a proved law lets the compiler regroup freely, while a claim that was only tested permits one fixed grouping and can still be wrong, and the report says which you have. If an operator isn't associative, use `foldl` or `foldr` to say which way to fold. A reduction over nothing can't be silently wrong: the `else` gives the answer for an empty collection, and without it the result type includes `#empty`, unless the operator has an identity or the collection is known not to be empty.\n\nFloating-point sums get special care. `samples >\u003C (+)` computes the exact sum and rounds it once, so the result doesn't depend on how the work was split or how many cores ran it. If you'd rather have speed than that guarantee, you ask for it, and it shows in the type: `samples >\u003C (+) unordered`. Your own floating-point operator needs no law: with none, the reduction runs on one fixed tree over the collection's order, so it gives the same bits at any core count.\n\n### Pushing into a map\n\nA map can be filled by pushing values to its keys, where a reducer says how values at one key merge.\n\n**Syntax:** `name: K ->? V with reducer(op)`, `name[k] \u003C- v`\n\n```zed\nhist: int ->? int with reducer((+));\nfor w in words { hist[w.len] \u003C- 1; };\n\nsame = words.group(w -> w.len).count;   \u002F\u002F the same table, written as a pull\n```\n\nWith four words, `hist` and `same` hold the same table:\n\n```text\nbefore: words    after: hist, same\n+---+-----+      +-----+---+\n| i | w   |      | len | n |\n+===+=====+      +=====+===+\n| 0 | a   |      | 1   | 1 |\n| 1 | to  |      | 2   | 2 |\n| 2 | be  |      | 3   | 1 |\n| 3 | not |      +-----+---+\n+---+-----+\n```\n\nSometimes it's clearer to say where each value goes than where each value comes from. `hist` is a map that many places can push to, and `reducer((+))` says how contributions to one key merge. Without the reducer, the compiler has to prove that no two pushes land on one key, and otherwise rejects the program. Pushing and pulling compile to the same thing, so writing it this way doesn't choose the direction the data moves at run time. The compiler picks that for each edge of the graph.\n\n### Joins\n\nA join combines two maps on a shared field, either with a word such as `join` or with a `for` over both.\n\n**Syntax:** `a.join(b, on: #field, kind: #left)`, `a.diff(b, on: #field)`, `for x in a, y in b where ...`\n\n```zed\n\u002F\u002F Both inputs are uniquely keyed by OrderId; orderId is their join key.\npaid = orders.join(payments, on: #orderId, kind: #left);\n\u002F\u002F OrderId -> (Order, Payment | #none)\n\nunpaid = orders.diff(payments, on: #orderId);\n\nshipped = for o in orders, s in shipments where o.orderId == s.orderId { (o, s) };\npairs = for i in 0..\u003Cn, j in i+1..\u003Cn { (i, j) };\n```\n\nOn small sample data, where `o1` stands for the order with key 1, and `p1` and `s10` likewise:\n\n```text\nbefore: orders         before: payments\n+---------+-------+    +---------+---------+\n| orderId | order |    | orderId | payment |\n+=========+=======+    +=========+=========+\n| 1       | o1    |    | 1       | p1      |\n| 2       | o2    |    | 3       | p3      |\n| 3       | o3    |    +---------+---------+\n+---------+-------+\n\nafter: paid                  after: unpaid\n+---------+-------------+    +---------+-------+\n| orderId | value       |    | orderId | order |\n+=========+=============+    +=========+=======+\n| 1       | (o1, p1)    |    | 2       | o2    |\n| 2       | (o2, #none) |    +---------+-------+\n| 3       | (o3, p3)    |\n+---------+-------------+\n\nbefore: shipments                after: shipped\n+------------+--------------+    +-----------------------+-----------+\n| shipmentId | shipment     |    | (orderId, shipmentId) | value     |\n+============+==============+    +=======================+===========+\n| 10         | s10, order 1 |    | (1, 10)               | (o1, s10) |\n| 11         | s11, order 1 |    | (1, 11)               | (o1, s11) |\n| 12         | s12, order 3 |    | (3, 12)               | (o3, s12) |\n+------------+--------------+    +-----------------------+-----------+\n\nafter: pairs, with n = 3\n+--------+--------+\n| (i, j) | value  |\n+========+========+\n| (0, 1) | (0, 1) |\n| (0, 2) | (0, 2) |\n| (1, 2) | (1, 2) |\n+--------+--------+\n```\n\nA missing match in a left join is the atom `#none`, which the type shows, and not a row of nulls. A `for` over several collections is a join as well, and the compiler can pick a hash join or a merge join for it instead of two nested loops. Queries and loops compile to the same terms, so they are optimized together.\n\n### Chunks\n\n`chunkBy` cuts an ordered collection into runs that share a key.\n\n**Syntax:** `m.chunkBy(x -> key)`\n\n```zed\nsessions = clicks.chunkBy(c -> c.userId).map(s -> Session(start: s.first.time, count: s.count));\n```\n\nWith four clicks in time order, `ann`'s clicks at `i` = 1 and `i` = 3 land in different chunks because `bob` clicked between them:\n\n```text\nbefore: clicks       after .chunkBy(c -> c.userId)\n+---+-----------+    +-----+---+-----------+\n| i | click     |    | run | i | click     |\n+===+===========+    +=====+===+===========+\n| 0 | ann, t=10 |    | 0   | 0 | ann, t=10 |\n| 1 | ann, t=12 |    |     | 1 | ann, t=12 |\n| 2 | bob, t=15 |    +-----+---+-----------+\n| 3 | ann, t=20 |    | 1   | 2 | bob, t=15 |\n+---+-----------+    +-----+---+-----------+\n                     | 2   | 3 | ann, t=20 |\n                     +-----+---+-----------+\n\nafter: sessions\n+-----+------------------------------+\n| run | session                      |\n+=====+==============================+\n| 0   | Session(start: 10, count: 2) |\n| 1   | Session(start: 15, count: 1) |\n| 2   | Session(start: 20, count: 1) |\n+-----+------------------------------+\n```\n\nIf you have ever split a list into runs by hand, you know the easy mistake is forgetting to flush the last group. Here that can't happen, because the last chunk is included. And since a chunk exists only because a click fell into it, `s.first` is exact, with no `#none` case to handle.\n\n### Vectors and matrices\n\nAn array's type can state its size, so shape mismatches are compile errors.\n\n**Syntax:** `[T; n]`, `[T; r, c]`, `s * v`, `a.matmul(b)`\n\n```zed\nscale(positional s: T, positional v: [T; n]) = s * v;     \u002F\u002F result: [T; n]\n\na: [f64; 2, 3] = [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]];\nb: [f64; 3, 2] = [[1.0, 0.0], [0.0, 1.0], [1.0, 1.0]];\nc = a.matmul(b);                                          \u002F\u002F [f64; 2, 2]\n\u002F\u002F d = a.matmul(a);                                       \u002F\u002F ✗ rejected: 3 columns, 2 rows\n```\n\n```text\nbefore: s = 2.0, v = [1.0, 2.0]\nafter:  scale(2.0, [1.0, 2.0]) = [2.0, 4.0]\n```\n\nThe two inputs and the product, drawn as maps of rows to columns to values:\n\n```text\nbefore: a          before: b          after: c\n+---+---+-----+    +---+---+-----+    +---+---+------+\n| r | c | v   |    | c | k | v   |    | r | k | v    |\n+===+===+=====+    +===+===+=====+    +===+===+======+\n| 0 | 0 | 1.0 |    | 0 | 0 | 1.0 |    | 0 | 0 | 4.0  |\n|   | 1 | 2.0 |    |   | 1 | 0.0 |    |   | 1 | 5.0  |\n|   | 2 | 3.0 |    +---+---+-----+    +---+---+------+\n+---+---+-----+    | 1 | 0 | 0.0 |    | 1 | 0 | 10.0 |\n| 1 | 0 | 4.0 |    |   | 1 | 1.0 |    |   | 1 | 11.0 |\n|   | 1 | 5.0 |    +---+---+-----+    +---+---+------+\n|   | 2 | 6.0 |    | 2 | 0 | 1.0 |\n+---+---+-----+    |   | 1 | 1.0 |\n                   +---+---+-----+\n```\n\nA name in a shape that isn't bound to an integer is a size variable of the signature, so `[T; n, n]` is a square matrix. Dimension checks are ordinary type checks, and the mismatch in the last line is a compile error. `*` scales a vector or matrix by a number. Between two vectors or matrices it is an error, because it could mean several products: you write `matmul`, `dot` or `cross`. `matmul` isn't built in: it's a one-line remap with a reduction, in the same style as the `pivot` above.\n\n## Time and repetition\n\n### Recurrences\n\nA recurrence defines an array by an equation over earlier entries, plus its boundary values.\n\n**Syntax:** `x[i] = f(x[i-1]) with x[-1] = start;`\n\n```zed\nrunning[i] = running[i-1] + xs[i] with running[-1] = 0;\n\nd[i][j] = min(d[i-1][j] + 1, d[i][j-1] + 1, d[i-1][j-1] + cost(a[i], b[j]))\n  with d[-1][j in -1..\u003Cb::len] = j + 1, d[i in 0..][-1] = i + 1;\n```\n\nWith `xs` = 3, 1, 4, with `a` and `b` arrays of the code points of \"ab\" and \"ac\", and with a `cost` of 0 for equal characters and 1 otherwise, `d[1][1]` is the edit distance, 1:\n\n```text\nbefore: xs    after: running    after: d\n+---+---+     +---+---+         +---+---+---+\n| i | x |     | i | v |         | i | j | v |\n+===+===+     +===+===+         +===+===+===+\n| 0 | 3 |     | 0 | 3 |         | 0 | 0 | 0 |\n| 1 | 1 |     | 1 | 4 |         |   | 1 | 1 |\n| 2 | 4 |     | 2 | 8 |         +---+---+---+\n+---+---+     +---+---+         | 1 | 0 | 1 |\n                                |   | 1 | 1 |\n                                +---+---+---+\n```\n\nYou write the equation and the boundary cases, as you would on a whiteboard. The first line is a running total. The second is edit distance, and it needs no explicit table and no choice of memoization or fill order. The compiler reads the dependencies and picks a plan: it fills the table across your cores in dependency order if you need most of it, and memoizes on demand if you only touch part of it.\n\nThe compiler also recognizes some loops that look serial and runs them in parallel:\n\n```zed\ncur[i] = max(xs[i], cur[i-1] + xs[i]) with cur[-1] = 0;\nbest = cur >\u003C max else 0;\n\nstate[i] = csvStep(state[i-1], text::codepoints[i]) with state[-1] = #outsideQuotes;\n```\n\nWith `xs` = 2, -3, 4, -1, 2, `best` is 5. For the text `a\"b\"`, if `csvStep` switches state at each quote character:\n\n```text\nbefore: xs    after: cur    after: state\n+---+----+    +---+----+    +---+------+----------------+\n| i | x  |    | i | v  |    | i | char | state          |\n+===+====+    +===+====+    +===+======+================+\n| 0 | 2  |    | 0 | 2  |    | 0 | a    | #outsideQuotes |\n| 1 | -3 |    | 1 | -1 |    | 1 | \"    | #insideQuotes  |\n| 2 | 4  |    | 2 | 4  |    | 2 | b    | #insideQuotes  |\n| 3 | -1 |    | 3 | 3  |    | 3 | \"    | #outsideQuotes |\n| 4 | 2  |    | 4 | 5  |    +---+------+----------------+\n+---+----+    +---+----+\n```\n\nThe first recurrence is maximum subarray. The compiler recognizes that its step composes in any grouping, so it runs as a parallel scan. The second walks a CSV file with a small state machine. Because the states are finite, the compiler can tabulate the transitions, and tables compose in any grouping, so a job usually done one character at a time splits across cores.\n\n### Loops\n\nA loop describes one step, and the loop as a whole is a value holding the final state and the history.\n\n**Syntax:** `loop { x' = f(x) with x = start; until done; }`, `run.x`, `run::frames`\n\n```zed\nsim = loop {\n  pos' = pos + vel * dt with pos = p0;\n  vel' = vel + accel(pos) * dt with vel = v0;\n  until pos'.x > bound;\n};\n\nfinal = sim.pos;\nhistory = sim::frames;\nsteps = sim::len;\n```\n\nFollowing only the `x` part, with `dt` = 1, `pos` starting at 0, `vel` at 1, `accel` always 1 and `bound` = 2, `final.x` is 3 and `steps` is 2. The starting values aren't part of `sim::frames`:\n\n```text\nafter: sim::frames\n+---+-------+-------+\n| t | pos.x | vel.x |\n+===+=======+=======+\n| 0 | 1     | 2     |\n| 1 | 3     | 3     |\n+---+-------+-------+\n```\n\n`pos'` is the next value of `pos`, written in terms of the current values. Both updates here read the old `pos`, so they don't race and their order doesn't matter. Each step writes each variable once, so a data race can't be written. After the loop, `sim.pos` is the final value.\n\n`sim::frames` is every step of the run, kept only if you read it. If you don't, the compiler keeps only the steps the loop still reads. If you do, the whole history is there to read. This is how you write undo:\n\n```zed\nrun = loop t {\n  while t \u003C edits::len;\n  doc' = doc.patch(edits[t]) with doc = empty;\n};\n\nprevious = run::frames[run::len - 2].doc else empty;\n```\n\nWith two edits `e1` and `e2`:\n\n```text\nbefore: edits    after: run::frames\n+---+------+     +---+-----------------+\n| t | edit |     | t | doc             |\n+===+======+     +===+=================+\n| 0 | e1   |     | 0 | empty.patch(e1) |\n| 1 | e2   |     | 1 | that.patch(e2)  |\n+---+------+     +---+-----------------+\n```\n\n`previous` is the document after `e1`. With no edits, or just one, the lookup finds no frame and `previous` is `empty`.\n\n`patch` applies one edit to the document. The versions share structure, so keeping them all doesn't copy the document each time, although the history still uses memory.\n\n### Methods and the next value\n\nA method is a function on a struct, and it can define the struct's next version with the same `'` that a loop uses.\n\n**Syntax:** `Type.method() { field' = ...; }`, `x.method()`, `x*.method()`\n\n```zed\nstruct Counter { n: int, peak: int }\n\nCounter.bump(positional by) -> int {\n  n' = n + by;\n  peak' = max(peak, n + by);\n  return n;\n}\n\nstart = Counter(n: 0, peak: 0);\nafter, was = start.bump(2);\n```\n\n```text\nbefore: start = Counter(n: 0, peak: 0), by = 2\nafter:  after = Counter(n: 2, peak: 2), was = 0\n        start = Counter(n: 0, peak: 0), unchanged\n```\n\nInside a method, `n'` means the same thing it means in a loop: the value of `n` in the next version of this struct. The method doesn't change `start`: it returns a new `Counter` and its declared result, and you have to take both. In a loop body, a `*` makes a call look like mutation: `prev = c*.bump(3);` replaces `c` in the loop's next step. So no call changes a value you hold unless the text shows a `*`.\n\n### Only what's needed runs\n\nA value no result depends on doesn't have to be computed, so unused fields and unbounded ranges cost nothing extra.\n\n**Syntax:** `for i in n.. { ... }`, unused fields, `.first`\n\n```zed\nstats(positional data: [f64]) {\n  n = f64(data::len);\n  mean = data.sum \u002F n;\n  sd = (data.map(x -> (x - mean) ** 2).sum \u002F n).sqrt;\n  return { mean:, sd: };\n}\n\nm = stats([1.0, 2.0, 3.0]).mean;      \u002F\u002F sd is never computed\n\nfirstPrime = (for i in 2.. { i }).where(isPrime).first;\n```\n\n```text\nbefore: data = [1.0, 2.0, 3.0], the unbounded range 2, 3, 4, ...\nafter:  m = 2.0, and sd has not run\n        firstPrime = 2\n```\n\nA caller that reads `.mean` doesn't pay for `sd`, and you don't need two versions of the function or a flag. Zed isn't lazy in the Haskell sense: any evaluation order that gives the same value is legal, and the compiler chooses by cost. The `firstPrime` search runs over an unbounded range. The compiler may try candidates in parallel, and once a prime is found and every smaller candidate has been ruled out, the larger ones can be canceled.\n\n## The outside world\n\n### Ports\n\nPorts are declared channels to the outside world, and they are the only way a program reaches it.\n\n**Syntax:** `main(input: T) -> (output: U) { output \u003C- value; }`\n\n```zed\nmain(req: Stream(Query)) -> (resp: Stream(Answer)) {\n  resp \u003C- req.map(q -> answer(q));\n}\n```\n\n```text\nbefore: req delivers q1, then q2\nafter:  resp carries answer(q1), then answer(q2)\n```\n\nPorts are declared in `main`'s header or as stored collections: files, sockets, clocks, devices, databases and the like. Foreign calls and logging go through ports too. Everything else is a pure value, so Zed needs no effect system. Reading a port gives you a value, and `\u003C-` pushes one out. So a server, a batch job and a pipeline are all the same kind of thing: a function from input ports to output ports.\n\nRuns repeat exactly, apart from a short list such as the order that messages arrive at a port and running out of a resource. Inputs and arrival order can be recorded, so you can replay a failing run in a test.\n\n### Timeouts and retries\n\nA port's reliability settings are declared on the port, and the ones that can fail show up in its type.\n\n**Syntax:** `with timeout(d)`, `with retry(n, backoff: b)`, `with bound(n, overflow: policy)`\n\n```zed\ncache: Utf8String ->? [u8]\n  with store(kv(endpoint))\n  with timeout(0.2r with units(\"s\"))\n  with retry(2, backoff: #fixed(0.1r with units(\"s\")));\n\nhit = cache[key] else fetch(key);\n```\n\n```text\nbefore: key is in the cache\nafter:  hit = the cached bytes\n\nbefore: key isn't in the cache, or the read fails, or 0.2 seconds pass\nafter:  hit = fetch(key)\n```\n\nDeclaring a timeout changes the type. A read of `cache` is now `[u8] | #ioError | #timeout | #notFound`, and the program has to deal with that, here by treating anything other than a hit as a miss. `retry` adds no failure member, and the timeout covers all the attempts together. Pure code never times out, because a computation's finishing time isn't a value.\n\nRetries, hedged requests, circuit breakers, rate limits and failover are declared on the port in the same way. The compiler permits retries only for operations declared safe to repeat, so a write that may already have landed needs an idempotence guarantee before it can be retried. Queues declare what happens when they are full (`#block`, `#dropOldest` or `#full`), so every queue has a limit, and by default a writer waits when it is full.\n\n### Databases\n\nA database table is declared as a map on a store, and its schema is checked at build time.\n\n**Syntax:** `name: K ->? V with store(...)`\n\n```zed\norders: OrderId ->? { total: rat, note: Utf8String | #none }\n  with store(postgres(dbUrl, table: \"orders\", schema: sql(\"db\u002Forders.sql\")));\n\nn = orders[id]?.note;     \u002F\u002F Utf8String | #none | #notFound | #dbError\n```\n\n```text\nbefore: orders             after: n, for each id\n+----+-------+--------+    +----+-----------+\n| id | total | note   |    | id | n         |\n+====+=======+========+    +====+===========+\n| 1  | 9r    | \"gift\" |    | 1  | \"gift\"    |\n| 2  | 4r    | NULL   |    | 2  | #none     |\n+----+-------+--------+    | 3  | #notFound |\n                           +----+-----------+\n```\n\nIf the database can't answer, `n` is `#dbError` for any `id`.\n\nA stored table is a map like any other, and you read it with the same `[key]`. The compiler checks your declaration against the SQL schema at build time, without a live connection: a nullable column read as non-optional, or an unbounded string written to a `varchar(80)`, is a compile error at this line. At startup, the program compares the columns it uses with the real database. On a port that supports transactions, such as Postgres, writes made in one step of the program form one transaction, and you never write `begin` or `commit`.\n\n### Incremental updates\n\nWhen an input changes, the compiler can update the affected results or recompute them in full, and `@memoized` asserts that a value is kept for reuse.\n\n**Syntax:** `@memoized`\n\n```zed\n\u002F\u002F sales is keyed by SaleId; each sale has a region and an amount.\n@memoized\nreport = sales\n  .group(s -> s.region)\n  .map(rows -> rows.map(s -> s.amount).sum);\n```\n\nHere are three sales, shown as region and amount. If sale 7 then changes from 5 to 6, East's total becomes 9 and West's stays 2:\n\n```text\nbefore: sales           after .group(s -> s.region)      after: report\n+--------+---------+    +--------+--------+---------+    +--------+-----+\n| saleId | sale    |    | region | saleId | sale    |    | region | sum |\n+========+=========+    +========+========+=========+    +========+=====+\n| 7      | East, 5 |    | East   | 7      | East, 5 |    | East   | 8   |\n| 8      | West, 2 |    |        | 9      | East, 3 |    | West   | 2   |\n| 9      | East, 3 |    +--------+--------+---------+    +--------+-----+\n+-","Zed 是一种面向 AI 时代的新型数据流编程语言，以声明式依赖图替代传统控制流和可变状态。其核心特性包括全自动并行执行、零开销内存管理（无需垃圾回收）、增量重计算、静态验证（支持范围检查、单位约束、污点分析与计算成本建模），以及编译期部分求值与形式化验证能力。适用于对确定性、并发安全、资源可控性要求高的场景，如实时数据处理流水线、AI 模型推理服务、高可靠嵌入式逻辑及需强静态保障的金融或科学计算系统。","2026-11-24 04:32:57","CREATED_QUERY"]