The small pure-utility dependency that lets the pure gen substrate drop nixpkgs.lib.
It is builtins re-exports plus the handful of pure utilities (genAttrs, unique,
filterAttrs, fix, optional, sort, …) the substrate uses, vendored
behavior-identically from nixpkgs lib.
Not a type system, not a module-system shim — only general pure utilities. The
lib.types / mkOption / evalModules tier is a separate concern (a Korora-class
replacement) and out of scope here.
Dependency class: A (pure) — the lib takes no flake inputs and imports nothing from
nixpkgs.lib; it is the nixpkgs-lib-free base every other pure gen lib depends on. The
lib flake carries zero inputs, so a consumer's lock gains no transitive nixpkgs
dependency from pulling gen-prelude in. Purity is enforced structurally (the flake has
no inputs to draw a lib from) and that structure is itself asserted, by the purity
suite, rather than left as an argument; every utility vendored from nixpkgs is held
byte-behavior-identical to its counterpart by the prelude-fidelity test suite. (The
few gen-prelude-originals with no nixpkgs counterpart — indexOf, dedupByKey — are
covered by the literal-expectation prelude suite instead; see Provenance.)
gen-prelude is a single attrset of pure functions — no inputs, no functor. Two kinds of member:
builtinsre-exports — direct aliases of Nixbuiltins(map,filter,foldl',genList,partition, …), grouped under one name so consumers need not reach intobuiltinsthemselves.- Vendored pure utilities — the small set of
nixpkgs.libhelpers the gen substrate actually uses (genAttrs,filterAttrs,unique,fix, …), copied here so the pure gen libraries can depend on gen-prelude instead ofnixpkgs.lib. Each is behavior-identical to itslib.*original.
The mental model: wherever a pure gen lib would have written lib.X, it writes
prelude.X instead and gets identical semantics with no nixpkgs.lib in its closure.
Downstream libraries — gen-graph (phaseOrder over condensation), gen-vars, gen-scope,
gen-dispatch, and others — build on exactly this surface.
| Library | Role |
|---|---|
| gen-prelude | This lib — Pure nixpkgs-lib-free utility base (builtins re-exports + vendored lib utils) |
| gen-algebra | 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-prelude.url = "github:sini/gen-prelude";
outputs = { gen-prelude, ... }:
let
prelude = gen-prelude.lib;
in
{
example = prelude.genAttrs [ "a" "b" ] (n: n + "!");
# => { a = "a!"; b = "b!"; }
};
}gen-prelude has no inputs, so nothing transitive (no nixpkgs) enters your lock. The
.lib output is a plain value — there is no gen-prelude { inherit lib; } functor call.
let
prelude = import "${builtins.fetchGit { url = "https://github.com/sini/gen-prelude"; }}/lib";
# or, against a local checkout: prelude = import ./path/to/gen-prelude/lib;
in
prelude.unique [ 3 1 1 2 3 ] # => [ 3 1 2 ]import ./lib evaluates directly to the lib attrset. The root entry is a nullary function
over it — import ./default.nix { } — so the empty call, not the bare import, is the
non-flake entry text.
Every name below is a top-level member of the lib attrset (verified against
nix eval .#lib --apply builtins.attrNames). 69 members total.
Direct aliases of Nix builtins, re-exported so consumers depend only on gen-prelude:
all any attrNames attrValues concatLists concatMap concatStringsSep elem
elemAt filter foldl' genList groupBy head isAttrs isList length listToAttrs
map mapAttrs match partition sort stringLength substring tail
Semantics are exactly those of the corresponding builtins.*.
-
isFunction f/functionArgs f— nixpkgs'lib.isFunction/lib.functionArgs: functor-aware, through a__functorthat is itself a functor or returns one. A functor carrying__functionArgs(nixpkgssetFunctionArgs, and everydoorbelow) is a function, and its published map is its arguments, at whatever returned level it is published; on a lambda they answer exactly what the builtins answer. They are NOT thebuiltinsof the same names, which read a functor as a non-function and abort uncatchably on one. They give nixpkgs' answer on every functor chain withinapplicableLevels(32)__functorsteps. Beyond it, where nixpkgs recurses until the stack overflows, each refuses catchably, naming the bound ("gen-prelude.isFunction: a functor that reaches no function within 32 `__functor` steps").isFunctionisapplicability's verdict;functionArgsis nixpkgs' recursion on the same fuel. -
patternOf f— the shape of a function's pattern,{ kind; formals; ellipsis; }, every field always present.kindis"named"forx:,"set"for{ … }:(with or without@), and"primop"for a builtin or a primop application.formalsisfunctionArgs f, andellipsisis true exactly when a set pattern carries.... It answers whatfunctionArgscannot: that is{ }forx:,{ }:and{ ... }:alike. Functor-aware by the same rule:kindandellipsisdescribe the lambda the call applies, the headapplicabilityreaches, while for a functor publishing__functionArgs,formalsis that published claim, so the two may describe different things (adoorreads"named"with its derived formals). Its domain isisFunctionvalues: a non-function is refused at the record itself. The two sources are independent, so every other refusal fires only where its field is read:kindandellipsisrefuse a rendering the parse does not read, andformalsrefuses a functor whose__functionArgsis not an attrset of booleans. A reader ofkindis never refused onformals, nor a reader offormalson the rendering. Each refusal is a catchablethrow "gen-prelude.patternOf: …". Cost, per application overfunctionArgs, derived from 100000-application totals on upstream Nix and Determinate, which count the same thunks: readingkindcosts +12.0 thunks and about 6 µs, readingformalsalone +6.5 thunks and about 1 µs, since it never renders the lambda, and the whole record +13.3 thunks; adoorcall costs +3 thunks and +4.5 µs. A consumer pays it where it reads a pattern.It depends on
builtins.toXML, the one call in the library (lib/pattern-shape.nix): no builtin exposes a function's..., so the pattern is read from the evaluator's XML rendering of the lambda, which carries the pattern and never the body or defaults. The parse is anchored on that rendering's head element (<varpat name="…" />,<attrspat>withellipsis="1"thenname="…", or<unevaluated />), and the regex never runs over a long name: it reads the rendering's first 1024 characters, and where a long name pushes the head's close past them, the rendering's token skeleton (split on", which the evaluator escapes inside every attribute value, with long values elided). No length of name is refused. Failure mode: if an evaluator changes the rendering, every read ofkindorellipsisrefuses by name and never misreads (formalsstill serves), and thepattern-shaperendering-pin cell reds in CI first. Option (c), not taken: read no XML and treat everyfunctionArgs == { }shape alike. It needs no rendering, but it cannot tellx:and{ ... }:(which accept any set) from{ }:(which accepts only the empty one), so a consumer has to hand all three the same argument; and no builtin exposes an ellipsis, so{ a }and{ a, ... }cannot be told apart under (c). -
applicability f— what Nix can apply, and the function it applies (lib/applicable.nix):{ verdict; head; }. Nix applies a set carrying__functoras(f.__functor f) x, and__functormay itself be such a set, so the reader runs that call rule for one unknown argument.verdictistruewhen it reaches a function (headis that function, the one the argument meets),falsewhen Nix would call a non-function or a__functorwhose set pattern cannot bind the pushed set (a missing required formal, or an extra attribute without...), andnullwhen no answer comes withinapplicableLevels(32)__functorsteps;headisnullunless the verdict istrue. Applicability is only semi-decidable (a__functormay return its own set forever), so the walk is fuelled, and an exhausted walk answers rather than overflowing. It runs the caller's__functorcode, and what that code throws, it throws. A{ }:__functorreads as binding (functionArgscannot tell it fromx:). -
isApplicable f— the bool a door asks:builtins.isFunction f || (applicability f).verdict == true, so a lambda costs no walk and an exhausted walk isfalse, nevernull. It differs fromisFunctiononly there:isFunctionrefuses an exhausted walk by name. -
applicablePatternOf f— the pattern where the argument meets it:patternOf fwhereisFunction fholds (so a published__functionArgsis honoured), elsepatternOfof the reached head. Its domain isisApplicablevalues; an unapplicable value is refused bypatternOf's name, and an exhausted walk byisFunction's. -
applicableKindOf v— a refused value's kind as a door names it:"a functor that reaches no function within 32 `__functor` steps"where the walk exhausted the bound, else"a ${builtins.typeOf v}".
Behavior-identical copies of nixpkgs.lib helpers:
genAttrs names f— attrset with each name innamesmapped tof name.nameValuePair name value—{ inherit name value; }(pairs forlistToAttrs).optional cond x—[ x ]ifcondelse[ ].optionalAttrs cond attrs—attrsifcondelse{ }.optionalString cond s—sifcondelse"".last xs— final element (throws on[ ]).init xs— all but the final element (throws on[ ]).setAttrByPath path value— the nested attrset holdingvalueatpath;[ ]returnsvalueunchanged. Throwsgen-prelude.setAttrByPath: path must be a list of stringswhenpathis not one.getAttrByPath path attrs— the value atpath;[ ]returnsattrsunchanged. Throwsgen-prelude.getAttrByPath: attribute path '<dotted>' not foundon a missing key or a non-attrset encountered mid-path, naming the whole requested path rather than the segment that failed. nixpkgs spells this onegetAttrFromPathsince its rename; the older name is kept for symmetry with the writer. Both refusals are named and catchable, where nixpkgs' is an uncatchableabort— fidelity for this pair is asserted on the happy path only.unique xs— order-preserving deduplication under structural==, first occurrence kept. Total on every value: ints, lists, attrsets and functions all work. Internally a guarded two-path — a list of strings routes to a linear key→first-index table, anything else to the original quadratic fold, retained deliberately because Nix has no total injective pure value→string key. See Performance for what each path costs and where the trade lies.findFirst pred default list— the first element satisfyingpred, elsedefault(nixpkgslib.findFirst;foldl'-based, stack-safe, no early cutoff).filterAttrs pred attrs— attrset keeping entries wherepred name value.mapAttrsToList f attrs— list off name valueover the attrset.groupBy keyOf xs— attrset grouping each element ofxsunder the string keykeyOf x; each value is the list of elements sharing that key, in input order. Abuiltinsre-export, not a vendored copy: the primop is linear where an accumulating fold rebuilds each group at every step.concatMapStringsSep sep f xs—map f xsjoined bysep.concatMapStrings f xs—map f xsconcatenated (concatMapStringsSep "").hasPrefix pre s— whethersstarts withpre. A pathpreis refused (thrown), as in nixpkgs.hasSuffix suf s— whethersends withsuf. A pathsufis refused (thrown), as in nixpkgs.isStringLike x— whethertoStringcoercesx: a string, a path, or a set withoutPathor__toString(every derivation).imap0 f xs—mapwith a 0-based index:f index element.fix f— least fixed pointlet x = f x; in x.max a b— the larger of two comparables.range from to— inclusive integer range ([ ]whenfrom > to).removePrefix pre s—swith a leadingprestripped (unchanged if absent). A pathpreis refused (thrown), as in nixpkgs.removeSuffix suf s—swith a trailingsufstripped (unchanged if absent). A pathsufis refused (thrown), as in nixpkgs.splitString sep s—ssplit on the literalsep(regex metacharacters are escaped); a separator at either end yields an empty piece there, and every piece keepss's string context.reverseList xs—xsin reverse order.remove e xs—xswithout every element== e.recursiveUpdate lhs rhs—lhs // rhs, recursing where both sides hold an attrset at the same name; anywhere elserhswins.
Shared by every published gen door. Each takes the name of the door the caller invoked and
refuses, catchably, as <door>: … (in prelude.<construct>):
checkOptions door accepted opts— a closed options set; an unknown field is refused by name.checkRequired door required record— an open data record; a missing field is refused, an extra one admitted.checkGuarded door guardName guardedNames record— a record field that is one of a sibling options step's own names is refused by name.refusals— the text of every refusal above, as values: each construct throws exactlyrefusals.<name>of its own arguments (optionsNotASet,unknownOption,recordNotASet,missingField,guardedField,unknownReference,ambiguousDeclaration,unregisteredDeclaration,unlocatedDeclaration,notAReference). A consumer's test composes its expected message through them with its own literal door, field and accepted set, so it keeps every assertion and pins none of this library's wording.door { name; required ? [ ]; optional ? [ ]; open ? false; optionsStep ? null; next ? null; } body— the door constructor: a functor that publishes its field contract as data,__contractplus the derived__functionArgs(required ↦false, optional ↦true), and checks its argument at its own application —checkRequiredfor anopenrecord,checkOptions ∘ checkRequiredfor a closed one — beforebodyruns. A curried door is a chain of doors, one per record step. The spec record is itself checked atdoor spec: an unknown field, and a field both required and optional, are refused by name.nextpublishes the chain's later steps as data,__contract.next(OQ16 "nest"): the record step's spec, bound once and used both asnextand asdoor recordSpec. A positional step between two record steps is the node{ positional = "<operand>"; next = recordSpec; }. A door declaringnextrefuses, by name, a body whose result is not a door ofnext.name(or, behind a positional node, not a function).__functionArgsstill reads step 1 only.- A record step naming its
optionsStepis refused atdoor specunless that door'snextreaches exactly this step's contract: an undeclared chain and a same-name drift both refuse once per spec, never per application.
resolve { hint ? "name"; form ? "an attrset"; } { entries; isCanonical; } door ref— a reference written as an identifier (a string) or a declaration value, to its identifier. Options first, then the registry; both steps are doors. Thehintfield only locates candidates; the member'sisCanonical v kdecides, and nothing is minted.
toposort used to live here, vendored verbatim from nixpkgs lib/lists.nix along with its
internal listDfs and list-reverse helpers. It is gone. Ordering has one owner in the gen
ecosystem and it is gen-graph: use gen-graph.topoOrder,
which is Kahn 1962 over an accessor and returns { ok = true; order; } or
{ ok = false; cycles; } rather than { result } / { cycle; loops; }.
Two guarantees went with the copy and are not reproduced anywhere: byte-compatibility with
nixpkgs lib.toposort, and the polymorphism that let it order integers and attrset
records directly. gen-graph's accessor is string-keyed; non-string nodes reach it through an
explicit keyOf projection. sort — the primitive comparator sort — stays here.
Four helpers with no nixpkgs.lib counterpart, so they are covered by the
literal-expectation prelude suite rather than prelude-fidelity:
-
indexOf xs x— first position ofxinxs(structural==), or-1if absent. List-first arg order (xsthenx), built on the same stack-safe first-match scan asfindFirst. -
iterateBounded strict step init bound—stepapplied once per element ofbound, returning the state after the last application. The elements ofboundare ignored: only its length is read, as the bound on how many steps can be productive, so a caller passes a list it already holds and the loop allocates nothing of its own.The stack-safe encoding for a loop that carries state, as
findFirst's scan is for one that does not. A loop written as a self-applying lambda spends one evaluator frame per iteration — Nix does not reuse the frame of a tail call — so its descent depth is the iteration count and pastmax-call-depthit aborts with a stack overflowtryEvalcannot catch;foldl'is a C-level loop whose frame cost is constant in the iteration count. Iterating a fixed number of times where a recursion would run to its own fixed point is sound on two properties the caller owes: at mostlength boundsteps do work, andstepis the identity once no work remains, so the surplus steps idle.strictnames the loop-carried fields and is forced on every intermediate state.foldl'forces its accumulator only to WHNF — for a record, the record and not its fields — so a field left unforced accumulates a thunk chain as long as the loop, and forcing it at the end costs C stack: a second, distinct overflow that nomax-call-depthsetting bounds and thattryEvaldoes not contain either. Pass_: nullwhen there is nothing to force.# gen-graph's Kahn loop: the node-key list is the bound, and every accumulating field of # the state is what `strict` forces — `emitted` by its LENGTH, because forcing the spine # each step is what keeps its pending carries one deep rather than n. prelude.iterateBounded (st: builtins.seq st.base (builtins.seq st.residue ( builtins.seq st.width (builtins.seq st.ready ( builtins.seq st.count (builtins.length st.emitted)))))) step { base = indeg0; residue = { }; width = 0; ready = heapOfSources; emitted = [ ]; count = 0; } keys
-
absorb { fn; subject; at; } kept twins— the quotient rule: a collapse of data equal under==but differing in string context keeps the union of the twins' dependency edges. A stringkeptcarries it by its context. A non-stringkeptcannot, so a collapse that would lose an edge is refused, and so is any collapse holding a coercible set that is not a derivation and has attributes beside its coercion (an edge the walk cannot read). The refusal isthrow "${fn}: …"withfnthe caller's full door name, so it names the door the caller invoked. The caller owes thatkeptand the twins already passed its own walk. One home for every==-collapsing site (gen-view's dedup and set union, gen-scope'ssetandmergeAttrsDeep), cells inci/tests/absorb.nix. -
dedupByKey getKey list— first-occurrence-wins dedup bygetKey x, order-preserving. Anullkey is always kept and never deduplicated — the safe direction against silent cross-scope content-loss (a keyless element cannot be proven a duplicate, so a false-keep equal-merges harmlessly whereas a false-collapse silently drops distinct content). Vendored from den-hoaglib/dedup-by-key.nix.getKeymust return a string ornull: any other type is an interpreter type error at the attribute-name site, whichtryEvaldoes not catch.
nix develop ./ci --command ci # guarded
nix flake check ./ci # the gates too; unguardedci 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.
The ci/ directory is a separate flake (it pulls nixpkgs only to supply the lib
oracle the fidelity suite compares against — the lib itself pulls nothing). It runs
138 tests across 4 suites (nix-unit --flake ./ci#tests ⇒ 138/138 successful, 60dc6bf):
-
entry(1) — the standalone-leaf check: the rootdefault.nixis a nullary function whose{ }call forwards the flake's published surface, the uniform entry call across the roster regardless of whether a given library takes a dependency. -
prelude(56) — readable literal-expectation sanity checks (genAttrs,unique,filterAttrs,fix, thetoposortretirement + itssortcontrol, empty-list throw,groupBybasic + empty + collision-order stability, plus the gen-prelude-originalsdedupByKeyfirst-occurrence + null-keep + empty,indexOfpresent/absent/first,findFirstmatch/default, anditerateBoundedcount + ignored elements + empty bound + surplus-step idling + forced/unforced pair + stack safety at 20000 iterations + a guarded step carrying a fieldstrictdoes not name, at 100000). TheiterateBoundedarms that must FAIL — a self-applying loop at the same size, and that last loop with its guard deleted — are not here: a stack overflow is an uncatchable abort, so no in-language assertion observes it, and the red arms are shell commands.unique's two-path carries its own group: first-occurrence ORDER (including two traps that a construction sorting keys rather than indices fails); STRING CONTEXT (a context-carrying string is a legal element and an illegal attribute name, so this arm fails as an uncatchable abort rather than a wrong answer, and no other arm sees it); NON-STRING ROUTING over ints, lists, attrsets, a mixed list and a 24-element attrset list, each asserted element-for-element against the incumbent expression rather than merely "does not throw"; and STRICTNESS PARITY over 14 value classes viatryEval ∘ length, the only instrument that observes how much a construction forces — every arm comparing under==forces both sides and is structurally blind to it. The load-bearing case isunique [ (throw "BOOM") ]⇒ 1, not an abort.dedupByKeyadds null-keep at EQUAL content, order across a mixed keyed/unkeyed input, and stack safety at 50,000 elements. -
prelude-fidelity(72) — the load-bearing guard: for every nixpkgs-vendored utility,prelude.X input == lib.X inputover normal and boundary inputs (empty lists, absent prefixes, reversed ranges, cycles). This is what keeps the vendored copies byte-behavior-identical to nixpkgslib. (indexOfis additionally cross-checked againstlib.lists.findFirstIndex;dedupByKeyhas no nixpkgs oracle and lives only in thepreludesuite.groupByhas no arm here either — it is abuiltinsre-export, and nixpkgs' ownlib.groupByisbuiltins.groupBy or (…), so a fidelity arm over it would compare the primop with itself.)Eighteen of those arms are
escapeRegex's metacharacter set, which gets per-member coverage rather than a table of representative cases: which member is wrong decides which needle notices, so a sample cannot see it. Twelvetest-escset-*arms cover a member DROPPED (the needle stops being quoted and becomes a pattern — eight flip the boolean, four raise);test-escapeRegex-printable-asciicovers a member ADDED, by byte-identity againstlib.escapeRegexover all 95 printable ASCII characters. The remaining five hold]to being a NON-member from both sides — escaping it emits\], which the regex engine rejects, so the needle aborts where nixpkgs answers, andtryEvaldoes not catch it. -
purity(9) — purity as a CHECKED property rather than a structural argument. This suite used to be absent, and the reason given was that the lib flake declares no inputs, so there is nonixpkgs.libin scope to accidentally depend on. That argument is sound and it rests on a premise nothing asserted: aninputsattribute added to the rootflake.nixputsnixpkgsback in scope, and no test saw it.test-flake-declares-no-inputsis that premise, written down as the flake's own attribute names — this is the load-bearing cell, and the token scan overlib/**.nixplus the rootdefault.nixis the second line behind it.Four more cells are what make an empty violation list mean something. The detector is run over the same corpus with one synthetic tether appended and must produce exactly that violation;
builtins.readDir lib/is pinned so a file — or a subdirectory the flat read would not descend into — arrives as a red rather than as unscanned code; the labels are shown to carry this repository's live text rather than a constant (test-scan-reads-are-live); and the scan is run over the RAW text as well, where it must fire, because this library's own header truly states it is nixpkgs-lib-free and names thelib.types/mkOption/evalModulestier.The remaining three cells guard the comment-strip itself, which is what makes the green above a statement about code rather than about text already blinded: the strip's premise holds of what was actually read from disk (
test-strip-premise-holds); the premise predicate is shown capable of saying no, over a literal unseverable from the tree (test-strip-premise-scan-is-live); and multiline string blocks — which a line-local premise cannot see across — are declared rather than trusted in silence (test-strip-premise-multiline-strings). The scanner is this library's ownhasInfixscanning this library, so the detector cell is also what stands between ahasInfixbroken to always answer false and a clean-looking report.
Two functions here have costs worth knowing before you reach for them. Both are stated in
two variables, because one variable hides the answer: N is the list length and K the
distinct-element count, 1 ≤ K ≤ N.
unique is a guarded two-path. A list of strings builds a key→first-index table in one
pass and costs 2N + 3K + 3 list elements — linear in both variables. Anything else takes
the original fold, which costs K(K+1)/2 + K + N + 2: quadratic in K, not in N, because
acc ++ [ x ] copies the whole accumulator on each of the K first-sightings. The append is
the cost, not the membership test — which is why swapping in an O(1) attrset lookup while
keeping the append changes nothing.
That makes the trade explicit rather than uniform:
| shape | which path wins | measured |
|---|---|---|
| K ≈ N (all-distinct) | string path, by a lot | 8,010,002 → 20,003 elements at N = K = 4,000 |
| N ≈ 2K (an endpoint union over an edge list) | string path | 23.3× fewer at N = 640, 91.9× at N = 2,560, doubling with every doubling |
| K ≪ N (few distinct values, long list) | the fold | string path converges to exactly 2.00× more allocation, and time drifts as log N / K — measured +29.5% at N = 400,000, K = 8 |
The string path is chosen whenever it applies because the K ≪ N penalty is bounded at 2.00× while the K ≈ N saving is unbounded and grows with input size. If you are deduplicating a long list with very few distinct values and it is hot, that is the one case where this library is knowingly slower than it was, and the reason is in the table.
The non-string fold is not a leftover. There is no total, injective, pure value→string
key in Nix — builtins.toJSON is not one, since it aborts on functions and forces deeply —
so a non-string list has no index table to build at all, and the fold is what keeps unique
total on ints, lists, attrsets and functions. The guard is per-list, not per-element: a
mixed list routes whole to the fold.
dedupByKey is linear (5N + 3) and frame-flat. It previously used a non-tail [ x ] ++ go … rest recursion, which was quadratic in N whatever the distinct count and, worse, spent
one evaluator frame per element — so it aborted uncatchably past max-call-depth at around
10,000 elements. Every step is now a primop, so there is no descent left to overflow.
gen-prelude has no research lineage — it is plumbing, with one exception: iterateBounded
is an encoding decision rather than a copy, and its rationale is stated with it above.
The builtins members are direct
re-exports of the Nix builtins set. The vendored utilities are copied
behavior-identically from nixpkgs lib:
| Utility | nixpkgs source |
|---|---|
genAttrs, filterAttrs, mapAttrsToList, nameValuePair, optionalAttrs, recursiveUpdate |
lib/attrsets.nix |
optional, last, init, unique, imap0, range, findFirst, reverseList, remove |
lib/lists.nix |
optionalString, concatMapStringsSep, concatMapStrings, hasPrefix, hasSuffix, removePrefix, removeSuffix, splitString, isStringLike |
lib/strings.nix |
fix, max |
lib/trivial.nix / lib/fixed-points.nix |
The prelude-fidelity test suite asserts each utility stays
behavior-identical to its nixpkgs.lib original, so the vendoring cannot silently
drift.
Three members are gen-prelude-original (no nixpkgs origin), so they are held by the
literal-expectation prelude suite rather than prelude-fidelity:
| Utility | origin |
|---|---|
indexOf |
gen-prelude-original — small list helper (den-hoag hand-roll shape); shares the internal stack-safe findFirstIndex scan (lib/lists.nix:575) that also backs findFirst |
iterateBounded |
gen-prelude-original — the stack-safe loop encoding for state a scan cannot carry; nothing was vendored, so there is no fidelity oracle to hold it against |
dedupByKey |
vendored from den-hoag lib/dedup-by-key.nix (itself the port of v1 scope-walk dedupByKey); null-keep semantics have no nixpkgs.lib counterpart |
MIT — see LICENSE.