35 KiB
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 compiler 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.
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,clampandswap.
std has most of these now (see What's there now). What's left:
- orders and tests taken as anything
invokable, sorting by a key, and a sort that allocates nothing; swap,reverse,fillandis_sorted;- for vectors, taking the last element out, keeping only some, and dropping repeats.
Its users:
- the compiler, 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;
- the random plan (random.md), whose
shuffleswaps 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 compiler. 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 <, throughordered0.17 s A function value 0.23 s The compiler's own sort_words, a heap sort0.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_wordstook 0.30 s. - Sorting 100,000 strings by a function value worked.
- Sorting 1,000,000 structs by a function value took 0.25 s. Packing the same two
fields into words and calling
-
std's sort (2026-10-20), a stable merge sort, over a million random words made the same way:
Sort Time sort, by<0.19 s sort_by, a named function0.26 s sort_by, a lambda0.25 s 1,000,000 structs by a field, sort_bywith a lambda0.19 s The introsort above, by <, written again beside it0.13 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
groupscounts 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 orderF: invokable<def(&T, &T): bool>instead of the private trait, sorting 1,000,000 random words:How the order is given Time <, through a functor,by_order<T>0.14 s A functor comparing a key of its own 0.15 s A function value 0.22 s A function value held in a struct, as comparer<T>held it0.23 s A function value costs the same through
invokableas through a parameter of function type, or held ascomparer<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 Time A loop over indexes, written out 0.12 s span::contains0.19 s anyof a span, generic over its test, given a functor holding the value0.19 s for &each in v, written out0.26 s iter().any, given such a functor0.26 s anyof a span, given a lambda referring to the value0.44 s iter().any, given that lambda0.65 s - Memory grew in none.
- On 2026-10-09 such a lambda took 3.23 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. The compiler calls it directly and inlines it.
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 compiler'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
Fis 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::containscosts. An algorithm generic over its test is compiled for each functor's type, soinvokeis 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 compiler. The loop over indexes is faster still, 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.span.iter()gives&T, and the consumers' tests take a reference to what's given, soiter().anywantsinvokable<def(& &block): bool>. A functor taking&blockdoesn't meet it. A lambda doesn't care (decision 3). -
Bounds at methods work now. The compiler takes
def span<T>::is_sorted(&this): bool where T: ordered, and the method belongs only to orderedT(README, "Methods and properties"). std'slower_bound,upper_bound,sortandheapguard withif const !(T is ordered)andcompile_error, which gives a message of their own. Probed. -
Lambdas take their types from
invokablebounds, and the compiler infers a type parameter from a lambda, asFoftake<F>(f: F)givendef(x: i64): i64 => x. That was phase 0 here, built with the iterators on 2026-10-19. Probed. -
Overloads give a lambda the function type. Where
apply(x: i64, f: def(i64): i64)andapply<F>(x: i64, f: F) where F: invokable<def(i64): i64>take the same arguments, the compiler gives a lambda the function type and calls the first. It doesn't give 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, as
Kofleast_by_key<F, K>from a lambda giving au32. 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
&mutit counts in the caller's. Both work. Probed again. -
strviewisn'tordered. Itscomparetakes the other view by value, not as&self, so<doesn't work on text views. Taking&strviewfixes it.stringis ordered, sosortsorts strings, as std's tests do. -
for &each in vover a vector runs about 1.4 timesspan::contains, and twice the loop over indexes. It ran about 3 timesspan::containson 2026-10-09, beforemaybe<&T>was one word. std's algorithms loop over the span's pointer. -
sort_wordsis gone. std'ssort,heapandgroupsreplaced both copies, inmachine/heap.sakuraandnative/registers.sakura, on 2026-10-19. -
std's
sort_byandpartition_pointtake a function type,def(&T, &T): boolanddef(&T): bool, where the iterators' adapters and consumers takeF: invokable. A functor reaches them only through a lambda calling it (decision 1). -
std's
pops give nothing back.stack,queueandheappopthe valuepeekreads, and give nothing back.vector::truncate()removes the last, whichlast()reads, and is named apart frompop, its comment says, since a vector is no stack. So this plan'svector::pop(): maybe<T>would be apopunlike the others, and itstruncate(length)takes a name std uses (decision 5). -
Fixed while probing on 2026-10-09, in the compiler's sources, each with a test:
- The compiler moved a functor called as
f(x)to the heap on every call, wheref.invoke(x)kept it in the frame: 1.45 s against 0.09 s for the functor search. Itskeepsanalysis also tookf(x)to keepf. - Fixing that showed an older fault: the 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.
- The compiler didn't infer the
Kofinvokable<def(&T): K>from a function given for it.
- The compiler moved a functor called as
What's there now
span<T>(std/containers/span.sakura):index_of,last_index_of,count_of,contains,equals,first,last,getandsub. In a sorted run,lower_boundandupper_boundby<, andpartition_pointby a test,def(&T): bool.- Sorting (std/containers/sort.sakura):
sort, by<, andsort_by, by a functiondef(&T, &T): bool, ofslice<T>andvector<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<, andgiven_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()andlast(), which give a reference and stop the program where it's empty,resize(size)andresize(size, fill),clear,reserve,drain(range)andfrom(iterator). Nothing takes the last out, and there's noretainordedup.heap<T>(std/containers/heap.sakura): least first by<, withpush,peek,pop, which gives nothing,spanandclear. No order but<.groups<T>(std/containers/groups.sakura): elements gathered by a key from 0, in two passes:counteach key's,seal, which turns the counts into starts, thenputeach.of(key)gives a run as a span.runs<T>(std/containers/runs.sakura): many short lists in one block, each added whole byadd(span)or built bypushandend, named by au32, and read byview(id).- The iterators' consumers, default methods of
iter<T>(core/traits/iteration.sakura), over any iterator, asv.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_vectorandinto. Their tests, orders and keys are anythinginvokable(README, "Control flow"), andrev()walks a view from its far end. min,maxandclamp, instd::math(std/math/exact.sakura), for every ordered type. Of reals,minandmaxgive NaN where either is NaN, and put-0below0.invokable<def(...): R>andsignature, instd/traits. Functions, lambdas and addresses of C functions meetinvokablethrough aninvokethe compiler gives them. A value of any other type is called through its owninvoke, sof(x)works on all of them. A lambda leaving out its types takes them from aninvokablebound.function<S>(std/functions/function.sakura) holds any callable.- No
swap,reverse,fillof 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:
- Sorting by a key, and sorting in place without allocating where equal elements may move.
- Orders and tests of every kind for
sort_byandpartition_point, as the iterators take them: functions, lambdas, and functors holding what they need. - Changing a run: swapping, reversing and filling, and, for vectors, taking the last out, keeping only some, and dropping repeats.
is_sorted, to check a run's order.- 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.
swapcopies plain data through a held value, and swaps the bytes of anything that closes, so nothing is closed twice, asheap's privateswapdoes.- 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. fillcopies, asresize(size, fill)does, so it needscopyableor plain data.
-
Nothing allocates but the stable sorts, which take a buffer as
sortdoes now, andgroups, which is a container. -
Tests, orders and keys are anything
invokable(decision 1): a function, a lambda, or a functor, or&mutone.- Each is taken by value, as a function value is. A functor is copied in, or moved in where it owns something.
&mut flends 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
invokeis 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_elementsis now.sortgives itby_order::<T>{},sort_bythe order given, andsort_by_keyaby_keyholding the key's function. They take the place of the privatesort_order<T>,natural_order<T>andgiven_order<T>. - through
-
Bounds:
where, on free functions, on a method's own type parameters, asFandKofsort_by_key<F, K>, on a struct, asby_orderandby_key, and on a type's own parameters at a method, asdef span<T>::is_sorted(&this): bool where T: ordered. The compiler takes all four now. A guard ofif constandcompile_errorstill 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:
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.
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.span.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.span.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 positions, names.sort(), views.sort_by and math::max work today.
Probed.
How each part works
-
sort_unstableis 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_byandsort_by_keycall one core, generic over its orderF: 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>'sinvokeis<, 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_ordernow: 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_keyis the stable merge sort throughby_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_pointis the bisection there now, takingFrather than a function type. The compiler's calls of it give lambdas, which still work. -
is_sortedcompares each element with the one before. -
reverseswaps from both ends inward.fillcopies its value into each element, closing what was there. A slice'sswapswaps two of its elements as the freeswapdoes. -
take_lastmoves the last element out and shortens the vector, givingnonewhere it's empty. -
retainmoves the kept elements down in one pass and closes the rest. Callingremove_atin a loop shifts the tail for every removal. -
dedupkeeps 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. 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 compiler learns to call that lambda directly too.
- A functor is cheap: the functor search ran as fast as
What the compiler gains
These counts come from the compiler 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:
# 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) {
# 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.span.iter().any(closes_cell{ cell = cell + 1 });
# 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);
# 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_wordswas used: std'ssorttakes 0.19 s for a million words, wheresort_wordstook 0.30–0.35 s on 2026-10-08.sort_unstablewould take 0.13 s. - The two pack-and-sort groupings became linear with
groups. - Pops,
minandreversecost what they cost now. - Loops over a vector that become
any,positionorcountrun a little faster given a functor, 0.19 s against 0.26 s forfor &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, 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, asKof a key, inferred from the lambda's result; - the compiler infers a type parameter from a lambda;
- a type parameter bounded only by
signaturestill needs the lambda's types written.
Overloads take no part: the compiler doesn't give 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 compiler'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.
devirtualizelearns closures: the call becomes a directcallgiven the environment. Onceanyis inlined, the lambda is called directly, may be inlined in turn, andpromotecan then make the locals it refers to plain values.- It helps only where the algorithm is inlined into the code making the lambda, as
anyandpositionare. 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.
- 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.
- It helps only where the algorithm is inlined into the code making the lambda, as
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 withstd::testing, besidetest/std/containers.sakura, which tests std's sort, heap, runs and groups now, covers:- sorting, by
sort_unstable,sort_byandsort_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_byandsort_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
&thisor&mut this, and functors lent as&mut, whose state the caller reads after; partition_pointgiven a functor, in empty runs, below and above every element, and among repeats;- the rest:
retainclosing what it drops,dedup,fill,reverseof odd and even lengths,take_lastof an empty vector, andswap.
- sorting, by
- Where they run: in the machine, as executables at
-O0and-O2, and underrun --checks, which stops at a dangling reference or a block released twice, and lists what leaked. - Direct calls of lambdas (phase 3, if decision 4(b)): a test of the intermediate
code showing a direct
callof a lambda given toany, 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 compiler'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 optimizer only. Moving the compiler onto what's left removes few lines, about 50: it reads better rather than shrinks.
- Lambdas for
invokableparameters: built with the iterators, 2026-10-19. swap,by_orderandby_key;sort_byandpartition_pointtakingF(decision 1),sort_by_keyandis_sorted; the slice'sreverse,fillandswap; andstrviewbecomingordered.- The vector methods (decision 5), and
sort_unstable(decision 2). - Direct calls of lambdas, if decision 4 is (b).
- The compiler moved onto them, file by file: the pops,
minandmax, 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. - 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, forsort. 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
u64soheap<u64>orders them by<. groupsfrom a key function in one call, asgroups::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
intersectionis one. - A bit set, for the 56 places the compiler makes a
vector<bool>. - Selection, as
nth_element, and parallel sorting, now thatstd::threadexists.
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, instd/containers/sort.sakura,heap.sakura,groups.sakuraandruns.sakura. - How they're spelled: methods of
span,sliceandvector, asv.sort()andv.span.lower_bound(&x). The compiler takeswhereat a method now, so theif constguards are a choice, not a need. - Grouping:
groups<T>, filled in two passes bycount,sealandput, withruns<T>for lists built one at a time.sealdoes whatprefix_sumswould have. minandmax: instd::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:
- What an order or a test is, for
sort_byandpartition_point:- (a) Anything
invokable, withsort_by_keybeside them (recommended), as the iterators' adapters and consumers take them. A functor is called directly,&mutlends one, and a lambda still leaves out its types, so no caller changes. The privatesort_order<T>goes. - (b) Function types, as now, with
sort_by_keytakingdef(&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.
- (a) Anything
- A sort that allocates nothing:
- (a)
sort_unstable, an introsort, beside the stablesort(recommended). It takes 0.13 s againstsort's 0.19 s for a million words, and no buffer. All seven of the compiler'ssorts are ofu64words, where equal ones can't be told apart, so stability buys them nothing. - (b) Only the stable
sort, as now, and its buffer.
- (a)
- 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,leastandleast_by_key, as this plan had them, taking tests of&T. They read shorter and take a functor of&T, but repeat the consumers.
- (a) The iterators' consumers, as
- 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 optimizer only.
- The vector methods:
- (a)
take_last,retainanddedup(recommended). The compiler pops by hand 29 times, and taking an owning element out needs amoveof it beforetruncate()closes what's left.popstays the name of removing without giving back, as the stack, queue and heap have it. - (b) The same, with the first named
pop, giving amaybe<T>, and thepops ofstack,queueandheapchanged to match. - (c) None, keeping
vectoras it is.
- (a)