#include "system-macros.x"/* foreach converts each item to the declared type. try_get reports presence separately from its output: a stored zero is still a present value. */int main(void) { List numbers = %(1 2 3 4); int total = 0; foreach (int n in numbers) { if (n == 2) continue; total += n; } (int first, String label) = %(7 "seven"); Map counts = {zero: 0}; Var found; int present = counts.try_get(<zero>, found); puts($dedent(%" Sum after skipping 2: $total Unpacked number: $first Unpacked label: $label Zero key present: $present Stored value: $found Missing key present: $(<missing> in counts)")); // False does not mean absent: empty containers and numeric zero are false. Array empty = []; printf("Empty array is true: %d\nNull differs from void: %d\n", empty ? 1 : 0, (Var) NULL !== void); return 0;}
Actual output
Expected output
Sum after skipping 2: 8
Unpacked number: 7
Unpacked label: seven
Zero key present: 1
Stored value: 0
Missing key present: 0
Empty array is true: 0
Null differs from void: 1
Run locally: x2c run examples/tours/language/iteration.x
Functions and closures
Pass a reference, splice positional arguments, and see what changes when a
closure captures by reference.
/* class generates operations for a chosen C representation. Point is a record value; Node is a pointer. Record copying is shallow, not recursive. */class Point { int x; int y; };class Node { int value; } *;static void Point.move(Point &p, int dx, int dy) { p.x += dx; p.y += dy; }int main(void) { Point point = Point.new(2, 3), copy = point; point.move(1, 1); Var boxed = point; // Boxing a record copies it into owned storage. Map labels = {}; labels[boxed] = "here"; printf("Moved point: (%d, %d)\nCopied point: (%d, %d)\nLabel for equal point: %s\n", point.x, point.y, copy.x, copy.y, labels[Point.new(3, 4)]); Node node = auto Node.new(7); Node same = node; same.value++; puts(%"Shared node: $(node.value)"); return 0;}
Actual output
Expected output
Moved point: (3, 4)
Copied point: (2, 3)
Label for equal point: here
Shared node: 8
Run locally: x2c run examples/tours/language/classes.x
Protocols and operators
Give a map-backed set union and intersection operations through protocol
adoption.
#include "system-macros.x"/* A typedef can reuse storage while defining new operations. Explicit adoption connects those methods to a protocol; names alone do not. */typedef Map Set;static Set Set.new(List keys) { Set set = {}; foreach (Var key in keys) set[key] = 1; return set;}static Set Set.add(Set a, Set b) => a.copy().merge(b);static Set Set.mul(Set a, Set b) => Set.new(a.keys().filter(%!(Var key) => key in b));protocol Map(T) { T T.add(T, T); T T.mul(T, T); }protocol Map(Set);int main(void) { Set a = Set.new(%(apple pear)), b = Set.new(%(pear bread)); Set combined = a + b, common = a * b; // Map traversal has no promised order; sort before presenting keys. puts($dedent(%" Union: $(combined.keys().list().sort().repr()) Intersection: $(common.keys().list().sort().repr())")); return 0;}
Actual output
Expected output
Union: (apple bread pear)
Intersection: (pear)
Run locally: x2c run examples/tours/language/operators.x
Patterns and templates
Match coordinates and flags, then simplify an addition by building a new
list from the captures.
/* Match arms try in order without fallthrough. Typed captures test tags, not convertibility. A rest capture is a List; $ inserts and @ splices. */static List simplify(List expression) { match (expression) { case %(add ?value 0): return %(value $value); case %(add ?(int a) ?(int b)): return %(value $(a + b)); default: return expression; }}int main(void) { List command = %(move (3 4) fast quiet); match (command) { case %(move (?(int x) ?(int y)) *flags) if (x > 0): puts(%"Matched command: $(%(at $x $y @flags).repr())"); default: puts("No move matched"); } List result = simplify(%(add 2 3)); if (result ~= %(value ?(int n))) puts(%"Simplified value: $n"); return 0;}
Actual output
Expected output
Matched command: (at 3 4 fast quiet)
Simplified value: 5
Run locally: x2c run examples/tours/language/patterns.x
Lifetime and errors
Move an array to a longer-lived scope and observe the order of cleanup,
catch, and finally.
#include "system-macros.x"/* A region frees mutable allocations together. Canonical text belongs to a pool, normally lasting until shutdown. Containers do not adopt references. */static String make_label(void) { auto { Buffer out = Buffer.new(); out.write("ready").write("!"); return out; // The String conversion interns text before the region ends. } return NULL;}int main(void) { puts(%"Label: $(make_label())"); Scope saved = auto Scope.new(); Array kept; auto { Array temporary = [1, 2]; temporary.move_to(&saved); // Preserve the container beyond this region. kept = temporary; } puts(%"Retained array: $(kept.repr())"); int level = 1; with (level = 9) { puts(%"Temporary level: $level"); } alias kept[0] as first; first += 4; // An alias substitutes its expression on each use. puts($dedent(%" Restored level: $level Aliased element: $(kept[0])")); try { defer puts("Cleanup before catch"); raise %(bad-arg (operation "tour")); } catch %(bad-arg *details): puts("Caught bad-arg"); finally puts("Finally"); return 0;}
#include "meta.x"/* An ordinary call runs now; $ calls a meta function during translation. A macro receives syntax. Its declared locals are private per expansion; free names resolve at the call site unless kept with using. */meta static int cube(int n) => n * n * n;static int factor = 2;macro Expression $scaled(Expr $n) => $n * factor;macro Expression $fixed(Expr $n) using factor => $n * factor;macro Decorator $twice(Stmt $body) { { for (int repeat = 0; repeat < 2; repeat++) $body }}keyword twice $twice;// A quotation writes generated code in source form; the hole inserts syntax.meta static List report_code(List value) => $!{ printf("Generated report: %s\n", (Var) $value); };macro Stmt $report(Expr $value) => $report_code($value);int main(void) { int n = 3; printf("Runtime cube: %d\nCompile-time cube: %d\n", cube(n), $cube(3)); int factor = 10; printf("Caller name result: %d\nKept name result: %d\n", $scaled(3), $fixed(3)); int total = 0; twice { total++; } $report(total); // Lisp is a runtime library, not the implementation of meta functions. Lisp lisp = auto Lisp.new(); puts(%"Runtime Lisp result: $(lisp.eval(%(+ 2 3)))"); return 0;}
#include "system-macros.x"/* One worker writes counts; main reads only after Thread.run joins both. The parent owns the Map and Channel throughout. Strings are canonical. Channel capacity bounds queued messages, not the canonical-value pool. */int main(void) { Channel lines = auto Channel.new(<string>, 2); Map counts = {}; Thread.run([ %!() => { defer lines.close(); foreach (String line in %("tea and cake" "more cake")) lines.send(line); }, %!() => { foreach (String line in lines) foreach (String word in line.words()) counts[word] += 1; } ]); puts($dedent(%" Cake: $(counts["cake"]) Tea: $(counts["tea"])")); return 0;}
Actual output
Expected output
Cake: 2
Tea: 1
Run locally: x2c run examples/tours/language/threads.x