Skip to content

Commit e72f4c1

Browse files
xperiandriclaude
andcommitted
docs: state exceptions, comparers and range costs exactly in ADR 0001
- D6: each function throws what the FSharp.Core function of the mirrored module throws (`Array` for `FlatList`, `List` for the sequence-like modules, `Map`, `Set`), with a measured table: `take 0` is valid, `skip -1` and `truncate -1` count as 0, `item` throws `IndexOutOfRangeException` for `Array` and `ArgumentException` for `List`, and so on. `ParamName` and the extras are the deliberate deviations. - D8: the contract tests take the expected exception from that same FSharp.Core function on the same input. - D5: a transformation keeps each comparer whose type does not change; `map` and `choose` give the result the default comparer of the new type. The defaults are `EqualityComparer<'T>.Default` for hash-based collections and F# generic comparison for sorted ones. - D5: `ImmutableList.GetRange` builds a new tree; its cost grows with the length of the range (48 B per element), not with log n. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 75c0c24 commit e72f4c1

1 file changed

Lines changed: 61 additions & 26 deletions

File tree

‎docsSrc/Explanations/ADR_0001_Collection_Modules.md‎

Lines changed: 61 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -56,9 +56,10 @@ semantics, whose module mirrors `FlatList`.
5656
Curated extras kept beyond FSharp.Core: `indexOf`/`indexOfWith`/`lastIndexOf`/`lastIndexOfWith`, `binarySearch`,
5757
`sortWithComparer`, `isDefault`/`isDefaultOrEmpty`, `asSpan`/`asMemory`/`ofSpan`/`ofReadOnlySpan`, the builder family
5858
(`builder`, `builderWith`, `ofBuilder`, `toBuilder`, `moveFromBuilder`, `build`, `update`), `blit`, `add`,
59-
`cons`/`uncons`/`tryUncons`, the struct partial patterns `(|Cons|_|)`/`(|Nil|_|)`, `tryTail`, `enqueue`/`enqueueMany`, `consMany`, `takeLast`/`skipLast`, `clear`
60-
on interface modules, `tryGetKey`/`tryGetValue`, `setItem`/`setItems`/`addRange`/`removeRange`, `containsValue`,
61-
`symmetricDifference`, `overlaps`/`setEquals`, comparer accessors and `with*Comparer` functions.
59+
`cons`/`uncons`/`tryUncons`, the struct partial patterns `(|Cons|_|)`/`(|Nil|_|)`, `tryTail`, `enqueue`/`enqueueMany`,
60+
`consMany`, `takeLast`/`skipLast`, `clear` on interface modules, `tryGetKey`/`tryGetValue`,
61+
`setItem`/`setItems`/`addRange`/`removeRange`, `containsValue`, `symmetricDifference`, `overlaps`/`setEquals`, comparer
62+
accessors and `with*Comparer` functions.
6263

