diff --git a/CHANGELOG.md b/CHANGELOG.md index 22b3dfaa..e80a4eca 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,7 +25,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 `sortRangeWith`, `sortRangeWithComparer`, `sortWith`, `sortWithComparer`, `toArray` and `updateAt`. The functions that change the builder return it. `replace` and `replaceWith` leave the builder as it is when no element equals the old value, as `ImmutableArray<'T>.Builder.Replace` does, where `FlatList.replace` throws `ArgumentException`. -* `flatList { }` builds a flat list. +* `flatList { }` builds a flat list. A `for` loop in it reads a flat list or an array without boxing it. The compiler + chooses the overload of `for` by the type of the source, so the type of the source must be known where the loop is + written, as for `yield!`: a function parameter without a type annotation needs one. Its `yield!` and `for` take spans + and memories too. * `FlatList.Parallel` has every function of the FSharp.Core `Array.Parallel` module except the in-place sorts, with its semantics and exceptions. Its `tryFind`, `tryFindIndex` and `tryPick` return `voption`, `choose` and `tryPick` take functions that return `voption`, and `groupBy`, `partition`, `partitionWith` and `zip` return struct tuples; the diff --git a/docsSrc/How_Tos/Use_A_Flat_List_With_Sequences.md b/docsSrc/How_Tos/Use_A_Flat_List_With_Sequences.md new file mode 100644 index 00000000..03aad19b --- /dev/null +++ b/docsSrc/How_Tos/Use_A_Flat_List_With_Sequences.md @@ -0,0 +1,92 @@ +--- +title: How To use a flat list with sequences +category: How To Guides +categoryindex: 2 +index: 3 +--- + +# How To use a flat list with sequences + +A `FlatList<'T>` is an `ImmutableArray<'T>`, which is a struct. A function that takes a `seq<'T>` boxes it: the call +allocates one object of 24 bytes on a 64-bit runtime, whatever the length of the flat list, and copies no element. The +boxed flat list implements `IReadOnlyList<'T>`, so `Seq.length`, `Seq.last` and `Seq.toArray` do not enumerate it. + +The box is rarely the problem. What matters is how a pipeline reads the elements. + +## When every element is read + +The functions of `FlatList` work on the array under the flat list. They box nothing and create no enumerator: + +``` F# +open FSharp.Collections.Immutable + +let numbers = FlatList.init 10_000 id + +let total = numbers |> FlatList.map (fun number -> number + 1) |> FlatList.sum +``` + +Each step builds a flat list. That is the cheapest way to read all the elements, and the wrong one when a step can stop +early. + +## When a pipeline stops early + +The functions of `Seq` are lazy: a pipeline that needs a few elements reads only those. The flat list is boxed once: + +``` F# +let firstFive = + numbers + |> Seq.filter (fun number -> number % 2 = 0) + |> Seq.map (fun number -> number + 1) + |> Seq.truncate 5 + |> FlatList.ofSeq +``` + +With `FlatList.filter` and `FlatList.map`, the same pipeline builds two flat lists of 5 000 elements first. + +## With the methods of LINQ + +`System.Linq` has extension methods for `ImmutableArray<'T>`. F# binds a call on a flat list to them, and they read the +array directly: + +``` F# +open System.Linq + +let firstFiveWithLinq = + numbers.Where(fun number -> number % 2 = 0).Select(fun number -> number + 1) + |> Seq.truncate 5 + |> FlatList.ofSeq + +let hasNegative = numbers.Any (fun number -> number < 0) +``` + +Only the first call of a chain reads the flat list. The rest work on the iterator that it returns, which is a class. + +`Where`, `Select`, `Any`, `All`, `Aggregate` and `ToArray` have a version for `ImmutableArray<'T>`. The other methods, +such as `Sum`, `Count`, `Take` and `OrderBy`, are the methods of `System.Linq.Enumerable`: called on a flat list, they +box it and read it through an enumerator object. `Seq.sum` does the same, so `FlatList.sum` reads a flat list faster +than both. + +## Where a sequence is taken + +A function of `FlatList` that takes a sequence recognises a flat list: `FlatList.ofSeq` returns it as it is. In +`flatList { }`, `yield!` and `for` take a sequence, an array, a flat list, a memory or a span. They read an array, a flat +list or a memory directly, without a box, and they copy the elements of a span first: + +``` F# +let combined = flatList { + yield! numbers + + for number in FlatList.ofArray [| 1; 2; 3 |] do + yield number * 10 + + yield! seq { 100..102 } +} +``` + +The compiler chooses the overload of `for` by the type of the source, which must be known where the loop is written. A +function parameter without a type annotation does not compile as the source of a loop, as it does not for `yield!`. +Annotate it: + +``` F# +let doubled (items : FlatList) = flatList { for item in items do yield item * 2 } +``` diff --git a/src/FSharp.Collections.Immutable/FlatList/FlatList.fsi b/src/FSharp.Collections.Immutable/FlatList/FlatList.fsi index 766f3a22..22cfd256 100644 --- a/src/FSharp.Collections.Immutable/FlatList/FlatList.fsi +++ b/src/FSharp.Collections.Immutable/FlatList/FlatList.fsi @@ -2047,7 +2047,14 @@ val toList : array : FlatList<'T> -> 'T list /// Returns the flat list as a sequence. /// The input flat list. /// The sequence of the elements. -/// O(1). +/// +/// O(1). A flat list is a struct, so the conversion boxes it: each call allocates one object of 24 bytes on a 64-bit +/// runtime, whatever the length of the flat list. The sequence implements +/// , +/// and , so that the functions of +/// and of that look for +/// these interfaces take the length, the last element or a copy of the elements without an enumerator. +/// [] val toSeq : array : FlatList<'T> -> seq<'T> diff --git a/src/FSharp.Collections.Immutable/FlatList/FlatListCE.fs b/src/FSharp.Collections.Immutable/FlatList/FlatListCE.fs index 8834ade9..d1838c2a 100644 --- a/src/FSharp.Collections.Immutable/FlatList/FlatListCE.fs +++ b/src/FSharp.Collections.Immutable/FlatList/FlatListCE.fs @@ -3,8 +3,12 @@ namespace FSharp.Collections.Immutable open System open System.Collections.Immutable +[] type FlatListBuffer<'T> = FlatList<'T>.Builder -> unit +// The members of the expression are the compiled F# code that the message of the abbreviation is about +#nowarn 1204 + [] type FlatListCE () = @@ -13,7 +17,7 @@ type FlatListCE () = member inline _.Yield (item : 'T) : FlatListBuffer<'T> = fun builder -> builder.Add item member inline _.YieldFrom (items : seq<'T>) : FlatListBuffer<'T> = - // A default flat list given as a sequence is still a default flat list, as in FlatList.ofSeq (ADR 0001, D6) + // A default flat list given as a sequence is still a default flat list, as in FlatList.ofSeq checkNotNullOrDefaultSeq (nameof items) items fun builder -> builder.AddRange items @@ -21,10 +25,24 @@ type FlatListCE () = member inline _.YieldFrom (items : FlatList<'T>) : FlatListBuffer<'T> = // The builder would dereference the missing array of a default flat list; the expression rejects it as the - // functions of FlatList do (ADR 0001, D6) + // functions of FlatList do checkNotDefault (nameof items) items fun builder -> builder.AddRange items + // A function cannot keep a span, so the elements of the span are copied before the function is made + member inline _.YieldFrom (items : ReadOnlySpan<'T>) : FlatListBuffer<'T> = + let items = items.ToArray () + fun builder -> builder.AddRange items + + member inline this.YieldFrom (items : Span<'T>) : FlatListBuffer<'T> = + this.YieldFrom (Span<'T>.op_Implicit items : ReadOnlySpan<'T>) + + member inline _.YieldFrom (items : ReadOnlyMemory<'T>) : FlatListBuffer<'T> = fun builder -> builder.AddRange items.Span + + member inline this.YieldFrom (items : Memory<'T>) : FlatListBuffer<'T> = + this.YieldFrom (Memory<'T>.op_Implicit items : ReadOnlyMemory<'T>) + + // The body of another expression is a function of the builder, so it adds to what the expression has already member inline _.YieldFrom (buffer : FlatListBuffer<'T>) : FlatListBuffer<'T> = buffer member inline _.Combine (first : FlatListBuffer<'T>, second : FlatListBuffer<'T>) : FlatListBuffer<'T> = @@ -43,6 +61,43 @@ type FlatListCE () = for item in source do body item builder + member inline _.For (source : 'U array, [] body : 'U -> FlatListBuffer<'T>) : FlatListBuffer<'T> = + // The check is in the function that the member returns: a statement before that function costs one more closure + // for each loop, so that a loop inside a loop allocates for each inner loop + fun builder -> + checkNotNull (nameof source) source + + for item in source do + body item builder + + member inline _.For (source : FlatList<'U>, [] body : 'U -> FlatListBuffer<'T>) : FlatListBuffer<'T> = + // The overload for sequences would box the flat list and read it through an enumerator object. The check is in the + // returned function for the reason given at the overload for arrays + fun builder -> + for item in unwrapArray (nameof source) source do + body item builder + + // A function cannot keep a span, so the loop reads a copy of its items + member inline _.For (source : ReadOnlySpan<'U>, [] body : 'U -> FlatListBuffer<'T>) : FlatListBuffer<'T> = + let items = source.ToArray () + + fun builder -> + for item in items do + body item builder + + member inline this.For (source : Span<'U>, [] body : 'U -> FlatListBuffer<'T>) : FlatListBuffer<'T> = + this.For ((Span<'U>.op_Implicit source : ReadOnlySpan<'U>), body) + + member inline _.For (source : ReadOnlyMemory<'U>, [] body : 'U -> FlatListBuffer<'T>) : FlatListBuffer<'T> = + fun builder -> + let span = source.Span + + for index = 0 to span.Length - 1 do + body span[index] builder + + member inline this.For (source : Memory<'U>, [] body : 'U -> FlatListBuffer<'T>) : FlatListBuffer<'T> = + this.For ((Memory<'U>.op_Implicit source : ReadOnlyMemory<'U>), body) + member inline _.While ([] guard : unit -> bool, body : FlatListBuffer<'T>) : FlatListBuffer<'T> = fun builder -> while guard () do @@ -74,3 +129,5 @@ type FlatListCE () = let builder = ImmutableArray.CreateBuilder<'T>() buffer builder builder.DrainToImmutable () + +#warnon 1204 diff --git a/src/FSharp.Collections.Immutable/FlatList/FlatListCE.fsi b/src/FSharp.Collections.Immutable/FlatList/FlatListCE.fsi index 33c851fa..042a7dac 100644 --- a/src/FSharp.Collections.Immutable/FlatList/FlatListCE.fsi +++ b/src/FSharp.Collections.Immutable/FlatList/FlatListCE.fsi @@ -5,14 +5,31 @@ open System /// /// The body of a flatList { } expression: a function that adds the elements to a builder. /// +/// +/// The type is public because the inline members of the expression use it. It is hidden from completion, and its use in +/// other code is a warning, as it is for the types that FSharp.Core keeps for the same purpose. +/// +[] type FlatListBuffer<'T> = FlatList<'T>.Builder -> unit -/// -/// The builder of the flatList { } computation expression. -/// +// The members of the expression are the compiled F# code that the message of the abbreviation is about +#nowarn 1204 + +/// The builder of the flatList { } computation expression. /// +/// /// The expression collects its elements in an and -/// returns them without a copy when the builder is full (ADR 0001, D7). +/// returns them without a copy when the builder is full. A loop reads a flat list, an array or a +/// memory directly, without boxing it, a span from a copy of its items, and any other source as a sequence. The compiler +/// chooses the overload of by the type of the source, which must be known where the loop is written, +/// as for : the source of a loop in a function needs a type annotation when its parameter has none. +/// +/// +/// The compiler makes a function of what follows an element, and a function cannot keep a span. So a span in +/// or has to be created and used before the next element that the expression +/// adds, such as yield! array.AsSpan (1, 2): a span that comes from outside the expression, or that is read after +/// the next element, does not compile. A memory has no such limit. +/// /// [] type FlatListCE = @@ -38,6 +55,18 @@ type FlatListCE = /// Thrown when the flat list is a default flat list. member inline YieldFrom : items : FlatList<'T> -> FlatListBuffer<'T> + /// Adds the elements of a span. + member inline YieldFrom : items : ReadOnlySpan<'T> -> FlatListBuffer<'T> + + /// Adds the elements of a span. + member inline YieldFrom : items : Span<'T> -> FlatListBuffer<'T> + + /// Adds the elements of a memory. + member inline YieldFrom : items : ReadOnlyMemory<'T> -> FlatListBuffer<'T> + + /// Adds the elements of a memory. + member inline YieldFrom : items : Memory<'T> -> FlatListBuffer<'T> + /// Adds the elements of another expression body. member inline YieldFrom : buffer : FlatListBuffer<'T> -> FlatListBuffer<'T> @@ -53,6 +82,28 @@ type FlatListCE = /// Thrown when the sequence is or a default flat list. member inline For : source : seq<'U> * [] body : ('U -> FlatListBuffer<'T>) -> FlatListBuffer<'T> + /// Adds the elements of the body for each item of an array. + /// Thrown when the array is . + member inline For : source : 'U array * [] body : ('U -> FlatListBuffer<'T>) -> FlatListBuffer<'T> + + /// Adds the elements of the body for each item of a flat list. + /// Thrown when the flat list is a default flat list. + member inline For : source : FlatList<'U> * [] body : ('U -> FlatListBuffer<'T>) -> FlatListBuffer<'T> + + /// Adds the elements of the body for each item of a span. + /// The items of the span are copied into an array first. + member inline For : source : ReadOnlySpan<'U> * [] body : ('U -> FlatListBuffer<'T>) -> FlatListBuffer<'T> + + /// Adds the elements of the body for each item of a span. + /// The items of the span are copied into an array first. + member inline For : source : Span<'U> * [] body : ('U -> FlatListBuffer<'T>) -> FlatListBuffer<'T> + + /// Adds the elements of the body for each item of a memory. + member inline For : source : ReadOnlyMemory<'U> * [] body : ('U -> FlatListBuffer<'T>) -> FlatListBuffer<'T> + + /// Adds the elements of the body for each item of a memory. + member inline For : source : Memory<'U> * [] body : ('U -> FlatListBuffer<'T>) -> FlatListBuffer<'T> + /// Adds the elements of the body while the guard holds. member inline While : [] guard : (unit -> bool) * body : FlatListBuffer<'T> -> FlatListBuffer<'T> @@ -70,3 +121,5 @@ type FlatListCE = /// Collects the elements of the expression. member Run : buffer : FlatListBuffer<'T> -> FlatList<'T> + +#warnon 1204 diff --git a/tests/FSharp.Collections.Immutable.Tests/FlatList/FlatListComputationExpressionTests.fs b/tests/FSharp.Collections.Immutable.Tests/FlatList/FlatListComputationExpressionTests.fs index 93e6248f..3ba8bfae 100644 --- a/tests/FSharp.Collections.Immutable.Tests/FlatList/FlatListComputationExpressionTests.fs +++ b/tests/FSharp.Collections.Immutable.Tests/FlatList/FlatListComputationExpressionTests.fs @@ -1,8 +1,9 @@ namespace FSharp.Collections.Immutable.Tests open System -open FSharp.Collections.Immutable open Microsoft.VisualStudio.TestTools.UnitTesting +open FSharp.Quotations +open FSharp.Collections.Immutable /// The `flatList { }` computation expression. [] @@ -10,6 +11,186 @@ type FlatListComputationExpressionTests () = static let defaultArray = Unchecked.defaultof> + /// The types of the first parameter of the For members that an expression calls, in the order of the loops: the + /// compiler chooses the overload of For by the type of the source of the loop, so they tell which overload it chose. + static let rec loopSources (expression : Expr) : Type list = + match expression with + | Patterns.Call (_, info, arguments) when info.Name = "For" -> + info.GetParameters().[0].ParameterType + :: List.collect loopSources arguments + | ExprShape.ShapeVar _ -> [] + | ExprShape.ShapeLambda (_, body) -> loopSources body + | ExprShape.ShapeCombination (_, arguments) -> List.collect loopSources arguments + + /// The sources of yield! and for that the compiler does not see as a sequence, an array or a flat list, by the construct and + /// the shape of the source, with the elements that the expression adds. The rows of the test are the names: a function + /// has no readable name in a row. + static let sources : Map FlatList))> = + let array = [| 1; 2; 3; 4; 5 |] + + Map.ofArray [| + "yield! of a span", struct ([| 2; 3 |], (fun () -> flatList { yield! array.AsSpan (1, 2) })) + "yield! of a read-only span", struct ([| 2; 3; 4 |], (fun () -> flatList { yield! ReadOnlySpan(array, 1, 3) })) + "yield! of a memory", struct ([| 3; 4 |], (fun () -> flatList { yield! array.AsMemory (2, 2) })) + "yield! of a read-only memory", + struct ([| 1; 2; 3 |], (fun () -> flatList { yield! ReadOnlyMemory(array, 0, 3) })) + "yield! of an empty span", struct ([||], (fun () -> flatList { yield! Span.Empty })) + "yield! of an empty read-only span", struct ([||], (fun () -> flatList { yield! ReadOnlySpan.Empty })) + "yield! of an empty memory", struct ([||], (fun () -> flatList { yield! Memory.Empty })) + "yield! of an empty read-only memory", struct ([||], (fun () -> flatList { yield! ReadOnlyMemory.Empty })) + "for over a span", + struct ([| 20; 30 |], + (fun () -> flatList { + for item in array.AsSpan (1, 2) do + yield item * 10 + })) + "for over a read-only span", + struct ([| 10; 20; 30 |], + (fun () -> flatList { + for item in ReadOnlySpan(array, 0, 3) do + yield item * 10 + })) + "for over a memory", + struct ([| 20; 30; 40 |], + (fun () -> flatList { + for item in array.AsMemory (1, 3) do + yield item * 10 + })) + "for over a read-only memory", + struct ([| 40; 50 |], + (fun () -> flatList { + for item in ReadOnlyMemory(array, 3, 2) do + yield item * 10 + })) + "for over an empty span", + struct ([||], + (fun () -> flatList { + for item in Span.Empty do + yield item + })) + "for over an empty memory", + struct ([||], + (fun () -> flatList { + for item in Memory.Empty do + yield item + })) + "yield! of memories between other elements", + struct ([| 0; 2; 3; 9; 1; 4; 8 |], + (fun () -> + let memory = ReadOnlyMemory array + + flatList { + yield 0 + yield! memory.Slice (1, 2) + yield 9 + yield! [| 1; 4 |].AsMemory() + yield 8 + } + )) + "yield! of spans between other elements", + struct ([| 0; 2; 3; 9 |], + (fun () -> flatList { + yield 0 + yield! array.AsSpan (1, 2) + yield 9 + })) + |] + + /// The expressions that add the body of another expression, by the place of yield!, with the elements of the result. A + /// body is a function of what the expression collects in: it adds its elements to the ones that are there already. + static let bodies : Map FlatList))> = + let ce = FlatListCE () + let body = ce.YieldFrom [| 10; 11 |] + + Map.ofArray [| + "alone", struct ([| 10; 11 |], (fun () -> flatList { yield! body })) + "between two elements", + struct ([| 1; 10; 11; 2 |], + (fun () -> flatList { + yield 1 + yield! body + yield 2 + })) + "after an array and a sequence", + struct ([| 1; 2; 3; 10; 11 |], + (fun () -> flatList { + yield! [| 1; 2 |] + yield! Seq.singleton 3 + yield! body + })) + "in a loop", + struct ([| 0; 10; 11; 1; 10; 11 |], + (fun () -> flatList { + for item in 0..1 do + yield item + yield! body + })) + "in the branch of a condition", + struct ([| 5; 10; 11 |], + (fun () -> flatList { + yield 5 + + if true then + yield! body + })) + "in try with, before another element", + struct ([| 1; 10; 11; 2 |], + (fun () -> flatList { + yield 1 + + try + yield! body + with _ -> + yield -1 + + yield 2 + })) + |] + + /// The sources that are not a sequence for the compiler, as the rows of their test. + static member Sources = sources.Keys + + /// The places of yield! of another body, as the rows of their test. + static member Bodies = bodies.Keys + + [] + member _.``yield! and for take spans and memories`` (name : string) = + let struct (expected, expression) = sources[name] + + CollectionAssert.AreEqual (expected, FlatList.toArray (expression ()), $"flatList must add the elements with %s{name}") + + [] + member _.``yield! of another body adds to the elements that the expression has`` (place : string) = + let struct (expected, expression) = bodies[place] + + CollectionAssert.AreEqual ( + expected, + FlatList.toArray (expression ()), + $"yield! of another body %s{place} must keep the elements of the expression" + ) + + [] + member _.``what yield! gets holds the elements that were added before`` () = + let counts = ResizeArray() + let targets = ResizeArray.Builder>() + + let probe (collected : FlatList.Builder) = + counts.Add collected.Count + targets.Add collected + + let result = flatList { + yield! probe + yield 1 + yield 2 + yield! probe + yield! [| 3; 4; 5 |] + yield! probe + } + + CollectionAssert.AreEqual ([| 0; 2; 5 |], counts.ToArray (), "each part must receive what the parts before it filled") + Assert.AreSame (targets[0], targets[1], "the second probe must get the instance that the first one got") + Assert.AreSame (targets[0], targets[2], "the third probe must get the instance that the first one got") + CollectionAssert.AreEqual ([| 1; 2; 3; 4; 5 |], FlatList.toArray result, "the parts must not replace the elements") [] member _.``an expression without elements is empty`` () = @@ -102,7 +283,257 @@ type FlatListComputationExpressionTests () = CollectionAssert.AreEqual ([| 10; 20; 30 |], FlatList.toArray array, "flatList must run the body of for for each item") [] - member _.``for rejects a default flat list, which it takes as a sequence`` () = + member _.``for adds the elements of a flat list in order`` () = + let array = flatList { + for item in FlatList.ofArray [| 1; 2; 3 |] do + yield item * 10 + } + + CollectionAssert.AreEqual ( + [| 10; 20; 30 |], + FlatList.toArray array, + "flatList must run the body of for for each item of a flat list" + ) + + [] + member _.``for adds the elements of an array in order`` () = + let array = flatList { + for item in [| 1; 2; 3 |] do + yield item * 10 + } + + CollectionAssert.AreEqual ( + [| 10; 20; 30 |], + FlatList.toArray array, + "flatList must run the body of for for each item of an array" + ) + + [] + member _.``for adds the elements of a list and of a lazy sequence in order`` () = + let fromList = flatList { + for item in [ 1; 2; 3 ] do + yield item * 10 + } + + let fromSequence = flatList { + for item in Seq.map id [| 1; 2; 3 |] do + yield item * 10 + } + + CollectionAssert.AreEqual ( + [| 10; 20; 30 |], + FlatList.toArray fromList, + "flatList must run the body of for for each item of a list" + ) + + CollectionAssert.AreEqual ( + [| 10; 20; 30 |], + FlatList.toArray fromSequence, + "flatList must run the body of for for each item of a lazy sequence" + ) + + [] + member _.``for adds the elements of the flat lists of a flat list in order`` () = + let rows = FlatList.ofArray [| FlatList.ofArray [| 1; 2 |]; FlatList.empty; FlatList.ofArray [| 3 |] |] + + let array = flatList { + for row in rows do + for item in row do + yield item * 10 + } + + CollectionAssert.AreEqual ( + [| 10; 20; 30 |], + FlatList.toArray array, + "flatList must run the inner loop for each item of the outer loop, also when a flat list is empty" + ) + + [] + member _.``for gives the type of the items to its body for every kind of source`` () = + // The body uses a member of the loop variable. The compiler can resolve it only when the overload that it chose + // gives the loop variable its type, so the test does not compile when an overload loses the type of the items + let names = [| "a"; "bb" |] + + let fromFlatList = flatList { + for name in FlatList.ofArray names do + yield name.Length + } + + let fromArray = flatList { + for name in names do + yield name.Length + } + + let fromList = flatList { + for name in List.ofArray names do + yield name.Length + } + + let fromSequence = flatList { + for name in Seq.map id names do + yield name.Length + } + + CollectionAssert.AreEqual ( + [| 1; 2 |], + FlatList.toArray fromFlatList, + "flatList must give the type of the items of a flat list to the body of for" + ) + + CollectionAssert.AreEqual ( + [| 1; 2 |], + FlatList.toArray fromArray, + "flatList must give the type of the items of an array to the body of for" + ) + + CollectionAssert.AreEqual ( + [| 1; 2 |], + FlatList.toArray fromList, + "flatList must give the type of the items of a list to the body of for" + ) + + CollectionAssert.AreEqual ( + [| 1; 2 |], + FlatList.toArray fromSequence, + "flatList must give the type of the items of a lazy sequence to the body of for" + ) + + [] + member _.``for chooses the overload of the type of its source`` () = + let flatListSource = FlatList.ofArray [| 1; 2; 3 |] + let arraySource = [| 1; 2; 3 |] + let listSource = [ 1; 2; 3 ] + let sequenceSource = Seq.map id arraySource + let rows = FlatList.ofArray [| flatListSource |] + let memorySource = arraySource.AsMemory () + let readOnlyMemorySource = ReadOnlyMemory arraySource + let segmentSource = ArraySegment arraySource + let stringSource = "abc" + + Assert.AreEqual( + [ typeof> ], + loopSources + <@ + flatList { + for item in flatListSource do + yield item + } + @>, + "for must take a flat list as a flat list, which does not box it" + ) + + Assert.AreEqual( + [ typeof ], + loopSources + <@ + flatList { + for item in arraySource do + yield item + } + @>, + "for must take an array as an array" + ) + + Assert.AreEqual( + [ typeof> ], + loopSources + <@ + flatList { + for item in listSource do + yield item + } + @>, + "for must take a list as a sequence" + ) + + Assert.AreEqual( + [ typeof> ], + loopSources + <@ + flatList { + for item in sequenceSource do + yield item + } + @>, + "for must take a lazy sequence as a sequence" + ) + + Assert.AreEqual( + [ typeof> ], + loopSources + <@ + flatList { + for item in (flatListSource :> seq) do + yield item + } + @>, + "for must take a flat list that the code converted to a sequence as a sequence" + ) + + Assert.AreEqual( + [ typeof>>; typeof> ], + loopSources + <@ + flatList { + for row in rows do + for item in row do + yield item + } + @>, + "for must take the flat lists of a flat list as flat lists, the outer loop first" + ) + + Assert.AreEqual( + [ typeof> ], + loopSources + <@ + flatList { + for item in memorySource do + yield item + } + @>, + "for must take a memory as a memory" + ) + + Assert.AreEqual( + [ typeof> ], + loopSources + <@ + flatList { + for item in readOnlyMemorySource do + yield item + } + @>, + "for must take a read-only memory as a read-only memory" + ) + + // An array segment and a string convert implicitly to a span, but they are sequences, which need no conversion + Assert.AreEqual( + [ typeof> ], + loopSources + <@ + flatList { + for item in segmentSource do + yield item + } + @>, + "for must take an array segment as a sequence" + ) + + Assert.AreEqual( + [ typeof> ], + loopSources + <@ + flatList { + for item in stringSource do + yield item + } + @>, + "for must take a string as a sequence" + ) + + [] + member _.``for rejects a default flat list`` () = let ex = Assert.ThrowsExactly( Action (fun () -> @@ -117,6 +548,38 @@ type FlatListComputationExpressionTests () = Assert.AreEqual("source", ex.ParamName, "flatList must name the parameter of the default flat list") + [] + member _.``for rejects a default flat list given as a sequence`` () = + let ex = + Assert.ThrowsExactly( + Action (fun () -> + flatList { + for item in (defaultArray :> seq) do + yield item + } + |> ignore + ), + "flatList must reject a default flat list that for takes as a sequence" + ) + + Assert.AreEqual("source", ex.ParamName, "flatList must name the parameter of the default flat list") + + [] + member _.``for rejects a null array`` () = + let ex = + Assert.ThrowsExactly( + Action (fun () -> + flatList { + for item in Unchecked.defaultof do + yield item + } + |> ignore + ), + "flatList must reject a null array in for" + ) + + Assert.AreEqual("source", ex.ParamName, "flatList must name the parameter of the null array") + [] member _.``for rejects a null sequence`` () = let ex =