Skip to content

Commit 70f166a

Browse files
xperiandriclaude
andcommitted
refactor: split Helper.fs into root modules and declare InternalsVisibleTo in the project file (#40)
Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
1 parent dd5a275 commit 70f166a

9 files changed

Lines changed: 513 additions & 456 deletions

File tree

‎.github/copilot-instructions.md‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,13 @@ module's `.fsi` and the `.fs` on its `.fs`, so that Visual Studio shows them as
2323
│ └── CheckOrder.fs – checks the category order of the signature files with the Fantomas parser
2424
├── docsSrc/ – FSharp.Formatting documentation source
2525
├── src/FSharp.Collections.Immutable/ – main library
26-
│ ├── Helper.fs – argument checks and exceptions shared by the modules
26+
│ ├── Helper/ – internal helpers shared by the modules, one root module per file
27+
│ │ ├── ImmutableCollectionUtil.fs – argument checks and the wrapping of arrays
28+
│ │ ├── Comparers.fs – the default comparer of F# generic comparison
29+
│ │ ├── ErrorStrings.fs – the exception messages of FSharp.Core and the .NET libraries
30+
│ │ ├── Raise.fs – the exceptions of the FSharp.Core DetailedExceptions module
31+
│ │ ├── ArrayChecks.fs – the checks that the functions of several arrays share
32+
│ │ └── Arrays.fs – the algorithms over arrays that the default and Tuple modules share
2733
│ ├── FlatList/ – ImmutableArray API surface and builders
2834
│ │ ├── FlatListTypes.fs – the FlatList abbreviation
2935
│ │ ├── FlatList.fs / FlatList.fsi – includes the nested Parallel module

‎src/FSharp.Collections.Immutable/FSharp.Collections.Immutable.fsproj‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,20 @@
1818
<Tailcalls>true</Tailcalls>
1919
</PropertyGroup>
2020

21+
<ItemGroup>
22+
<!-- The tests call internal algorithms directly, where reaching a case through a public function would need arrays
23+
too large for memory (the bounds of the chunks of a parallel loop, for example) -->
24+
<InternalsVisibleTo Include="$(AssemblyBaseName).Tests" />
25+
</ItemGroup>
26+
2127
<ItemGroup>
2228
<Compile Include="AssemblyInfo.fs" />
23-
<Compile Include="Helper.fs" />
29+
<Compile Include="Helper\ImmutableCollectionUtil.fs" />
30+
<Compile Include="Helper\Comparers.fs" />
31+
<Compile Include="Helper\ErrorStrings.fs" />
32+
<Compile Include="Helper\Raise.fs" />
33+
<Compile Include="Helper\ArrayChecks.fs" />
34+
<Compile Include="Helper\Arrays.fs" />
2435
<Compile Include="FlatList\FlatListTypes.fs" />
2536
<Compile Include="FlatList\FlatList.fsi" />
2637
<Compile Include="FlatList\FlatList.fs" />

‎src/FSharp.Collections.Immutable/Helper.fs‎

Lines changed: 0 additions & 454 deletions
This file was deleted.
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
/// The checks of the FSharp.Core Array module that the functions of several arrays share.
2+
module internal FSharp.Collections.Immutable.ArrayChecks
3+
4+
/// The arrays of a function of two arrays must have the same length.
5+
let inline sameLengths (name1 : string) (array1 : 'T1 array) (name2 : string) (array2 : 'T2 array) =
6+
if array1.Length <> array2.Length then
7+
Raise.invalidArgDifferentArrayLength name1 array1.Length name2 array2.Length
8+
9+
/// The arrays of a function of three arrays must have the same length.
10+
let inline sameLengths3
11+
(name1 : string)
12+
(array1 : 'T1 array)
13+
(name2 : string)
14+
(array2 : 'T2 array)
15+
(name3 : string)
16+
(array3 : 'T3 array)
17+
=
18+
if
19+
array1.Length <> array2.Length
20+
|| array1.Length <> array3.Length
21+
then
22+
Raise.invalidArg3ArraysDifferent name1 name2 name3 array1.Length array2.Length array3.Length
Lines changed: 187 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,187 @@
1+
/// Algorithms over arrays that the default modules and the `Tuple` modules share (ADR 0001, D3).
2+
/// Each algorithm takes the constructor of the tuples that it produces, so that neither variant pays for a second pass.
3+
/// The callers check their arguments first, with the exceptions of the FSharp.Core module that they mirror.
4+
/// The algorithms exist because the functions of the FSharp.Core `Array` module that build or take pairs and triples work
5+
/// with reference tuples. The default functions of `FlatList` return struct tuples, and the functions of the `Tuple`
6+
/// namespace return reference tuples. Calling the `Array` function and converting its result would allocate every
7+
/// reference tuple and a second array. Each algorithm has exactly two callers, the function of `FlatList` with
8+
/// `structPair` or `structTriple` and the function of `Tuple.FlatList` with `referencePair` or `referenceTriple`, so
9+
/// that it exists once. For 10 000 elements, `zip` of struct tuples allocates 80 KB where `Array.zip` followed by a
10+
/// conversion allocates 400 KB.
11+
/// The first sentences of the comment of each function are the summary of the function of the FSharp.Core `Array` module
12+
/// word for word (FSharp.Core 10.1), and the sentences after them say what differs and why the function exists.
13+
module internal FSharp.Collections.Immutable.Arrays
14+
15+
open System
16+
open System.Collections.Generic
17+
open System.Linq
18+
19+
/// Returns a new array that contains all pairings of elements from the first and second arrays.
20+
/// The pairs are built with `tuple`. It exists because `Array.allPairs` returns reference tuples. `FlatList.allPairs`
21+
/// builds struct tuples with it directly (720 KB for 300 by 300 elements, where `Array.allPairs` followed by a conversion
22+
/// allocates 3.6 MB).
23+
let inline allPairs ([<InlineIfLambda>] tuple : 'T1 -> 'T2 -> 'R) (array1 : 'T1 array) (array2 : 'T2 array) : 'R array =
24+
let length2 = array2.Length
25+
let result = Array.zeroCreate (array1.Length * length2)
26+
27+
for i = 0 to array1.Length - 1 do
28+
for j = 0 to length2 - 1 do
29+
result[i * length2 + j] <- tuple array1[i] array2[j]
30+
31+
result
32+
33+
/// A key that may be null, for a dictionary, which rejects null keys. FSharp.Core has no such type in its public API.
34+
/// It exists because `Array.countBy` and `Array.groupBy` accept a null key (`[| null; "a"; null |]` has two keys), and
35+
/// `Dictionary` throws `ArgumentNullException` for one.
36+
[<Struct>]
37+
type NullableKey<'Key> = { Key : 'Key }
38+
39+
/// Compares wrapped keys in F# structural equality, which handles null keys, as FSharp.Core does for its keys.
40+
/// It exists because the default comparer of a `Dictionary` compares array keys by reference, where `Array.countBy`
41+
/// finds `[| 1 |]` and `[| 1 |]` equal.
42+
let nullableKeyComparer<'Key when 'Key : equality> () =
43+
let structural = HashIdentity.Structural<'Key>
44+
45+
{
46+
new IEqualityComparer<NullableKey<'Key>> with
47+
member _.Equals (left, right) = structural.Equals (left.Key, right.Key)
48+
member _.GetHashCode key = structural.GetHashCode key.Key
49+
}
50+
51+
/// Applies a key-generating function to each element of an array and returns an array yielding unique keys and their
52+
/// number of occurrences in the original array.
53+
/// The unique keys come in the order of their first occurrence, and the counting keeps one counter per key, not the
54+
/// elements, so it needs memory for the keys only. The tuples are built with `tuple`. It exists because `Array.countBy`
55+
/// returns reference tuples; null keys and keys that are arrays work as in FSharp.Core.
56+
let inline countBy
57+
([<InlineIfLambda>] tuple : 'Key -> int -> 'R)
58+
(projection : 'T -> 'Key)
59+
(array : 'T array)
60+
: 'R array when 'Key : equality =
61+
let indices = Dictionary<NullableKey<'Key>, int>(nullableKeyComparer<'Key>())
62+
let keys = ResizeArray<'Key>()
63+
let counts = ResizeArray<int>()
64+
65+
for item in array do
66+
let key = projection item
67+
let mutable index = 0
68+
69+
if indices.TryGetValue ({ Key = key }, &index) then
70+
counts[index] <- counts[index] + 1
71+
else
72+
indices.Add ({ Key = key }, keys.Count)
73+
keys.Add key
74+
counts.Add 1
75+
76+
let result = Array.zeroCreate keys.Count
77+
78+
for index = 0 to result.Length - 1 do
79+
result[index] <- tuple keys[index] counts[index]
80+
81+
result
82+
83+
/// Applies a key-generating function to each element of an array and yields an array of unique keys. Each unique key
84+
/// contains an array of all elements that match to this key.
85+
/// The keys come in the order of their first occurrence, and the elements of a key in their order. The tuples are built
86+
/// with `tuple`. It exists because `Array.groupBy` returns reference tuples. It groups once with a lookup, as the project
87+
/// rules ask.
88+
let inline groupBy
89+
([<InlineIfLambda>] tuple : 'Key -> 'T array -> 'R)
90+
(projection : 'T -> 'Key)
91+
(array : 'T array)
92+
: 'R array when 'Key : equality =
93+
let lookup = array.ToLookup ((fun item -> projection item), HashIdentity.Structural<'Key>)
94+
let result = Array.zeroCreate lookup.Count
95+
let mutable index = 0
96+
97+
for grouping in lookup do
98+
result[index] <- tuple grouping.Key (grouping.ToArray ())
99+
index <- index + 1
100+
101+
result
102+
103+
/// Builds a new array whose elements are the corresponding elements of the input array paired with the integer index
104+
/// (from 0) of each element.
105+
/// The pairs are built with `tuple`. It exists because `Array.indexed` returns reference tuples (320 KB for 10 000
106+
/// elements, where struct tuples take 80 KB).
107+
let inline indexed ([<InlineIfLambda>] tuple : int -> 'T -> 'R) (array : 'T array) : 'R array =
108+
let result = Array.zeroCreate array.Length
109+
110+
for i = 0 to result.Length - 1 do
111+
result[i] <- tuple i array[i]
112+
113+
result
114+
115+
/// Returns an array of each element in the input array paired with its predecessor, with the exception of the first
116+
/// element which is only returned as the predecessor of the second element. The predecessor comes first in the returned
117+
/// pairs.
118+
/// The pairs are built with `tuple`. It exists because `Array.pairwise` returns reference tuples.
119+
let inline pairwise ([<InlineIfLambda>] tuple : 'T -> 'T -> 'R) (array : 'T array) : 'R array =
120+
if array.Length < 2 then
121+
Array.Empty ()
122+
else
123+
let result = Array.zeroCreate (array.Length - 1)
124+
125+
for i = 0 to result.Length - 1 do
126+
result[i] <- tuple array[i] array[i + 1]
127+
128+
result
129+
130+
/// Splits an array of pairs into two arrays.
131+
/// `split` reads a pair as a struct tuple. It exists because `Array.unzip` takes reference tuples. `FlatList.unzip` has
132+
/// struct tuples and passes `id` as `split`, `Tuple.FlatList.unzip` has reference tuples and converts one pair at a time,
133+
/// so that no array of converted pairs (400 KB for 10 000 pairs) is built.
134+
let inline unzip ([<InlineIfLambda>] split : 'P -> struct ('T1 * 'T2)) (array : 'P array) =
135+
let result1 = Array.zeroCreate array.Length
136+
let result2 = Array.zeroCreate array.Length
137+
138+
for i = 0 to array.Length - 1 do
139+
let struct (first, second) = split array[i]
140+
result1[i] <- first
141+
result2[i] <- second
142+
143+
struct (result1, result2)
144+
145+
/// Splits an array of triples into three arrays.
146+
/// `split` reads a triple as a struct tuple. It exists for the reason of `unzip`: `Array.unzip3` takes reference tuples.
147+
let inline unzip3 ([<InlineIfLambda>] split : 'P -> struct ('T1 * 'T2 * 'T3)) (array : 'P array) =
148+
let result1 = Array.zeroCreate array.Length
149+
let result2 = Array.zeroCreate array.Length
150+
let result3 = Array.zeroCreate array.Length
151+
152+
for i = 0 to array.Length - 1 do
153+
let struct (first, second, third) = split array[i]
154+
result1[i] <- first
155+
result2[i] <- second
156+
result3[i] <- third
157+
158+
struct (result1, result2, result3)
159+
160+
/// Combines the two arrays into an array of pairs. The two arrays must have equal lengths, otherwise an ArgumentException
161+
/// is raised.
162+
/// The pairs are built with `tuple`, and the callers check the lengths first and raise the exception of `Array.zip`. It
163+
/// exists because `Array.zip` returns reference tuples (400 KB for 10 000 elements with the conversion, 80 KB here).
164+
let inline zip ([<InlineIfLambda>] tuple : 'T1 -> 'T2 -> 'R) (array1 : 'T1 array) (array2 : 'T2 array) : 'R array =
165+
let result = Array.zeroCreate array1.Length
166+
167+
for i = 0 to result.Length - 1 do
168+
result[i] <- tuple array1[i] array2[i]
169+
170+
result
171+
172+
/// Combines three arrays into an array of triples. The three arrays must have equal lengths, otherwise an
173+
/// ArgumentException is raised. (The summary of `Array.zip3` says "an array of pairs", which is a slip.)
174+
/// The triples are built with `tuple`, and the callers check the lengths first. It exists for the reason of `zip`:
175+
/// `Array.zip3` returns reference tuples.
176+
let inline zip3
177+
([<InlineIfLambda>] tuple : 'T1 -> 'T2 -> 'T3 -> 'R)
178+
(array1 : 'T1 array)
179+
(array2 : 'T2 array)
180+
(array3 : 'T3 array)
181+
: 'R array =
182+
let result = Array.zeroCreate array1.Length
183+
184+
for i = 0 to result.Length - 1 do
185+
result[i] <- tuple array1[i] array2[i] array3[i]
186+
187+
result
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/// The default comparers of the collections (ADR 0001, D5).
2+
[<AutoOpen>]
3+
module internal FSharp.Collections.Immutable.Comparers
4+
5+
open System.Collections.Generic
6+
7+
/// <summary>
8+
/// The comparer of F# generic comparison for a type: the comparer of the sorts, of <c>binarySearch</c> and of the
9+
/// sorted collections that are created without a comparer.
10+
/// </summary>
11+
/// <remarks>
12+
/// <para>
13+
/// The class resolves <see cref="M:Microsoft.FSharp.Core.LanguagePrimitives.FastGenericComparer``1"/> once per type, in
14+
/// generic code, where FSharp.Core returns the comparer that it keeps for the type.
15+
/// </para>
16+
/// <para>
17+
/// A call of <c>FastGenericComparer</c> at a concrete type that is not primitive creates a new comparer each time, and
18+
/// the F# optimizer creates such calls when it inlines a small function of the library into its caller. Collections of
19+
/// one type would then have different comparers, and the BCL could not take its shortcuts for two collections with the
20+
/// same comparer, such as the one of <c>ImmutableSortedSet.Union</c>. A static field cannot be inlined.
21+
/// </para>
22+
/// </remarks>
23+
[<Sealed>]
24+
type DefaultComparer<'T when 'T : comparison> private () =
25+
26+
static let comparer = LanguagePrimitives.FastGenericComparer<'T>
27+
28+
/// The comparer of F# generic comparison for the type.
29+
static member Instance : IComparer<'T> = comparer
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
/// <summary>
2+
/// The exception messages of FSharp.Core (<c>FSCore.resx</c>) and of the .NET libraries, in English.
3+
/// </summary>
4+
/// <remarks>
5+
/// The modules throw what the FSharp.Core function that they mirror throws (ADR 0001, D6). FSharp.Core keeps its resources
6+
/// internal, so the texts are copied. The texts of the .NET libraries are for the functions that report a BCL exception
7+
/// under the name of their own parameter. Each constant is the text of one resource and its comment names the resource,
8+
/// so a text that no resource of FSharp.Core or of the .NET libraries holds does not belong here.
9+
/// </remarks>
10+
module internal FSharp.Collections.Immutable.ErrorStrings
11+
12+
/// FSCore.resx, arraysHadDifferentLengths.
13+
[<Literal>]
14+
let ArraysHadDifferentLengths = "The arrays have different lengths."
15+
16+
/// FSCore.resx, indexOutOfBounds.
17+
[<Literal>]
18+
let IndexOutOfBounds = "The index was outside the range of elements in the list."
19+
20+
/// FSCore.resx, arrayWasEmpty.
21+
[<Literal>]
22+
let InputArrayEmpty = "The input array was empty."
23+
24+
/// FSCore.resx, inputListWasEmpty.
25+
[<Literal>]
26+
let InputListWasEmpty = "The input list was empty."
27+
28+
/// FSCore.resx, inputMustBeNonNegative.
29+
[<Literal>]
30+
let InputMustBeNonNegative = "The input must be non-negative."
31+
32+
/// FSCore.resx, inputMustBePositive.
33+
[<Literal>]
34+
let InputMustBePositive = "The input must be positive."
35+
36+
/// FSCore.resx, inputSequenceEmpty.
37+
[<Literal>]
38+
let InputSequenceEmpty = "The input sequence was empty."
39+
40+
/// FSCore.resx, inputSequenceTooLong.
41+
[<Literal>]
42+
let InputSequenceTooLong = "The input sequence contains more than one element."
43+
44+
/// FSCore.resx, keyNotFound.
45+
[<Literal>]
46+
let KeyNotFound = "The item, key, or index was not found in the collection."
47+
48+
/// FSCore.resx, keyNotFoundAlt.
49+
[<Literal>]
50+
let KeyNotFoundAlt = "An index satisfying the predicate was not found in the collection."
51+
52+
/// FSCore.resx, listsHadDifferentLengths.
53+
[<Literal>]
54+
let ListsHadDifferentLengths = "The lists had different lengths."
55+
56+
/// System.Private.CoreLib, ArgumentOutOfRange_NeedNonNegNum: the message of the .NET libraries for a negative argument, as
57+
/// `Array.BinarySearch` reports it.
58+
[<Literal>]
59+
let NeedNonNegativeNumber = "Non-negative number required."
60+
61+
/// FSCore.resx, notAPermutation.
62+
[<Literal>]
63+
let NotAPermutation = "The function did not compute a permutation."
64+
65+
/// FSCore.resx, notEnoughElements.
66+
[<Literal>]
67+
let NotEnoughElements = "The input sequence has an insufficient number of elements."
68+
69+
/// FSCore.resx, outOfRange.
70+
[<Literal>]
71+
let OutOfRange = "The index is outside the legal range."

0 commit comments

Comments
 (0)