6364
Removed from the started branch: `iter3`/`iteri3`/`exists3`/`forall3`/`mapi3`/`foldBack3`, `foldi`/`foldi2`/`foldBacki`/
6465
`foldBacki2`, `findDup`/`findDupBy`, `pickBack`/`tryPickBack`/`chooseBack`, the `From`/`Range` variants of `index*`/
@@ -157,21 +158,52 @@ Consequences for the types: `FlatList` range operations (`take`, `skip`, `trunca
157158
`chunkBySize`, `windowed`) copy the selected elements. An `ImmutableArray` is a single array reference without an offset or a
158159
length, so `Slice` allocates and copies unless the range is empty (`Empty` is returned) or covers the whole input (the input
159160
itself is returned); zero-copy views of a range are available through `asSpan`/`asMemory` and the span's own `Slice`.
160-
`IndexedList` ranges use `GetRange` (O(log n)). `Stack` reverses only in its constructors: the BCL `ImmutableStack.Create`
161-
and `CreateRange` push in order and leave the last element on top, so `ofSeq`, `ofArray`, `ofList`, `ofReadOnlySpan` and
162-
`ofSpan` push from the end instead (`ofSeq [1; 2; 3]` has `1` on top), and every transformation snapshots top-to-bottom,
163-
applies `Array.*` and rebuilds the same way. `Queue.length`/`Stack.length` are O(n) and say so; map and set transformations preserve the comparers of the
164-
input (`CreateRange(keyComparer, valueComparer, …)`, `CreateBuilder(keyComparer)`); interface modules preserve the caller's
165-
implementation through `Clear()` plus `AddRange`/`Enqueue`/`Push`; `FrozenMap.keys`/`values` and `FrozenSet.toFlatList`
166-
return the underlying `ImmutableArray` in O(1).
161+
`IndexedList` ranges use `GetRange`, which builds a new tree from the selected elements: its work and allocation grow with
162+
the length of the range (48 B per element in a measurement), not with log n. `Stack` reverses only in its constructors:
163+
the BCL `ImmutableStack.Create` and `CreateRange` push in order and leave the last element on top, so `ofSeq`, `ofArray`,
164+
`ofList`, `ofReadOnlySpan` and `ofSpan` push from the end instead (`ofSeq [1; 2; 3]` has `1` on top), and every
165+
transformation snapshots top-to-bottom, applies `Array.*` and rebuilds the same way. `Queue.length`/`Stack.length` are O(n) and say so. Interface modules keep the
166+
caller's implementation in same-type transformations through `Clear()` plus `AddRange`/`Enqueue`/`Push`.
167+
`FrozenMap.keys`/`values` and `FrozenSet.toFlatList` return the underlying `ImmutableArray` in O(1).
168+
169+
**Comparers.** A transformation keeps each comparer whose type does not change. The key comparer of a map is always kept,
170+
because the keys keep their type (`CreateRange(keyComparer, …)`, `CreateBuilder(keyComparer)`). The value comparer of a map
171+
and the element comparer of a set are kept by `filter`, `partition` and set algebra. `map` and `choose` change the value or
172+
element type, so their result gets the default comparer of the new type. The interface modules cannot read the comparers
173+
of their input, so their type-changing transformations return concrete collections with default comparers. The defaults,
174+
which creation functions without a comparer argument also use, are `EqualityComparer<'T>.Default` for hash-based
175+
collections, as ADR 0002 uses for equality, and the order of F# generic comparison
176+
(`LanguagePrimitives.FastGenericComparer<'T>`) for sorted collections. Thus `SortedSet<string>` is ordinal by default, as
177+
F# `Set<string>` is.
167178

168179
### D6. Exceptions mirror FSharp.Core
169180

170-
Exception types and message texts follow FSharp.Core (`FSCore.resx`): `ArgumentException` for an empty input to `head`,
171-
`tail`, `reduce`, `exactlyOne`, `average`, `min`, `max`, `randomChoice*`, for non-positive counts, length mismatches
172-
(`zip`, `map2`, …), out-of-range indices and invalid permutations; `InvalidOperationException` when `take`, `takeLast` or
173-
`randomSample` find too few elements; `KeyNotFoundException` for `find*`, `findIndex*` and `pick`; `ArgumentNullException`
174-
for a null input and for a default `FlatList` (the array-null analogue; the BCL itself throws on a default array).
181+
Each function validates its arguments as the FSharp.Core function of the mirrored module does for the same input, and
182+
throws the same exception type with the same message. The mirrored module is `Array` for `FlatList`, `Array.Parallel` for
183+
`FlatList.Parallel`, `List` for `IndexedList`, `Queue`, `Stack` and their interface modules, `Map` for the map modules and
184+
`Set` for the set modules. The rules differ per operation and per module (FSharp.Core 10, measured):
185+
186+
| Input | `Array` | `List` |
187+
|---|---|---|
188+
| `take 0`, `init 0`, `replicate 0` | valid | valid |
189+
| `take -1`, `init -1`, `replicate -1` | `ArgumentException` | `ArgumentException` |
190+
| `skip -1`, `truncate -1` | valid, as 0 | valid, as 0 |
191+
| `take` or `splitAt` beyond the length | `InvalidOperationException` | `InvalidOperationException` |
192+
| `skip` beyond the length | `ArgumentOutOfRangeException` | `ArgumentOutOfRangeException` |
193+
| `item` out of range | `IndexOutOfRangeException` | `ArgumentException` |
194+
| `insertAt`, `removeAt` out of range | `ArgumentException` | `ArgumentException` |
195+
| `randomSample` beyond the length | `ArgumentException` | `ArgumentException` |
196+
| `chunkBySize 0`, `windowed 0`, `splitInto 0` | `ArgumentException` | `ArgumentException` |
197+
| empty input to `head`, `reduce`, `exactlyOne`, `average`, `min`, `max` | `ArgumentException` | `ArgumentException` |
198+
| no match in `find*`, `findIndex*`, `pick` | `KeyNotFoundException` | `KeyNotFoundException` |
199+
200+
A `null` input, and a default `FlatList`, throw `ArgumentNullException`, as a `null` array does in `Array`. Deliberate
201+
deviations, each documented on the function:
202+
203+
- `ParamName` is the name of the parameter in this library's signature, such as `list`, `queue` or `map`. FSharp.Core uses
204+
`array`, `list`, `source` or `s`.
205+
- The extras of D1 have no FSharp.Core counterpart. `takeLast` and `skipLast` follow `take` and `skip`; the others throw
206+
what the BCL member that they wrap throws.
175207

176208
### D7. Computation expressions
177209

@@ -192,21 +224,23 @@ which sorts unstably, see D5); `Map`, `MapTransform`, `MapMutation`, `MapCreatio
192224
`SetCreation`. Expectations are computed with FSharp.Core `List` over the collection's
193225
observed enumeration order, so one test body serves FIFO, LIFO and indexed collections. Collection-specific behaviour
194226
(`isDefault`, spans, builders, `Stack.cons` direction, comparers, sorted-only functions, null inputs) lives in a per-collection
195-
file. Exceptions are asserted with `Assert.ThrowsExactly` on type, `ParamName` and message prefix; every assertion carries
196-
a message; categories come from `TestCategories.fs` attributes (collection level) and `TestCategory (nameof …)`
197-
(operation level), never from string literals. In a contract base, the function of any module gives the name, for
198-
example `nameof FlatList.map`. Dedicated files per collection prove that opening the `Option`/`Tuple` namespaces shadows the default
199-
functions and that the override functions are equivalent to the defaults after conversion.
227+
file. Expected exceptions come from the same oracle: the test calls the function of the mirrored FSharp.Core module (D6)
228+
on the same input and asserts the same type and message with `Assert.ThrowsExactly`; `ParamName` is checked against the
229+
ops record. Every assertion carries a message; categories come from `TestCategories.fs` attributes (collection level) and
230+
`TestCategory (nameof …)` (operation level), never from string literals. In a contract base, the function of any module
231+
gives the name, for example `nameof FlatList.map`. Dedicated files per collection prove that opening the `Option`/`Tuple`
232+
namespaces shadows the default functions and that the override functions are equivalent to the defaults after conversion.
200233

201234
### D9. Delivery: one pull request per collection, stacked
202235

203236
`chore/foundation` (helper module, order check script, test categories and contract bases, changelog and documentation
204237
skeleton, target frameworks), then `feat/flat-list`, `feat/flat-list-parallel` (the nested `Parallel` module of D11),
205238
`feat/equatable-array` (step 2 of ADR 0002: the mirror of the `FlatList` module, its builder functions and
206-
`equatableArray { }`), `feat/indexed-list`, `feat/queue`, `feat/stack`, `feat/hash-map` (with `IMap`), `feat/sorted-map`, `feat/hash-set` (with
207-
`ISet`), `feat/sorted-set`, `feat/frozen-map`, `feat/frozen-set` (both with the alternate lookup of D11), and an optional
208-
`chore/benchmarks` (BenchmarkDotNet, excluded from the solution filter). Each pull request deletes the legacy file
209-
it replaces, keeps the build green and updates the changelog and the documentation table. No release is cut mid-chain.
239+
`equatableArray { }`), `feat/indexed-list`, `feat/queue`, `feat/stack`, `feat/hash-map` (with `IMap`), `feat/sorted-map`,
240+
`feat/hash-set` (with `ISet`), `feat/sorted-set`, `feat/frozen-map`, `feat/frozen-set` (both with the alternate lookup of
241+
D11), and an optional `chore/benchmarks` (BenchmarkDotNet, excluded from the solution filter). Each pull request deletes
242+
the legacy file it replaces, keeps the build green and updates the changelog and the documentation table. No release is
243+
cut mid-chain.
210244
Step 1 of ADR 0002 (the `EquatableArray` type, its patterns and JSON converter) MAY ship from `main` before the chain.
211245

212246
### D10. Target frameworks
@@ -251,8 +285,9 @@ not byref-like, such as an `int` alternate for `int64` keys with a custom compar
251285
Breaking changes (major version): `try*` return `voption`; tuples become struct tuples; `choose`/`pick`/`tryPick`/`unfold`/
252286
`change` callbacks use `voption`; `ImmutableList` module becomes `IndexedList`; `Seq`, `IndexedSeq`/`ReadOnlyList`, the
253287
`ISet<'T>` abbreviation and the extras listed in D1 are removed; map and set `length` becomes `count`; map `filter`/`map`
254-
follow FSharp.Core semantics; `Stack` element order is defined (first element of `ofSeq` on top); `take`/`skip` throw on
255-
short input; `netstandard2.0` is not a target. The `Option` and `Tuple` namespaces give consumers a one-line migration path.
288+
follow FSharp.Core semantics; sorted maps and sets order by F# generic comparison unless a comparer is given; `Stack`
289+
element order is defined (first element of `ofSeq` on top); `take`/`skip` throw on short input; `netstandard2.0` is not a
290+
target. The `Option` and `Tuple` namespaces give consumers a one-line migration path.
256291

257292
Benefits: one vocabulary across ten modules, consistent with FSharp.Core 10.0.300; defects of the current map and set modules
258293
fixed by construction (comparer preservation, real `singleton`); fewer allocations (`voption`, struct tuples, span and memory views, zero-copy

0 commit comments

Comments
 (0)