Foundational primitives for the gen family: intensional functions, standalone identity hashing, record algebra with scoped labels, and Either combinators.
Class A (pure, zero-input). gen-algebra declares no flake inputs and depends on nothing — not even nixpkgs lib; it is builtins-only and sits at the pure-algebra root of the ecosystem. A CI purity invariant (ci/tests/purity.nix) enforces this: any stray lib.types / mkOption / evalModules in the library source fails the suite.
gen-algebra is a fully pure Nix library — zero dependencies, builtins only. Intensional function constructors for conservative equality (Palmer §2.2-2.3). Record algebra with scoped labels (Leijen §2) and mixin composition (Bracha §2-4). Either combinators. Standalone identity hashing.
The module-system tier (identity/strict/validators/cross-registry refs for lib.evalModules) relocated to gen-schema, its sole consumer; gen-algebra is the ecosystem's pure-algebra root. Its former pure tier is now simply the lib output — everything gen-algebra ships is pure.
flake-aspects ──→ gen-algebra.mkIntensional, gen-algebra.conservativeEq
↓
gen-schema (typed registries on gen-algebra primitives;
owns the module-system tier — identity/strict/validators/refs)
↓
gen-aspects (aspect composition on gen-algebra + gen-schema)
↓
den (system configuration framework)
gen-algebra has zero flake inputs — this lineage shows where each primitive was extracted from and who consumes gen-algebra downstream, not runtime dependencies.
| Library | Role |
|---|---|
| gen-prelude | Pure nixpkgs-lib-free utility base (builtins re-exports + vendored lib utils) |
| gen-algebra | This lib — Pure primitives (record, either, intensional identity) |
| gen-types | Clean-room MIT structural type checker (leaf/poly checkers; verify: v → null|err) |
| gen-merge | Byte-mode module merge engine (evalModuleTree, byte-identical to nixpkgs lib.evalModules over the priority subset) |
| gen-schema | Typed registries (kinds, instances, collections, refs); re-hosted on gen-merge |
| gen-aspects | Aspect type system (traits, classification, dispatch); re-hosted on gen-merge |
| gen-scope | HOAG scope-graph evaluator (demand-driven, _eval memoization, circular attributes) |
| gen-graph | Accessor-based graph query combinators (traversal, condensation, phaseOrder) |
| gen-select | Selector algebra (pattern matching over graph positions) |
| gen-bind | Module binding (inject external args into NixOS modules) |
| gen-dispatch | Relational rule dispatch STEP (stratified phases, conflict resolution) |
| gen-memo | The incremental plane — decides reuse, never evaluates (change propagation, AFFECTED set) |
| gen-vars | Pure-Nix vars/secrets (den-agnostic) |
{
inputs.gen-algebra.url = "github:sini/gen-algebra";
outputs = { gen-algebra, ... }:
let
# Fully pure — no lib needed. Everything is under the `lib` output.
inherit (gen-algebra.lib)
mkIntensional
conservativeEq
record
either
;
in
{ /* ... */ };
}let
# Fully pure — no nixpkgs / lib needed. The non-flake entry is a nullary function
# (default.nix = { }: import ./lib) — `{ }` applies it to the lib value.
gen = import ./path/to/gen-algebra { };
in
{
inherit (gen) record either mkIntensional;
}
# gen.record.fromAttrs, gen.either.right, … all `builtins`-only.Every exported name is documented below, grouped by primitive family. The full surface is record (26), either (6), plus top-level mkIntensional, conservativeEq, the four identity-regime readers (identityOf, regimeTagOf, isExact, comparisonSubject), the two mark readers (hasMark, markOf) and the four composite-preimage names (preimageTagOf, componentsPreimage, sealedCollisionEq, sealedMarker) — verified against nix eval .#lib.
Palmer §2.2-2.3: function wrappers with program-point identity, built by an encoder rather than assembled by the caller. Palmer discharges his closure-consistency requirements by construction at an encoder and never by a check, and this constructor is that transposed: the author names a constructor and an inert argument value, and a registry supplies the body.
mkIntensional : hashIdentity -> registry -> ctor -> args -> intensionalregistry is { revision; members; }, where members maps a constructor name to a builder over the
inert argument value. revision is required and total — a registry without one is refused by name
at construction, never defaulted.
registry = {
revision = "r1";
members.addN = args: (x: x + args.n);
};
mk = mkIntensional genIdentity.hashIdentity registry;
fn = mk "addN" { n = 1; };
fn 5 # → 6 (callable via __functor)
fn.name # → "addN" (the program point, DERIVED from the constructor)
fn.closure # → { n = 1; } (the reified argument value — it IS `args`)
fn.__mint # → { unmintable = { ctor = "addN"; reason = "…"; subject = { registry; ctor; args; }; }; }A registered construction is compared, never minted. Its registry coordinate discharges only on
the declared revision, so a digest over it would be a decision predicate and never a key: the value
carries no digest and declares its comparison subject instead (the registry coordinate, the
constructor and the inert arguments). identityOf therefore finds no exact identity (isExact is
false, so no key site keys on it), comparisonSubject answers the declared subject, and
conservativeEq decides two constructions of one term true and a different argument, member set or
revision false. The honest-mistake residue stays: two registries with the same members and revision
and different builder bodies decide true, which is the declared revision's obligation.
The mint is injected. The encoder takes hashIdentity and computes nothing with it (above);
preimageTagOf and componentsPreimage mint with it. It is the substrate's one minting authority and it lives in
gen-identity, a dependency-free leaf. It was gen-schema's, downstream of gen-algebra, and
importing it would have closed a flake dependency cycle — which is why the injection exists and why
the authority became a leaf. Taking it as a
constructor parameter mints the value inside the consumer's own eval — the identity is owned rather
than borrowed, and gen-algebra keeps its zero-dependency property.
There is no closure argument to under-supply. The shipped constructor took the name and the
closure from the caller, so an under-complete closure was undetectable and two bodies could share
one program point. Here both are derived: name = ctor, closure = args.
The registry construction is Lorenzen's lazy constructor (§1). A lazy constructor holds inert
first-order operands and no behaviour; the behaviour is "the associated right-hand side of the data
declaration", looked up by constructor when forcing arrives. { ctor; args; } is inert, registry.members.<ctor> args is applied only at demand, through __functor, and no other field forces it — so the operands
are readable on a value nobody has applied, as Lorenzen's debug-show reads a lazy constructor
without forcing it. Where the two part company is openness: §8 records that lazy constructors "have
to be declared up-front in the data type definition", so one declaration site fixes the whole map and
no coordinate is needed to say which map was meant. Here the registry is a value a caller supplies,
which is exactly why revision has to enter the identity coordinate below.
Reynolds is the constructor-plus-inert-argument shape only (§6, pp. 376-377) — not this
registry. His record fields are read off the lambda's own global variables (§6's table gives one
record equation per lambda expression) rather than chosen by a caller; elimination is a single
interpretive apply doing closed case analysis over FUNVAL = CLOSR ∪ SC ∪ EQ1 ∪ EQ2, where dispatch
here is an attribute selection into an open map; and that union is enumerated from every lambda
expression in the program, making it a whole-program transformation with no registry to pass.
The identity coordinate is (registry, ctor, args). The registry term is not decoration — Nix has
no linking, so a builder's free variables include its registry module instance's whole lexical scope.
Without it, two pins of the substrate give the same ctor and the same args one identity for two
behaviours.
Palmer's own term (§2.3, §5.3, §8) — "intensional" qualifies the function, never the equality. Fig. 5 is a conjunction over identity AND closure, and the relation this replaces shipped the first conjunct alone, which coarsens: it called behaviourally distinct functions equal, the one direction §2.3's guarantee forbids.
a = mk "addN" { n = 1; };
b = mk "addN" { n = 2; };
conservativeEq a b # → false — one program point, two substitutions, two behaviours
a 5 # → 6
b 5 # → 7
c = mk "addN" { n = 1; };
conservativeEq a c # → true — independently constructed, one coordinate, one identityThe relation dispatches on the identity regime rather than reading one field, and it has two
arms, neither of which merges more than Fig. 5 over non-derivation operands (Nix == compares two
type = "derivation" attrsets by outPath alone, so a derivation-shaped pair differing only in
closure compares equal; the relation therefore excludes every derivation — see conservativeEq's binding in
lib/intensional.nix). Where both sides carry a minted identity the
digests decide, which is exact and fuses both of Fig. 5's conjuncts. Every other pair — sealed,
unmigrated or mixed — falls through to the reified value itself, never a list of
components; on lambda-carrying values its precision is an allocation artefact, so two
separately-constructed equal-shaped values compare unequal and that arm merges strictly less than
Fig. 5, while on inert values it both identifies and separates. There is no name arm: deciding an
unmigrated pair on name alone would call two values at one program point with differing closures
equal, which Fig. 5 forbids. The name stays the unmigrated regime's bucket label at the key site
(below) and never decides.
The producer's witnesses are read first. A mark is minted over the value its producer
completed, and a Nix // copies the mark with every other slot, so whether a carried mark still
states the value is read when the relation decides. A producer declares which of its fields witness
it, by field name, in __witness, beside __mint:
__witness = {
completion = "<field>"; # the field holding `_: <the completed value>`
checks = { <field> = "<witness field>"; }; # a field published beside a witness of its value
};Each operand then reads as one of three standings. Refused: it departs from the value its
completion witness returns (a // copy), it declares a completion witness it does not carry as a
function, its mark comes with a declaration naming no completion, or the declaration is not a
record of field names. Any of these throws a refusal by name. Compared: a declared checks
field no longer holds its witness (a wrapper rewrote it), so the mark is only a bucket label, and
the pair is decided over comparisonSubject; identityOf answers the compared arm for such a
value. Holds: otherwise, and the arms above decide. A value declaring nothing holds. gen-types
publishes its declaration as typeWitness, and gen-merge and gen-schema declare theirs where they
complete a value.
Closures first. An undeclared attrset's subject is [ (closuresOf v) v ]: its function-valued
fields, then the whole record. List == decides the first element before the second, and == on
two functions answers without entering either closure, so two records whose closures differ decide
false before == can walk a back-edge (a nixpkgs record's functor.type across two lib
instances). Finding the function-valued fields forces every field, inside tryEval, so a field that
throws is left to the record's ==. The value moves in two places: a derivation-shaped pair decides
on its closures, which is finer than outPath alone, and a field whose evaluation fails
uncatchably aborts where the bare == would have decided on another attribute first (nixpkgs lib
on Lix, whose convertHash names a builtin Lix lacks).
The fall-through is total over inert attrset operands and partial over three populations, the
same boundary gen-select rules at selectorEq: a payload that refuses under any key surfaces its
own catchable throw, and a self-referential payload whose closures are all shared aborts the
evaluator uncatchably. Nothing is excluded: a value's fields are total data, and demanding an
identity is gen-types' idOf, a function rather than a field.
A component-wise conjunct is not the remedy. This design's component-list rule holds that a
constructor's declared components name what the comparison's subject must be, and never a set of
components to be compared one by one; the foreclosure rests on that rule alone, not on any claim
that a component-wise form cannot work. Nix == short-circuits on pointer identity, so an attribute
selection compares true against itself even when the selected value holds a lambda, and the
component-wise form would be finer rather than empty — only separately allocated lambdas compare
false.
A key site that dedups on these identities reads the same discipline rather than calling
conservativeEq: it keys exactly where an identity is minted and buckets otherwise, every key
carrying a regime tag so the three arms occupy disjoint key spaces, and a bucket stores its members
and compares inside itself (isExact's obligation, lib/intensional.nix).
The search namespace (Palmer §3's Search monad and its converge runner) is retired: gen
has one evaluator, gen-scope, and converge was a second one, interpreting a caller-authored
continuation program on its own carrier and its own round schedule. Its encoding also departed
from the primary where it mattered: Palmer's Search is idempotent, deduplicating repeated inserts,
and gen's appended them.
A composite whose components sit on different identity regimes stays minted: each component
enters the composite's preimage as a preimage tag, and one sealed component does not drag the
whole composite onto the comparison arm. The mint is injected, as mkIntensional takes it.
preimageTagOf hashIdentity v gives one tag per value shape, each a record under its own key:
| value | tag |
|---|---|
| carries a minted identity | { minted = <digest>; } |
| throws (catchably) at WHNF: no value to identify | { undefined = true; } |
| the mint takes it: an inert value | { inert = <digest>; } |
| anything else: a lambda, a path, a derivation, an unmigrated or partly defined value | sealedMarker ({ sealed = true; }) |
componentsPreimage hashIdentity [
{ path = [ "port" ]; value = 80; }
{ path = [ "body" ]; value = x: x; sealed = true; } # declared sealed: tagged, never forced
]
# → { tags = { port = { inert = "…"; }; body = { sealed = true; }; };
# sealed = { body = <the lambda>; }; }componentsPreimage returns the tags a composite mints over and the sealed subjects a
comparison reads, from one call, so the two cannot describe different planes. A duplicate path,
a non-string segment or a non-boolean sealed is refused by name.
A registered construction enters the sealed map as { compared = <its declared subject>; }, and a
minted component that itself carries a non-empty __sealed (a type or kind over a sealed component)
enters by its mark and hands its __sealed to the parent under its path, so the parent's mark never
decides on its own what the child's mark was blind to.
A value carrying a mark beside a non-empty __sealed is not an exact identity: identityOf puts it on
the compared arm (isExact false), conservativeEq decides it through sealedCollisionEq over its
mark and sealed subjects, and preimageTagOf still enters it by its mark.
A mark is not an identity. A gen-schema kind with an option default carries a non-empty __sealed,
so identityOf answers the compared arm for it, and its mark is a bucket label: a site may bucket or
look up by it and decides within the bucket over the sealed subjects with sealedCollisionEq
(gen-select's and gen-schema's kindEq), so a mark alone never decides an equal-mark pair. hasMark v decides whether v
carries a minted mark; it forces the __mint record and never the digest. markOf v demands the mark
and refuses by name where there is none, where a raw .minted read aborts uncatchably. Where nothing is
sealed the two readers agree: identityOf v is { minted = markOf v; }.
k = schema.host; # a kind whose `port` option has a default
hasMark k # → true
markOf k # → "schemakind:687e…"
regimeTagOf (identityOf k) # → "s" (a mark beside sealed components)
markOf { name = "x"; } # → error: gen-algebra: markOf: the value carries no mark …sealedCollisionEq site a b over { name; mark; sealed; } decides false on distinct marks and
true on equal marks with == sealed subjects. Equal marks with unequal subjects decide false when
every differing leaf is a compared entry whose subject is inert on both sides (a bounded walk under
tryEval): two different registered constructions, whose inequality is evidence of two
constructions. Every other unequal pair is two declarations the mark cannot tell apart, and it is
refused by name, listing the sealed components that differ, rather than merged. Two separately
built lambdas are unequal, so two constructions of one sealed declaration refuse: the same allocation
residue as conservativeEq, and so does a registered construction whose args hold a lambda.
A record algebra with scoped labels (Leijen §2) and mixin composition (Bracha §2-4). Records support duplicate labels via shadow stacks — extending with an existing label pushes a new value, restriction pops it, exposing the previous value.
All operations are in gen-algebra.record (import path) — or inputs.gen-algebra.lib.record via the flake output. Zero dependencies.
Records use an attrset-with-shadow-stack representation for O(1) select:
# Internal: { __entries = { label = [value-stack]; }; __order = [labels]; }
r = record.fromAttrs { port = 8080; hostname = "localhost"; };
record.select "port" r # → 8080
record.emit r # → { port = 8080; hostname = "localhost"; }record.empty # empty record
record.extend "x" 42 r # push value onto label's stack
record.select "x" r # head of stack (throws if absent)
record.restrict "x" r # pop head (no-op if absent)
record.has "x" r # bool: label present?
record.depth "x" r # stack depth (0 if absent)Every operation takes its label operands first and the record last (the uniform grammar's R7:
the subject is the last argument), so a partial application is a record transformer:
map (record.select "port") rs, record.compose (record.extend "a" 1) (record.extend "b" 2).
# Duplicate labels form a stack — restriction exposes previous values
base = record.fromAttrs { level = "info"; };
env = record.extend "level" "warn" base;
user = record.extend "level" "debug" env;
record.select "level" user # → "debug"
record.select "level" (record.restrict "level" user) # → "warn"
record.select "level" (record.restrict "level" (record.restrict "level" user)) # → "info"record.emit r # → plain attrset (heads only)
record.emitAll [ "validators" ] r # → full stacks for listed labels, heads for rest
record.fromAttrs { a = 1; } # → record with single-element stacks
record.show r # → "{ x = [2, 1]; y = [3] }" (full stacks)
record.showCompact r # → "{ x = 2; y = 3 }" (heads only)record.update "x" 99 r # replace head (throws if absent — strict)
record.upsert "x" 99 r # insert-or-update (no error)
record.rename "old" "new" r # move label
record.labels r # label names in insertion order# Left-biased combination (⊕): left's values shadow right's. Two operands of one sort, so one
# record (R7 (b)).
record.combine { left = a; right = b; }
# Smalltalk direction: delta wins over parent
record.mixin delta parent # → combine (delta parent) parent
# Beta direction: parent controls, delta extends
record.mixinBeta prefix suffix
# Associative mixin composition (⋆)
record.compose m1 m2 # → fun(i) m1(m2(i) ⊕ i) ⊕ m2(i)record.satisfies [ "port" "hostname" ] r # → bool
record.assertSatisfies [ "port" "hostname" ] r # → r or throws with missing fieldsFold ordered layers with per-field merge strategies. Useful for composing configuration from multiple priority tiers (e.g. defaults, system, user overrides) where different fields need different merge semantics.
Pure — builtins only, no lib dependency.
record.foldLayers {
strategies ? {}; # field name → "replace" | "append" | "recursive"
defaults ? {}; # fallback values for fields absent from all layers
layers ? []; # list of attrsets, least-specific first (base before overrides, last wins)
}Strategy types:
"replace"(default) — last layer providing the field wins. CSS cascade order: later overrides earlier."append"— list concatenation across all layers in order, starting fromdefaults. Result:defaults ++ layer1 ++ layer2 ++ ..."recursive"— nested attrset merge (//) across layers in order. Later layers override earlier keys."semilattice-set"— list-valued fields merged by set-union: fold each layer's elements into the accumulator, skipping any already present (dedup bybuiltins.elem). Unlike the three above — which are associative but order-sensitive (replaceandappendboth depend on layer order,recursiveon override order) — set-union is ACI: associative, commutative, and idempotent. The result is the layers' elements viewed as a set, so it is invariant under layer reordering and under duplicate contributions. This is the join of a set-union join-semilattice (∪ over finite sets); it is the strategy that letsfoldLayersTracedstand in for the "semi-naïve evaluation over a lattice" merge of Datafun (ICFP 2016) and Flix (PLDI 2016), where a relation's value is the least upper bound of its contributions rather than a last-writer-wins cell.
record.foldLayers {
strategies = {
tags = "append";
settings = "recursive";
# name uses default "replace"
};
defaults = {
tags = [ "base" ];
settings = { verbose = false; };
};
layers = [
# layer 0: lower priority (system)
{ name = "default"; tags = [ "system" ]; settings = { verbose = true; pager = "less"; }; }
# layer 1: highest priority (user)
{ name = "custom"; tags = [ "user" ]; settings = { color = true; }; }
];
}
# → {
# name = "custom"; # replace: last layer wins
# tags = [ "base" "system" "user" ]; # append: defaults ++ layers in order
# settings = { verbose = true; pager = "less"; color = true; }; # recursive: merge in order
# }Single-pass variant of foldLayers that also returns per-field provenance. Takes
additional layerNames (opaque labels aligned 1:1 with layers, least-specific
first), optional defaultLabel, and optional entryTransform; returns
{ value; provenance; } where provenance.<field> is an ordered list of
{ layer; value; } (default first when present, then each contributing layer).
Any value is admissible as a layer name; the fold stores each verbatim into
provenance.<field>[].layer and never reads one.
Powers settings stratification.
record.foldLayersTraced {
strategies = { tags = "append"; };
defaults = { tags = [ "base" ]; };
layers = [ { tags = [ "system" ]; } { tags = [ "user" ]; } ];
layerNames = [ "system" "user" ];
}
# → { value = { tags = [ "base" "system" "user" ]; };
# provenance.tags = [ { layer = "default"; value = [ "base" ]; }
# { layer = "system"; value = [ "system" ]; }
# { layer = "user"; value = [ "user" ]; } ]; }The value agrees with foldLayers on the strategies both accept, and only
there. Over "replace" — declared explicitly or reached by omission —
"append", "recursive", and a field carried by defaults alone, the two
return byte-identical values for the same strategies, defaults and layers;
the value-identity guards in ci/tests/rec-fold-layers-traced.nix hold exactly
that. They are not one primitive with two return shapes: "semilattice-set"
resolves here and foldLayers refuses it. Computing an expected value from the
untraced sibling is licensed on the shared domain and nowhere else.
entryTransform is an optional field -> entry -> entry' applied to every entry
of a field's chain, the default entry included. It is for a caller that wants a
derived reading of each entry — the entry's value under some substitution the
caller owns — to be emitted by the fold rather than re-mapped over its output
afterwards. The fold hands over the field name and learns nothing in return: the
transform is opaque to it, exactly as layer labels are.
record.foldLayersTraced {
defaults = { font = "unset"; };
layers = [ { font = "mono"; } ];
layerNames = [ "host" ];
entryTransform = field: entry: { inherit (entry) layer; resolved = lookup field entry.value; };
}
# → provenance.font = [ { layer = "default"; resolved = <thunk>; }
# { layer = "host"; resolved = <thunk>; } ]Non-interference. Application is per entry and demand-driven (call-by-need,
Launchbury 1993 §2). Forcing a chain's spine, one entry's own transformed record,
or any sibling entry never applies the transform to another entry, and forcing
.value never applies it at all. So a transform that is lazy in its derived part
keeps a diverging entry — one whose refinement throws, because it points at
something absent — harmless to the rest of the trace: the chain still has a
length, the entry still reports which layer it came from, its siblings still
resolve. That property, not the hook, is the capability; it is what a
consumer-side map over the finished provenance cannot give you. Omitting
entryTransform emits the chain untransformed with no per-entry application.
flattenAttrs, unflattenAttrs, and foldNestedLayers extend layer folding to
nested attrsets. They are published here as record.* and re-exported unchanged by
the gen hub as gen.lib.substrate.algebra.record.*, so the key language below is
the same on both surfaces. foldNestedLayers is foldLayers for nested
structures, with strategies keyed by path; flattenAttrs/unflattenAttrs are
the flatten/rebuild primitives for that key language (flattenAttrs halts
recursion at fields whose strategy is "recursive").
foldNestedLayers is a left fold of one binary step, with defaults as the
seed: the value is foldl' step {} ([ defaults ] ++ layers). At a path p:
strategy at p |
step(acc, v) |
|---|---|
"replace" (default) |
v an attrset: merge its keys into acc (or into {} if acc is not an attrset), each key stepping at p.k; otherwise v |
"append" |
(acc or []) ++ v; a non-list operand is refused by name |
"recursive" |
(acc or {}) // v; a non-attrset operand is refused by name |
So "last layer providing the field wins" holds whatever the shape: a later scalar
(or null, or a list) at a.b replaces the whole earlier subtree there, and later
attrsets merge onto what that reset left. A {} contributes no keys, so it keeps
the subtree it lands on (and is {} over a scalar). A default is the value layer 0
starts from, so its shape never splits the layers after it, and a default a layer
overrides is never forced (defaults.a.b = throw "required" is fine once a layer
sets a.b).
record.foldNestedLayers { layers = [ { a.b.x = 1; } { a.b = 5; } { a.b.y = 9; } ]; }
# → { a.b.y = 9; } (the 5 resets a.b; the last layer merges onto it)The algebra. The fold is a right action of the layer list on the value:
run(acc, xs ++ ys) = run(run(acc, xs), ys), with {} the identity layer at the
root. So pre-folding any prefix and resuming from it — as defaults, or as the
first layer — changes nothing. It is not associative on layers, unlike the flat
strategies above: pre-folding a block that is not a prefix changes the result. In
the example, [ { a.b = 5; } { a.b.y = 9; } ] pre-folds to { a.b.y = 9; }, and
[ { a.b.x = 1; } { a.b.y = 9; } ] gives { a.b = { x = 1; y = 9; }; }, not
{ a.b.y = 9; }: no single layer stands for a reset followed by a merge.
Refusals. Each of these throws a catchable error naming the input, prefix
rec.foldNestedLayers: — a mistyped "append"/"recursive" operand at a path
(strategy 'append' at 'a.b' needs a list, …), a layer or defaults that is not an
attrset, layers that is not a list, strategies that is not an attrset, and an
unknown strategy (unknown strategy '<a lambda>' at 'a.b', a non-string rendered by
its type). foldLayers and foldLayersTraced render a non-string strategy the same
way.
Keys are escaped attribute paths. A flat key encodes the path [s₁ … sₙ] by
escaping each segment as RFC 6901 (JSON Pointer) §3 does — ~ becomes ~0, then
. becomes ~1 — and joining the segments with . where RFC 6901 uses /. An
escaped segment contains no ., so distinct paths get distinct keys: a literal
key "a.b" and the nested path a.b stay two leaves, and an empty segment is
data rather than the root. On segments containing no ., ~ or empty name the
key is the plain dot join.
record.flattenAttrs { } { "a.b" = 1; a.b = 2; }
# → { "a~1b" = 1; "a.b" = 2; }unflattenAttrs decodes each segment in one left-to-right pass (~1 → .,
~0 → ~, the RFC 6901 §4 order) and throws, naming the key and segment, on a
segment that is not an escape — a ~ not followed by 0 or 1, e.g.
{ "a~2b" = 1; }. Decoding it leniently would let { "~" = 1; "~0" = 2; } land
on one path and drop a value.
strategies keys (and prefix, an already-encoded key, "" being the root) use
the same encoding. A strategy for a path whose segment contains . is written
escaped: strategies."a~1b.c" names [ "a.b" "c" ]. A strategy written for a
literal dotted segment as strategies."a.b" now names the path [ "a" "b" ], so
over { "a.b".p = 1; } it matches nothing and is not applied — the same silent
miss as any unmatched strategy key. A nested strategies tree looked up by path
(strategies.a.b = "append") would take the encoding off the surface callers
write by hand; it is not taken for now, and remains open while nothing calls
these functions with such keys.
Cost. Flatten re-encodes the whole path at each node and unflatten checks each segment's escape, so both remain quadratic in nesting depth, as before. The constant grows: measured in Nix values allocated for a flatten/unflatten round trip, about 1.6× on a wide tree (27 000 leaves, depth 3) and about 2.5× on a deep chain (depth 200–800).
Short-circuit and accumulating error handling via { right = value; } | { left = error; }. Zero dependencies.
All operations are in gen-algebra.either (import path) — or inputs.gen-algebra.lib.either via the flake output.
Construct Either values.
either.right 42 # → { right = 42; }
either.left "oops" # → { left = "oops"; }Short-circuit chain: first left stops the pipeline.
either.pipe [
(x: if x > 0 then either.right (x * 2) else either.left "must be positive")
(x: if x < 100 then either.right x else either.left "too large")
] 5
# → { right = 10; }Accumulate all errors without short-circuiting.
either.collectErrors [
(x: if x > 0 then either.right x else either.left "must be positive")
(x: if x > -3 then either.right x else either.left "must be > -3")
] (-5)
# → { left = [ "must be positive" "must be > -3" ]; }Map over the right value, passing left through unchanged.
either.mapR (x: x + 1) (either.right 41) # → { right = 42; }
either.mapR (x: x + 1) (either.left "err") # → { left = "err"; }FlatMap on right — apply a function that returns a new Either.
either.chain (x: if x > 0 then either.right (x * 10) else either.left "neg") (either.right 3)
# → { right = 30; }See examples/demo/ for a self-contained example exercising the record algebra and either combinators. It binds the library as import ../.. { }, so it evaluates against the checkout it ships in.
cd examples/demo
nix eval .#scopedLabels
nix eval .#eitherDemogen-algebra/
default.nix — non-flake entry (nullary function over the lib value: import ./default.nix { })
flake.nix — flake output (single `lib` value, no __functor)
lib/
default.nix — exports intensional + either + record
intensional.nix — mkIntensional, conservativeEq, the identity-regime discipline
either.nix — Either combinators (right, left, pipe, collectErrors, mapR, chain)
rec.nix — Leijen §2 record algebra with scoped labels + Bracha §2-4 mixin composition + foldLayers
ci/ — nix-unit test suite (incl. the purity invariant)
examples/
demo/ — self-contained demo (records + either)
gen-algebra is fully pure — zero dependencies of any kind, not even nixpkgs lib. The CI purity invariant (ci/tests/purity.nix) enforces this: a stray lib.types / mkOption / evalModules in the library source fails the suite. The module-system tier relocated to gen-schema, its sole consumer.
Tests live in ci/ and run under nix-unit (via gen-harness.lib.mkCi). 263 test cases across 16 suites (nix develop ./ci --command ci ⇒ 263/263 successful) (either, intensional, intensional-cplus, mark, purity, repl, term, rec-primitives, rec-derived, rec-row, rec-composition, rec-composition-reference, rec-fold-layers, rec-fold-layers-traced, rec-nested-layers, gen-ci-examples), including the purity invariant that fails on any stray lib.types / mkOption / evalModules in the library source. gen-ci-examples is gen-harness's examples guard (declared in ci/tests/examples.nix, gen.ci.examples): it holds that examples/ directory names equal the declared names, and that every declared example forces under deepSeq. Requires nix-unit. Cells whose expr must throw a named refusal live on the second output, ci/tests-error.nix (48 cells across 7 suites: nix develop ./ci --command ci --tests-error, or nix-unit --flake ./ci#testsError). Cells whose verdict is an evaluator count live on the third output, ci/tests-process.nix (nix develop ./ci --command ci --tests-process): each runs in its own serial evaluator process, under every evaluator column. They hold that a composition step's entries cost the labels its operands share (thunks and environment bytes per step stay flat as a fold of mixin, combine or compose doubles from 8 to 64 steps), and that { } is tagged once per partial application of preimageTagOf.
# all suites
nix develop ./ci --command ci
# one suite
nix develop ./ci --command ci rec-compositionci refuses when anything under a declared read root is unknown to git — any extension or name,
_-prefixed included — and the remedy is git add or a move. The bare nix-unit --flake ./ci#tests
and nix flake check ./ci are unguarded: they read a git-filtered copy of the tree, so an untracked
cell is silently absent and the run stays green.
| Paper | Relationship | Used for |
|---|---|---|
| Palmer et al. (2024) Intensional Functions | Informed by | The Search monad of §3 was implemented and is retired, since gen-scope is gen's one evaluator (its encoding also departed from the primary: gen's insert appended where Palmer's Search deduplicates); the three intensional eliminators __functor/name/closure (§2.2-2.3). The constructor is an encoder (§5's Def 5.5–5.7 discharged by construction, as Palmer discharges them, rather than by a check), and conservativeEq is regime-dispatched — exact where an identity is minted, a bucket or whole-value == otherwise — because Fig. 5 is a conjunction and the name-only relation gen used to ship merged behaviourally distinct functions. The closure-consistency hypotheses discharge CONDITIONALLY, on the registry revision a declaration can get wrong; the condition disappears only when builders become first-order terms. Theorem 1 does not transfer at all: it is a preservation theorem about 𝜆ITS reduction and gen is not 𝜆ITS. |
| Lorenzen et al. (2025) First-Class Labels: First-Order Laziness | Implements | The registry construction in lib/intensional.nix is a lazy constructor (§1): inert first-order operands, with behaviour "the associated right-hand side of the data declaration" looked up by constructor at forcing, and the operands readable before anything is forced. The mechanism was identified at the landed construction rather than derived from the paper, and the fit is exact for §1's construct alone — none of the paper's memoization, in-place reuse or reference-counting results are claimed. Where the two part company is openness: §8 records the up-front data-type declaration as a limitation, and it is precisely because gen's registry is an open caller-supplied value that revision must enter the identity coordinate. |
| Reynolds (1972) Definitional Interpreters for Higher-Order Programming Languages | Informed by | The constructor-plus-inert-argument shape only (§6, pp. 376-377) — replace a function value by a tag plus inert fields and interpret the tag. Scoped deliberately: his record fields are read off the lambda's own global variables (§6's one-record-equation-per-lambda table) where an author here chooses args; elimination is a single interpretive apply doing closed case analysis over FUNVAL = CLOSR ∪ SC ∪ EQ1 ∪ EQ2 where dispatch here selects into an open map; and the union is enumerated from every lambda in the program, so it is a whole-program transformation with no registry. |
| Leijen (2005) Extensible Records with Scoped Labels | Implements | Record algebra with extension/selection/restriction (§2), scoped labels via shadow stacks (§2.1-3.2), row compatibility checks (§3.1) |
| Bracha & Cook (1990) Mixin-Based Inheritance | Implements | Left-biased combination (§2.1 ⊕ operator), Smalltalk-direction mixin (§2.1), Beta-direction mixin (§2.2), associative mixin composition ⋆ (§4) |
Implements means the code directly realizes the paper's constructs (lib/intensional.nix for Palmer's intensional structure and for Lorenzen's lazy constructor; lib/rec.nix for Leijen and Bracha). One caveat on the Palmer row: conservativeEq dispatches on the identity regime rather than realizing Fig. 5 — its minted arm fuses both conjuncts, its fall-through merges strictly less, and its unmigrated arm merges strictly more — the closure-consistency hypotheses discharge only conditionally — on a registry revision an author can get wrong — and Theorem 1 does not transfer at all. See Intensional Functions.