Files
sakurac/docs/algorithms.md
T

663 lines
36 KiB
Markdown
Raw Normal View History

2026-10-26 10:14:11 -05:00
# Plan: algorithms
Written 2026-10-08, revised 2026-10-09 for `invokable`, which changes how
predicates, orders and keys are taken, and brought up to date 2026-10-20 for what std
and the compilers gained since: sorting, bisection, `heap`, `groups` and `runs` in std,
the iterators' consumers, `min`, `max` and `clamp` in `std::math`, lambdas typed from
`invokable` bounds, and lambdas that no longer allocate. This is a proposal. std is
yours, so the decisions at the end are yours to make. Much of what it proposed is in std
now, built apart from it; the rest isn't built.
**Comes after the ffi plan, now built:** `std::sys` is `system`, and `@foreign` and
`@link` are `extern` sections.
**Built in the rebuild alone** ([roadmap.md](roadmap.md), decision 1). Where this plan
says both compilers, C's half is left out. What was measured in C stays as measured.
**What it is:** the operations on runs of elements that programs keep writing by hand:
- sorting;
- searching, including by bisection;
- testing, counting and finding;
- grouping elements by a key;
- reversing, filling and removing;
- a heap of least-first elements;
- `min`, `max`, `clamp` and `swap`.
std has most of these now (see [What's there now](#whats-there-now)). What's left:
- orders and tests taken as anything `invokable`, sorting by a key, and a sort that
allocates nothing;
- `swap`, `reverse`, `fill` and `is_sorted`;
- for vectors, taking the last element out, keeping only some, and dropping repeats.
**Its users:**
- **the compiler rebuild,** which moved onto std's sort, heap, groups, runs and
bisections on 2026-10-19, and still writes the rest by hand. See
[What the compiler gains](#what-the-compiler-gains);
- the random plan ([random.md](random.md)), whose `shuffle` swaps elements;
- the build tool, ordering files and steps;
- writers of documents that want keys in order, and every program that sorts.
**Probed:** in the scratchpad, on 2026-10-08 and 2026-10-09 (`algo/`, since gone), and
again on 2026-10-20 (`plans/algorithms/`) against std as it is now. Each program was
built at `-O2` by the rebuild's own compiler and by the C compiler, and both gave the
same results. Times are the rebuild's where only one is given. The machine was busy on
2026-10-20, so those times are the best of three runs on one core.
- **A generic sort** (2026-10-08): introsort over a private `comparer<T>` trait, sorting
1,000,000 random words:
| How the order is given | Time |
|---|---|
| `<`, through `ordered` | 0.17 s |
| A function value | 0.23 s |
| The rebuild's own `sort_words`, a heap sort | 0.30–0.35 s |
Also:
- Sorting 1,000,000 structs by a function value took 0.25 s. Packing the same two
fields into words and calling `sort_words` took 0.30 s.
- Sorting 100,000 strings by a function value worked.
- **std's sort** (2026-10-20), a stable merge sort, over a million random words made the
same way:
| Sort | Rebuild | C |
|---|---|---|
| `sort`, by `<` | 0.19 s | 0.26 s |
| `sort_by`, a named function | 0.26 s | 0.31 s |
| `sort_by`, a lambda | 0.25 s | 0.31 s |
| 1,000,000 structs by a field, `sort_by` with a lambda | 0.19 s | 0.31 s |
| The introsort above, by `<`, written again beside it | 0.13 s | 0.17 s |
The introsort allocates nothing and isn't stable. The merge sort takes a buffer as
long as the run.
- **Grouping by key** (2026-10-08): a counting sort of 1,000,000 items into 65,536 keys
took 0.02 s. The register allocator's way then, which packed, sorted, counted and
summed, took 0.33 s for the same order. std's `groups` counts this way now.
- **Bisection through a key function that captures nothing** (2026-10-08) ran as fast as
the loop written out: 3.24 s against 3.40 s for 10,000,000 searches.
- **Through `invokable`** (2026-10-09). The same introsort, generic over its order
`F: invokable<def(&T, &T): bool>` instead of the private trait, sorting 1,000,000
random words:
| How the order is given | Rebuild | C |
|---|---|---|
| `<`, through a functor, `by_order<T>` | 0.14 s | 0.18 s |
| A functor comparing a key of its own | 0.15 s | 0.17 s |
| A function value | 0.22 s | 0.24 s |
| A function value held in a struct, as `comparer<T>` held it | 0.23 s | 0.24 s |
A function value costs the same through `invokable` as through a parameter of
function type, or held as `comparer<T>` held it: 0.23 s in the sort.
- **Lambdas in a hot loop** (2026-10-20): 10,000,000 searches of 8 elements, each for a
value that changes:
| Search | Rebuild | C |
|---|---|---|
| A loop over indexes, written out | 0.12 s | 0.24 s |
| `span::contains` | 0.19 s | 0.24 s |
| `any` of a span, generic over its test, given a functor holding the value | 0.19 s | 0.27 s |
| `for &each in v`, written out | 0.26 s | 0.42 s |
| `iter().any`, given such a functor | 0.26 s | 0.37 s |
| `any` of a span, given a lambda referring to the value | 0.44 s | 0.51 s |
| `iter().any`, given that lambda | 0.65 s | 1.45 s |
- Memory grew in none.
- On 2026-10-09 such a lambda took 3.23 s (C 4.09 s), where a functor took 0.09 s, in
a probe searching for one value. Each lambda made then allocated twice.
- A named function given for the test, looking for a constant, took 0.13 s in the
rebuild, which calls it directly and inlines it, and 0.49 s in C, which calls it
through the value.
**Found:**
- **A lambda allocates nothing now, but is called through its value.**
- Lambdas refer to the locals they use where those are (README, "Functions"), so the
two allocations are gone: 0.44 s where it was 3.23 s.
- The rebuild's `devirtualize` (compiler/optimizer/inline.sakura) calls a known
function value directly, so a named function, or a lambda referring to nothing, is
inlined once the algorithm is. "A function taking an environment is left called
through the value," so a lambda referring to locals isn't: 2.3 times a functor in
the search.
- A lambda given for `F` is of its function type, so all lambdas of one signature
share an instance of an algorithm. One the optimizer doesn't inline, as a sort,
calls its order through the value however the order was made.
Decision 4 is about this.
- **A functor costs about what `span::contains` costs.** An algorithm generic over its
test is compiled for each functor's type, so `invoke` is a direct call, inlined at
`-O2`, and what the test needs is a field. It's still the cheap path, and needs no
change to the compilers. The loop over indexes is faster still in the rebuild, 0.12 s
against 0.19 s, where on 2026-10-09 they ran even.
- **A functor for a view's iterator takes `& &T`.** `v.view().iter()` gives `&T`, and
the consumers' tests take a reference to what's given, so `iter().any` wants
`invokable<def(& &block): bool>`. A functor taking `&block` doesn't meet it, in both
compilers. A lambda doesn't care (decision 3).
- **Bounds at methods work in both compilers now.** Both take
`def span<T>::is_sorted(&this): bool where T: ordered`, and the method belongs only to
ordered `T` (README, "Methods and properties"). The C compiler refused it on
2026-10-09, so this plan guarded such methods with `if const !(T is ordered)` and
`compile_error`. std's `lower_bound`, `upper_bound`, `sort` and `heap` still guard that
way, which gives a message of their own. Probed.
- **Lambdas take their types from `invokable` bounds,** in both compilers, and the
rebuild infers a type parameter from a lambda, as `F` of `take<F>(f: F)` given
`def(x: i64): i64 => x`, as C did. That was phase 0 here, built with the iterators on
2026-10-19. Probed.
- **Overloads still split the compilers.** Where `apply(x: i64, f: def(i64): i64)` and
`apply<F>(x: i64, f: F) where F: invokable<def(i64): i64>` take the same arguments,
the rebuild gives a lambda the function type and calls the first, and C refuses the
lambda, since no function type is expected. Neither gives a lambda its types from the
bound of a generic overload, even where the other overloads take fewer arguments. So
overloads still don't serve both forms (decision 1). Probed.
- **A key's type is inferred from what gives it,** in both compilers, as `K` of
`least_by_key<F, K>` from a lambda giving a `u32`. Probed again.
- **A test taken by value is a copy.** A functor counting what it's asked counts in the
algorithm's copy, and lent as `&mut` it counts in the caller's. Both work in both
compilers. Probed again.
- **`strview` isn't `ordered`.** Its `compare` takes the other view by value, not as
`&self`, so `<` doesn't work on text views, in either compiler. Taking `&strview` fixes
it. `string` is ordered, so `sort` sorts strings, as std's tests do.
- **`for &each in v` over a vector runs about 1.4 times** `span::contains`, and twice the
loop over indexes, in the rebuild. It ran about 3 times `span::contains` on
2026-10-09, before `maybe<&T>` was one word. std's algorithms loop over the span's
pointer.
- **`sort_words` is gone.** std's `sort`, `heap` and `groups` replaced both copies, in
`machine/heap.sakura` and `native/registers.sakura`, on 2026-10-19.
- **std's `sort_by` and `partition_point` take a function type,** `def(&T, &T): bool`
and `def(&T): bool`, where the iterators' adapters and consumers take
`F: invokable`. A functor reaches them only through a lambda calling it (decision 1).
- **std's `pop`s give nothing back.** `stack`, `queue` and `heap` `pop` the value `peek`
reads, and give nothing back. `vector::truncate()` removes the last, which `last()`
reads, and is named apart from `pop`, its comment says, since a vector is no stack.
So this plan's `vector::pop(): maybe<T>` would be a `pop` unlike the others, and its
`truncate(length)` takes a name std uses (decision 5).
- **Fixed while probing** on 2026-10-09, in both compilers' sources, each with a test:
- The rebuild moved a functor called as `f(x)` to the heap on every call, where
`f.invoke(x)` kept it in the frame: 1.45 s against 0.09 s for the functor search.
Its `keeps` analysis also took `f(x)` to keep `f`.
- Fixing that showed an older fault: the rebuild's machine ran a function returning
a struct of no fields with a destination its code didn't take, and gave wrong
values or crashed. Native code was right.
- C refused `f(x)` in a generic of another module where `f` was a `&mut` functor
whose `invoke` wasn't `pub`, and accepted `f.invoke(x)`.
- The rebuild didn't infer the `K` of `invokable<def(&T): K>` from a function given
for it, which C did.
## What's there now
- **`span<T>`** (std/containers/span.sakura): `index_of`, `last_index_of`, `count_of`,
`contains`, `equals`, `first`, `last`, `get` and `sub`. In a sorted run, `lower_bound`
and `upper_bound` by `<`, and `partition_point` by a test, `def(&T): bool`.
- **Sorting** (std/containers/sort.sakura): `sort`, by `<`, and `sort_by`, by a function
`def(&T, &T): bool`, of `slice<T>` and `vector<T>`.
- Both are stable. Runs of 16 are sorted by insertion, then merged in pairs, back and
forth with a buffer as long as the run, from the program's heap. No allocator is
taken.
- Elements are moved byte for byte, so strings and other owning values sort without
being copied or closed.
- One core, `sort_elements<T, O>`, is generic over a private trait, `sort_order<T>`:
`natural_order<T>` gives `<`, and `given_order<T>` holds the function.
- **`vector<T>`:** `append`, `extend`, which copies a span's elements, `insert_at`,
`remove_at`, `remove`, `truncate()`, which closes the last, `first()` and `last()`,
which give a reference and stop the program where it's empty, `resize(size)` and
`resize(size, fill)`, `clear`, `reserve`, `drain(range)` and `from(iterator)`. Nothing
takes the last out, and there's no `retain` or `dedup`.
- **`heap<T>`** (std/containers/heap.sakura): least first by `<`, with `push`, `peek`,
`pop`, which gives nothing, `view` and `clear`. No order but `<`.
- **`groups<T>`** (std/containers/groups.sakura): elements gathered by a key from 0, in
two passes: `count` each key's, `seal`, which turns the counts into starts, then `put`
each. `of(key)` gives a run as a span.
- **`runs<T>`** (std/containers/runs.sakura): many short lists in one block, each added
whole by `add(span)` or built by `push` and `end`, named by a `u32`, and read by
`view(id)`.
- **The iterators' consumers,** default methods of `iterator<T>`
(std/traits/iterator.sakura), over any iterator, as `v.iter()`: `count`, `sum`,
`product`, `fold`, `reduce`, `any`, `all`, `find`, `position`, `min`, `max`, `min_by`,
`max_by`, `min_by_key`, `max_by_key`, `last`, `nth`, `for_each`, `to_vector` and
`into`. Their tests, orders and keys are anything `invokable` (README, "Control
flow"), and `rev()` walks a view from its far end.
- **`min`, `max` and `clamp`,** in `std::math` (std/math/exact.sakura), for every ordered
type. Of reals, `min` and `max` give NaN where either is NaN, and put `-0` below `0`.
- **`invokable<def(...): R>` and `signature`,** in `std/traits`. Functions, lambdas and
addresses of C functions meet `invokable` through an `invoke` the compiler gives them.
A value of any other type is called through its own `invoke`, so `f(x)` works on all of
them. A lambda leaving out its types takes them from an `invokable` bound, in both
compilers. `function<S>` (std/functions/function.sakura) holds any callable.
- **No** `swap`, `reverse`, `fill` of a slice, `is_sorted`, sort by a key, sort that
allocates nothing, or heap by an order given.
## What it needs
Of the ten needs this plan began with, std meets bisection, the tests over a run,
grouping, a heap, `min`, `max` and `clamp`, and owning elements sorted and moved. It
sorts stably. What's left:
1. **Sorting by a key,** and **sorting in place without allocating** where equal
elements may move.
2. **Orders and tests of every kind** for `sort_by` and `partition_point`, as the
iterators take them: functions, lambdas, and functors holding what they need.
3. **Changing a run:** swapping, reversing and filling, and, for vectors, taking the
last out, keeping only some, and dropping repeats.
4. **`is_sorted`,** to check a run's order.
5. **As fast as code written out,** so the compiler loses nothing by using them.
## How it fits the rules
- **Elements are moved, never copied,** except where a type copies freely.
- `swap` copies plain data through a held value, and swaps the bytes of anything that
closes, so nothing is closed twice, as `heap`'s private `swap` does.
- Sorting and reversing move elements only by `swap`, or byte for byte as std's sort
does, so they work on strings and other owning values.
- `fill` copies, as `resize(size, fill)` does, so it needs `copyable` or plain data.
- **Nothing allocates** but the stable sorts, which take a buffer as `sort` does now,
and `groups`, which is a container.
- **Tests, orders and keys are anything `invokable` (decision 1):** a function, a
lambda, or a functor, or `&mut` one.
- Each is taken by value, as a function value is. A functor is copied in, or moved in
where it owns something.
- `&mut f` lends a functor instead, so the caller keeps it and sees what it changed.
- An algorithm is compiled for each functor's type, so a functor's `invoke` is a
direct call.
- **Orders come three ways:**
- through `ordered`, where `<` is inlined: `sort`;
- through anything invokable as `def(&T, &T): bool`: `sort_by`;
- through a key it gives: `sort_by_key`.
One sorting core serves all three, generic over its order, as `sort_elements` is now.
`sort` gives it `by_order::<T>{}`, `sort_by` the order given, and `sort_by_key` a
`by_key` holding the key's function. They take the place of the private
`sort_order<T>`, `natural_order<T>` and `given_order<T>`.
- **Bounds:** `where`, on free functions, on a method's own type parameters, as `F` and
`K` of `sort_by_key<F, K>`, on a struct, as `by_order` and `by_key`, and on a type's own
parameters at a method, as `def span<T>::is_sorted(&this): bool where T: ordered`. Both
compilers take all four now. A guard of `if const` and `compile_error` still serves
where a message of its own reads better, as std's sort has one.
- **Nothing fails:** a bisection gives a position, and what may find nothing gives a
`maybe`.
## The API (decisions 1, 2, 3 and 5)
What's there stays as it is: `sort`, `lower_bound`, `upper_bound`, `heap`, `groups`,
`runs`, the iterators' consumers, and `std::math`'s `min`, `max` and `clamp`. This adds:
```sakura
module std;
# Two values.
pub def swap<T>(a: &mut T, b: &mut T): void; # moves both, copying nothing that closes
# Orders, which the sorts take as they take any other.
pub struct by_order<T> : invokable<def(&T, &T): bool> where T: ordered {} # `<`
pub struct by_key<T, F, K> : invokable<def(&T, &T): bool>
where F: invokable<def(&T): K> where K: ordered { pub var key_of: F; } # `<` of the keys
# Reading a run: the tests, counts, least and greatest are the iterators' consumers,
# as `v.iter().any(test)` (decision 3).
pub def span<T>::is_sorted(&this): bool where T: ordered;
# In a sorted run: `partition_point` takes anything invokable, where it takes
# `def(&T): bool` now (decision 1).
pub def span<T>::partition_point<F>(&this, held: F): u64 # the first that fails
where F: invokable<def(&T): bool>;
# Changing a run where it is: methods of slice<T>, and of vector<T> as `sort` is.
pub def slice<T>::sort_by<F>(&mut this, before: F): void # stable, as now (decision 1)
where F: invokable<def(&T, &T): bool>;
pub def slice<T>::sort_by_key<F, K>(&mut this, key_of: F): void # stable
where F: invokable<def(&T): K> where K: ordered;
pub def slice<T>::sort_unstable(&mut this): void where T: ordered; # decision 2; also
# `_by` and `_by_key`
pub def slice<T>::reverse(&mut this): void;
pub def slice<T>::fill(&mut this, value: T): void;
pub def slice<T>::swap(&mut this, i: u64, j: u64): void;
# Vectors (decision 5).
pub def vector<T>::take_last(&mut this): maybe<T>; # moved out; `truncate()` closes it
pub def vector<T>::retain<F>(&mut this, keep: F): void # in order; closes the rest
where F: invokable<def(&T): bool>;
pub def vector<T>::dedup(&mut this): void where T: equatable; # equal neighbours
```
`sort_by_key` takes its buffer as `sort` does, from the program's heap.
```sakura
names.sort(); # strings are ordered
entries.sort_by_key(def(e) => e.size); # equal sizes keep their order
views.sort_by(def(a, b) => a.compare(b) < 0); # views aren't ordered
# A lambda refers to `wanted` where it is, and allocates nothing.
val slot := this.free.view().iter().position(def(c) => c.size == wanted) else { return made(); };
# A functor holds what it tests against, and is called directly. A view's iterator
# gives `&block`, so its test takes `& &block`.
struct sized : invokable<def(& &block): bool> { var wanted: u64; }
def sized::invoke(&this, c: & &block): bool { return c.size == this.wanted; }
val slot := this.free.view().iter().position(sized{ wanted = wanted }) else { return made(); };
# Lent as `&mut`, a functor keeps what it saw, once `sort_by` takes one (decision 1).
struct counting_order : invokable<def(&u64, &u64): bool> { var comparisons: u64; }
def counting_order::invoke(&mut this, a: &u64, b: &u64): bool {
this.comparisons++;
return a < b;
}
var asked := counting_order{};
words.sort_by(&mut asked);
println($"{asked.comparisons} comparisons");
deepest = math::max(inner, deepest);
while todo.take_last() is some(at) {
# ...
}
```
The two `position`s, `names.sort()`, `views.sort_by` and `math::max` work today, in
both compilers. Probed.
## How each part works
- **`sort_unstable`** is introsort (decision 2):
- quicksort with the median of three;
- insertion sort for runs of 16 or fewer;
- heap sort once the depth passes 2·log₂ n, so it's never quadratic.
It's in place, allocates nothing, and isn't stable. Probed: 0.13 s against `sort`'s
0.19 s for a million words.
- **One core, three orders, for each sort:**
- `sort`, `sort_by` and `sort_by_key` call one core, generic over its order
`F: invokable<def(&T, &T): bool>` and compiled for each order's type. std's merge
core is generic that way now, over its private trait.
- `by_order<T>`'s `invoke` is `<`, a direct call inlined at `-O2`, so sorting numbers
costs no more than written-out code. A functor's order is as cheap.
- A function value or a lambda costs an indirect call per comparison, as through
`given_order` now: 0.26 s against 0.19 s. Every function value of a signature shares
one instance of the core, so not even a named function's order is inlined into it.
- **`sort_by_key`** is the stable merge sort through `by_key`, which compares the keys
its function gives. A functor's key cost 0.15 s against `<`'s 0.14 s on 2026-10-09.
- **`partition_point`** is the bisection there now, taking `F` rather than a function
type. The compiler's calls of it give lambdas, which still work.
- **`is_sorted`** compares each element with the one before.
- **`reverse`** swaps from both ends inward. **`fill`** copies its value into each
element, closing what was there. A slice's **`swap`** swaps two of its elements as the
free `swap` does.
- **`take_last`** moves the last element out and shortens the vector, giving `none`
where it's empty.
- **`retain`** moves the kept elements down in one pass and closes the rest. Calling
`remove_at` in a loop shifts the tail for every removal.
- **`dedup`** keeps the first of each run of equal neighbours and closes the rest, in
one pass.
- **Tests, orders and keys:**
- A functor is cheap: the functor search ran as fast as `span::contains`. In the
rebuild, a named function or a lambda referring to nothing is as cheap, where the
algorithm is inlined.
- A lambda referring to locals allocates nothing, but is called through its value:
0.44 s against 0.19 s for the same search by a functor. That's fine outside hot
loops.
- Decision 4 is whether the rebuild learns to call that lambda directly too.
## What the compiler gains
These counts come from the rebuild as it stands on 2026-10-20: about 72,700 lines in
`analyzer/`, `compiler/`, `machine/`, `native/` and `entry.sakura`, where there were
about 49,000 on 2026-10-08.
**Moved onto std on 2026-10-19,** apart from this plan:
| Written by hand on 2026-10-08 | Sites then | Now |
|---|---|---|
| A heap sort of words with keys packed in, as `key << 32 \| item` | 5 calls, 2 copies of the sort | `sort` at 7 sites, `sort_by` at 3 and one more in `server/`, `heap`, and `groups` |
| Pack, sort, count, sum and scatter into a `*_first` array | 2: live-ins and gap moves | `groups` |
| Count, sum and fill, in two passes | 4 more | `groups` and `runs` |
| Loops from one `_first` entry to the next | at least 9 | `groups::of` and `runs::view` |
| Bisection | 5 | `lower_bound`, `upper_bound` and `partition_point`, at 10 sites |
| A binary heap | 1 | `heap<u64>`, of a start and an interval packed as a pair's key |
| A loop filling a vector after `resize` | 12 | `resize(size, fill)`, at 34 sites |
| A loop appending another run's elements | 6 | `extend`, at 81 sites |
Seven `*_first` arrays are left, as `child_first`, `edge_first` and `row_first`. Some
index several vectors at once, as `child_first` does `child_starts`, `child_ends` and
`child_locs`, which neither `groups` nor `runs` holds.
**Still by hand:**
| Written by hand now | Sites | Becomes |
|---|---|---|
| `a < b ? a : b`, and the like | 38 | `math::min`, `max`, `clamp` |
| `val at: u32 = todo.last();`, then `todo.truncate();` | 29 | `take_last` |
| A loop filling a vector or array where it is | 6 | `fill` |
| Reversing | 1, in `code::reverse_postorder` | `reverse` |
| Searches by hand, as in the emitter's cells | several | `iter().any`, `position`, `index_of` |
**Before and after.** The grouping and the bisection this section showed on 2026-10-08
are done: `native/registers.sakura` counts, seals and puts the live-ins with `groups`,
and `analyzer/syntax.sakura` finds a declaration's first documentation line with
`partition_point`. What's left:
```sakura
# compiler/flows.sakura, and 28 more.
while todo.length != 0 {
val at: u32 = todo.last();
todo.truncate();
# After.
while todo.take_last() is some(at) {
```
```sakura
# compiler/emitter.sakura: whether a statement still closes a cell.
var kept := false;
for &each in this.kept {
kept = kept || each.cell == cell + 1;
}
# After. The lambda refers to `cell` where it is and allocates nothing, but is called
# through its value unless decision 4(b) is built.
val kept := this.kept.iter().any(def(each) => each.cell == cell + 1);
# Or, where it's hot, a functor, which costs what `span::contains` does.
struct closes_cell : invokable<def(& &kept_value): bool> { var cell: u32; }
def closes_cell::invoke(&this, each: & &kept_value): bool { return each.cell == this.cell; }
val kept := this.kept.view().iter().any(closes_cell{ cell = cell + 1 });
```
```sakura
# analyzer/checker/generics.sakura: the deepest nesting of a type's parts.
deepest = inner > deepest ? inner : deepest;
# After, with `import std::math`, which the compiler's sources don't import today.
deepest = math::max(inner, deepest);
```
```sakura
# compiler/intermediate/verifier.sakura: postorder turned round.
val length := order.length;
for i in 0..length / 2 {
val other := length - 1 - i;
val held: u32 = order[i];
order[i] = order[other];
order[other] = held;
}
# After.
order.slice().reverse();
```
**Speed:**
- **Sorting** became faster where `sort_words` was used: std's `sort` takes 0.19 s for
a million words, where `sort_words` took 0.30–0.35 s on 2026-10-08.
`sort_unstable` would take 0.13 s.
- **The two pack-and-sort groupings** became linear with `groups`.
- **Pops, `min` and `reverse`** cost what they cost now.
- **Loops over a vector** that become `any`, `position` or `count` run a little faster
given a functor, 0.19 s against 0.26 s for `for &each in v`. Given a lambda referring
to locals they run slower, 0.44 s, unless decision 4(b) is built.
What's left hasn't been measured on a self-build. Phase 4 measures it, and keeps only
the changes that don't slow it.
## Lambdas for `invokable` parameters (phase 0, built)
Built with the iterators on 2026-10-19, in both compilers, as this section planned
(README, "Functions"):
- a lambda leaving out its types takes them from a type parameter's
`invokable<def(A...): R>` bound, with the type parameters inferred so far put in, and
one in the result not yet known, as `K` of a key, inferred from the lambda's result;
- the rebuild infers a type parameter from a lambda, as C does;
- a type parameter bounded only by `signature` still needs the lambda's types written.
Overloads take no part: neither compiler gives a lambda its types from the bound of an
overloaded function (see Found).
## Lambdas that refer to locals (decision 4)
The memory work of 2026-10-19 built half of what this section planned. A lambda refers
to the locals it uses where they are, through an environment that is a cell of the
frame, so nothing moves to the heap and a lambda never allocates (README, "Functions").
The search it took 3.23 s for on 2026-10-09 takes 0.44 s.
What's left is the call. The rebuild's `devirtualize` turns a `call_value` whose
function is a known constant into a direct `call`, but leaves one taking an
environment called through the value. So a lambda referring to locals isn't inlined
into the loop calling it, and costs 2.3 times a functor: 0.44 s against 0.19 s.
Decision 4 is whether that call should be direct too:
- **(a) Leave it.** A test that refers to locals in a hot loop is written as a functor,
and as a lambda elsewhere. Phase 4's measurements say where it's hot.
- **(b) Call a known lambda directly, environment and all.** `devirtualize` learns
closures: the call becomes a direct `call` given the environment. Once `any` is
inlined, the lambda is called directly, may be inlined in turn, and `promote` can then
make the locals it refers to plain values.
- It helps only where the algorithm is inlined into the code making the lambda, as
`any` and `position` are. A sort's core isn't, and calls each order through the
value, whatever this decides.
- What a program means doesn't change, only how a call is made, so the C compiler,
which only builds stage 1, needn't follow.
- It's smaller than the 150 lines planned on 2026-10-09, which included the frame
half, now built. It hasn't been estimated again.
- The 0.44 s case should come near the 0.19 s functor. That's the phase's measure.
Only a type for each lambda would inline a lambda's order into a sort. That's a change
to the language, which the memory work left open, and isn't proposed here.
## Testing
- **`test/std/algorithms.sakura`, written with `std::testing`,** beside
`test/std/containers.sakura`, which tests std's sort, heap, runs and groups now,
covers:
- **sorting,** by `sort_unstable`, `sort_by` and `sort_by_key`:
- inputs of every length from 0 to 40, and of 1,000 and 100,000 elements;
- random, sorted, reversed, all equal, and organ-pipe orders;
- an input that defeats the median of three, to drive heap sort;
- checked by `is_sorted`, and against a count of each element;
- **stability** of `sort_by` and `sort_by_key`;
- **owning elements:** strings sorted, reversed, retained and taken out, each closed
exactly once, counted as the containers' tests count closes;
- **tests, orders and keys** given as named functions, lambdas with and without their
types, functors taking `&this` or `&mut this`, and functors lent as `&mut`, whose
state the caller reads after;
- **`partition_point`** given a functor, in empty runs, below and above every
element, and among repeats;
- **the rest:** `retain` closing what it drops, `dedup`, `fill`, `reverse` of odd and
even lengths, `take_last` of an empty vector, and `swap`.
- **Where they run:** in the rebuild's machine, as executables at `-O0` and `-O2`, and
under `run --checks`, which stops at a dangling reference or a block released twice,
and lists what leaked. The C compiler and its machine must give the same.
- **Direct calls of lambdas (phase 3, if decision 4(b)):** a test of the intermediate
code showing a direct `call` of a lambda given to `any`, and the probe's loop timed.
- **The compiler moved onto them (phase 4),** after each file:
- stage 2 equals stage 3;
- the corpus passes at every level;
- the rebuild's and std's tests pass;
- the self-build's instructions are measured against before.
## Phases
About 350 lines of std and 300 of tests, judged by the size of std's sort and
containers. Decision 4(b) adds to the rebuild's optimizer only. Moving the compiler onto what's left removes
few lines, about 50: it reads better rather than shrinks.
0. **Lambdas for `invokable` parameters:** built with the iterators, 2026-10-19.
1. **`swap`, `by_order` and `by_key`;** `sort_by` and `partition_point` taking `F`
(decision 1), `sort_by_key` and `is_sorted`; the slice's `reverse`, `fill` and
`swap`; and `strview` becoming `ordered`.
2. **The vector methods** (decision 5), and **`sort_unstable`** (decision 2).
3. **Direct calls of lambdas,** if decision 4 is (b).
4. **The compiler moved onto them,** file by file: the pops, `min` and `max`, the
fills and the reverse, and searches, with functors where a test refers to locals in a
hot loop. The sorts, the heap, the groupings and the bisections moved on 2026-10-19.
5. **The README:** sorting and bisection, which it doesn't mention today, beside the
containers in "Variables and types", and the new methods.
## Later, where wanted
- **Runs already in order,** sorted in linear time: pdqsort for `sort_unstable`, or a
merge sort that finds the runs it's given, for `sort`. The compiler often sorts what's
nearly in order, such as blocks in layout order.
- **Order adaptors,** as `reversed<F>`, which gives a descending sort from any order.
- **A heap by an order given.** The register allocator packs a start and an interval
into a `u64` so `heap<u64>` orders them by `<`.
- **`groups` from a key function in one call,** as `groups::by_key(items, keys, key_of)`,
which counts, seals and puts.
- **A sort's buffer from an allocator given,** so the compiler's sorts, whose vectors
are in its scratch arena, take their buffers from it too.
- **Merging and intersecting sorted runs.** The register allocator's `intersection` is
one.
- **A bit set,** for the 56 places the compiler makes a `vector<bool>`.
- **Selection,** as `nth_element`, and parallel sorting, now that `std::thread` exists.
Built elsewhere since: **lazy adaptors,** as `map`, `filter`, `enumerate` and `zip`,
with the iterators on 2026-10-19, generic over their functions through `invokable`.
## Decisions for you
What was built since settled four of the eight decisions of 2026-10-09:
- **Where it lives:** module `std`, beside the containers, in
`std/containers/sort.sakura`, `heap.sakura`, `groups.sakura` and `runs.sakura`.
- **How they're spelled:** methods of `span`, `slice` and `vector`, as `v.sort()` and
`v.view().lower_bound(&x)`. Both compilers take `where` at a method now, so the
`if const` guards are a choice, not a need.
- **Grouping:** `groups<T>`, filled in two passes by `count`, `seal` and `put`, with
`runs<T>` for lists built one at a time. `seal` does what `prefix_sums` would have.
- **`min` and `max`:** in `std::math`, for every ordered type, with IEEE 754's rule for
reals.
The decisions on how orders are given and what a test is are one now, the first below.
The rest are left:
1. **What an order or a test is, for `sort_by` and `partition_point`:**
- **(a) Anything `invokable`, with `sort_by_key` beside them (recommended),** as the
iterators' adapters and consumers take them. A functor is called directly, `&mut`
lends one, and a lambda still leaves out its types, so no caller changes. The
private `sort_order<T>` goes.
- **(b) Function types, as now,** with `sort_by_key` taking `def(&T): K`. A functor
is given as a lambda calling it, which is called through its value.
- **(c) Both, as overloads.** Each is declared twice, and C refuses a lambda where a
function type and an `invokable` overload take the same arguments, as probed.
2. **A sort that allocates nothing:**
- **(a) `sort_unstable`, an introsort, beside the stable `sort` (recommended).** It
takes 0.13 s against `sort`'s 0.19 s for a million words, and no buffer. All seven
of the compiler's `sort`s are of `u64` words, where equal ones can't be told apart,
so stability buys them nothing.
- **(b) Only the stable `sort`,** as now, and its buffer.
3. **Tests over a run:**
- **(a) The iterators' consumers, as `v.iter().any(test)` (recommended).** There's
one of each, and views take no more names. A functor for a view's iterator takes
`& &T`.
- **(b) Also methods of `span`:** `any`, `all`, `count`, `position`,
`last_position`, `least` and `least_by_key`, as this plan had them, taking tests of
`&T`. They read shorter and take a functor of `&T`, but repeat the consumers.
4. **Lambdas that refer to locals:**
- **(a) Leave them called through their value, and write a test that refers to
locals in a hot loop as a functor (recommended).** A lambda no longer allocates,
so it costs 2.3 times a functor, not 36 times. Direct calls can follow if phase 4
shows lambdas costing where a functor would read badly.
- **(b) Also call a known lambda directly, environment and all.** Lambdas then cost
about what functors do, where the algorithm is inlined. It's in the rebuild's
optimizer only.
5. **The vector methods:**
- **(a) `take_last`, `retain` and `dedup` (recommended).** The compiler pops by hand
29 times, and taking an owning element out needs a `move` of it before
`truncate()` closes what's left. `pop` stays the name of removing without giving
back, as the stack, queue and heap have it.
- **(b) The same, with the first named `pop`,** giving a `maybe<T>`, and the `pop`s
of `stack`, `queue` and `heap` changed to match.
- **(c) None,** keeping `vector` as it is.