Types, protocols, control flow, and concurrency, working together.
classes
A class act.
Declare three fields. Construction, fieldwise equality, hashing, and printing come free. Use a Color as a Map key: an independently constructed equal color finds the same entry. Store Color values in Arrays, too. No custom methods are needed.
#include <assert.h>class Color { int red, green, blue; };int main(void) { // Construction follows field order; equality compares every field. Color coral = Color.new(255, 127, 80); Color same = Color.new(255, 127, 80); assert(coral == same); // Generated hashing and equality let equal colors share a Map entry. Map names = {(coral): "coral"}; assert(names[same] == "coral"); // Colors also work as Array elements. Array palette = [Color.new(255, 127, 80), Color.new(70, 130, 180)]; assert(palette[0] == coral); // Printing includes the class name and each named field. printf("%s: %s\n", names[same], coral.repr()); return 0;}
Actual output
Expected output
coral: Color { red: 255, green: 127, blue: 80 }
Run locally: x2c run examples/power/classes.x
protocols
Sets appeal.
A Set built on a Map gains union and intersection through operators. The type is a typedef Map Set: it reuses Map storage and operations while giving the result a vocabulary of its own.
#include <assert.h>// Reuse Map storage: its keys are the set members.typedef Map Set;Set Set.add(Set left, Set right) => left.copy().merge(right);Set Set.mul(Set left, Set right) => Set.new(left.keys() .filter(%!(Var key) => key in right));Set Set.new(List keys) => keys.foldl(%{}, %!(Map set, Var key) => set.update_n(1, key, (Var) 1));// Connect add and mul to the + and * operators.protocol Map(T) { T T.add(T, T); T T.mul(T, T); }protocol Map(Set);int main(void) { // Create two sets, then take their union and intersection. Set fruit = Set.new(%(apple pear)); Set lunch = Set.new(%(pear bread)); Set set_union = fruit + lunch; Set intersection = fruit * lunch; assert(set_union.len() == 3 && set_union.contains(<apple>) && set_union.contains(<pear>) && set_union.contains(<bread>)); assert(fruit.len() == 2 && lunch.len() == 2); assert(Set.new(nil).len() == 0); assert(Set.new(%(apple pear apple)).len() == 2); Set symbols = Set.new(%(apple pear)); assert(symbols.contains(<apple>) && symbols.contains(<pear>)); assert(intersection.len() == 1 && intersection.contains(<pear>)); assert((fruit * fruit).len() == 2); assert((fruit * Set.new(nil)).len() == 0); assert((Set.new(nil) * fruit).len() == 0); assert(fruit.len() == 2 && lunch.len() == 2); printf("%d in the union, %d in both\n", set_union.len(), intersection.len()); return 0;}
Actual output
Expected output
3 in the union, 1 in both
Run locally: x2c run examples/power/protocols.x
indexing
Index marks the spot.
Collect document words into an index, then combine the indexed results. Maps, Arrays, and iterator operations make the useful structure visible in the program.
#include <assert.h>// Store documents once; words refer to them by ID.class Index { Array documents; Map words; } *;void Index.init(Index index) { index.documents = []; index.words = {};}// Add each word once per document, regardless of case or repetition.void Index.insert(Index index, String name, String text) { int id = index.documents.len(); index.documents.push(name); foreach (String word in text.lower().words().iter().unique()) index.words.setdefault(word, []).array().push(id);}// An unknown word has no matches; lookup does not change the index.Array Index.find(Index index, String word) => index.words.getdefault(word.lower(), []);int main(void) { Index index = Index.new(); index.insert("garden", "red roses red tulips"); index.insert("kitchen", "red apples green pears"); assert(index.find("RED") == [0, 1]); assert(index.find("roses") == [0]); int words = index.words.len(); assert(index.find("blue").len() == 0 && index.words.len() == words); Array matches = index.find("roses"); puts(%"roses: $(index.documents[matches[0]])"); return 0;}
Actual output
Expected output
roses: garden
Run locally: x2c run examples/power/indexing.x
destructuring
Breaking up is easy to do.
Destructuring gives each position a typed name. A pattern condition selects tea orders and binds their fields for the rest of the condition and its body.
int main(void) { Array orders = [ %(tea 2 "Ada"), %(coffee 1 "Grace"), %(tea 1 "Linus") ]; // Give each field a typed name. foreach (List order in orders) { (Symbol item, int count, String who) = order; printf("%s wants %d %s\n", who, count, item.str()); } // Select a shape and bind its fields in the condition. foreach (List order in orders) if (order ~= %(tea ?(int n) ?(String who)) && n > 1) puts(%"$who is thirsty"); return 0;}
Actual output
Expected output
Ada wants 2 tea
Grace wants 1 coffee
Linus wants 1 tea
Ada is thirsty
Run locally: x2c run examples/power/destructuring.x
matching
Match ado about nothing.
match selects nested List structures and binds their parts. Templates rebuild the result: $ inserts a value and @ splices a sequence.
This small simplifier combines pattern matching and reconstruction without manually indexing every node.
Iterators select, merge, and enumerate values as they are consumed. Compose the operations around the task, then collect or reduce the result where you need it.
unique: (3 1 2 4)
queue: (101 102 201 202)
first square over threshold: 81
temperature alerts: 2
temperature warning: yes
scores valid: yes
numbered: ((1 parse) (2 compile) (3 link))
Run locally: x2c run examples/power/iterators.x
errors
Catch of the day.
A failed read can leave a block without leaving its file open. Cleanup stays beside the resource; the caller handles the failure where it can decide what to do next.
#include <assert.h>#include "path.x"#include <fcntl.h>#include <errno.h>static int opened_fd = -1;// The caller decides how to present content that cannot be text.String preview(String path) { try return read_text(path); catch %(bad-arg *): { assert(fcntl(opened_fd, F_GETFD) == -1 && errno == EBADF); return "No text preview: file contains a NUL byte."; } catch %(not-found *): return "No preview: file not found."; catch: return "No preview: unable to read file.";}// Close the file on success or while unwinding from a failed read.String read_text(String path) { auto File input = path.open("r"); opened_fd = input.fileno(); return input.string();}// The checked-in data sits beside the examples wherever they live.String example_data(String name) { Path source = String.new(__FILE__); return source.dirname().join("../data").join(name);}int main(int argc, char **argv) { String directory = argc > 1 ? argv[1] : example_data("power-exceptions"); assert(preview(%"$directory/document.txt") == "Meeting at noon."); assert(fcntl(opened_fd, F_GETFD) == -1 && errno == EBADF); // document.bin contains a NUL byte, which String cannot hold. puts(preview(%"$directory/document.bin")); assert(fcntl(opened_fd, F_GETFD) == -1 && errno == EBADF); assert(preview(%"$directory/missing-preview-file.txt") == "No preview: file not found."); assert(preview(directory) == "No preview: unable to read file."); assert(fcntl(opened_fd, F_GETFD) == -1 && errno == EBADF); return 0;}
Actual output
Expected output
No text preview: file contains a NUL byte.
Run locally: x2c run examples/power/exceptions.x
channels
Concurrently yours.
Channels connect a producer and consumer. One worker updates the counts, and the caller reads the result after joining. Ownership and communication remain visible in the code.
#include <assert.h>int main(void) { // A bounded channel carries values between worker threads. Channel lines = auto Channel.new(<string>, 4); Map counts = {}; // Thread.run starts every worker and joins them all before returning. Thread.run([ %!(void) => { foreach (String line in %("tea and cake" "cake and more cake")) lines.send(line); lines.close(); }, %!(void) => { foreach (String line in lines) foreach (String word in line.words()) counts[word] += 1; } ]); assert(counts["cake"] == 3 && counts["and"] == 2); printf("cake: %s, tea: %s\n", counts["cake"], counts["tea"]); return 0;}
Actual output
Expected output
cake: 3, tea: 1
Run locally: x2c run examples/power/channels.x
packages
The whole package.
Import PCRE2 under the name rx, compile a pattern, and read named captures. Package types and methods work alongside ordinary x2c Strings, iteration, and scoped cleanup.
/* imports.x -- extract named request fields with the PCRE2 package In a checkout, `make -C packages/pcre2 run` builds the package and runs this example. With an installed x2c, run `x2c install pcre2` first; then `x2c run -q examples/power/imports.x` finds the package.*/#include <assert.h>#include "system-macros.x"// Import the package under a name you choose.import "pcre2" as rx;int main(void) { // Compile a pattern with named captures; release it on exit. auto rx.Regexp request = rx.Regexp.compile( "^(?<method>[A-Z]+) (?<path>/[^ ]+)$", 0); // Sample requests include lines the pattern will ignore. String text = $dedent(%" GET /docs POST /build -- idle -- DELETE /cache GET missing-slash "); int matches = 0; foreach (String line in text.lines()) { rx.RegexpMatch found = request.match(line); if (found) { puts(%"$(found[<method>]) requests $(found[<path>])"); matches++; } } assert(matches == 3); return 0;}
This program needs a package, so it runs only with the native toolchain.
Expected output
GET requests /docs
POST requests /build
DELETE requests /cache
Run locally:
./configure --packages pcre2
make -C packages/pcre2 builds/gallery-imports
./packages/pcre2/builds/gallery-imports
counting
File iteration, String.lower, and Map updates count words without
manual buffers or table management. Array.sort_with compares the counts
in each (word count) pair to rank the results: 3 tea, 2 coffee, 1 milk.
Ties sort by word in reverse order.
#include "path.x"// Files supply lines; each line supplies words.Map word_count(String path) { Map counts = {}; auto File input = path.open("r"); foreach (String line in input) foreach (String word in line.lower().words()) counts[word] += 1; return counts;}// The checked-in data sits beside the examples wherever they live.String example_data(String name) { Path source = String.new(__FILE__); return source.dirname().join("../data").join(name);}int main(int argc, char **argv) { // words.txt: "Tea coffee tea" then "Milk coffee tea". String path = argc > 1 ? argv[1] : example_data("power-counting/words.txt"); Map counts = word_count(path); // Rank by count, breaking ties by word in the same descending order. Array ranked = counts.enumerate().array().sort_with( %!(List left, List right) => { int order = right[1].compare(left[1]); return order ? order : right[0].compare(left[0]); }); foreach ((String word, int n) in ranked) puts(%"$n $word"); return 0;}
Actual output
Expected output
3 tea
2 coffee
1 milk
Run locally: x2c run examples/power/counting.x
threads
Thread.start_raw copies each batch’s bytes and launches a worker thread.
Both workers start before either Thread.join returns a result; their
partial sums combine to 91. Thread.free releases the finished handles.
The workers need neither shared input pointers nor a shared accumulator.
#include <assert.h>// Each worker squares its values and reduces them to one sum.static Var sum_squares(const void *input, size_t bytes) { const int *values = input; double sum = 0; for (size_t i = 0; i < bytes / sizeof(int); i++) sum += (double) values[i] * values[i]; return sum;}int main(void) { // Split the data; launch both workers before waiting for either. int values[2][3] = {{1, 2, 3}, {4, 5, 6}}; Thread first = Thread.start_raw(sum_squares, values[0], sizeof(values[0])); Thread second = Thread.start_raw(sum_squares, values[1], sizeof(values[1])); values[0][0] = 100; values[1][0] = 100; // Combine the partial sums after both workers finish. double left = first.join(), right = second.join(); first.free(); second.free(); printf("sum of squares: %g\n", left + right); assert(left == 14 && right == 77 && left + right == 91); return 0;}