Logo ResizeArray

Logo

ResizeArrayT

ResizeArrayT on nuget.org Build Status Docs Build Status Test Status license code size

ResizeArrayT is an F# extension and module library for ResizeArray<'T> ( = System.Collections.Generic.List<'T>).
It provides all the functions from the Array module in FSharp.Core for ResizeArray.
And more.

It also works in Javascript and Typescript with Fable.

This library was designed for use with F# scripting.
Functions and methods never return null.
When ResizeArrayT rejects invalid input, it throws a descriptive exception such as ResizeArrayTArgumentException, ResizeArrayTArgumentNullException, or ResizeArrayTKeyNotFoundException.
Each type inherits from its corresponding .NET exception type, so existing .NET exception handlers still work. Index errors use IndexOutOfRangeException directly because that type is sealed.
Functions starting with try... will return an F# option.

I was always annoyed that an IndexOutOfRangeException does not include the actual bad index nor the actual size of the array.
This library fixes that in the resizeArray.Get, resizeArray.Set, resizeArray.SliceIdx and similar instance methods for item access.
I made a similar library for array<'T>: https://github.com/goswinr/ArrayT/ .

Why ?

Yes, F#'s array and list modules can do these kind of operations on collections too.
But ResizeArray, being mutable, still offers the best performance for collections that can expand & shrink and need random access via an index.
In fact FSharp.Core uses a very similar module internally.

It Includes:

Namespace

The main namespace is ResizeArrayT.
It was renamed from ResizeArray to ResizeArrayT in release 0.23. When used in scripting this helps avoid name collisions with the
module inside of the same name. Reference Issue

Older versions of the library will still work with the old namespace ResizeArray.
And can be found on nuget.org with the name ResizeArray.

Usage

Just open the namespace

open ResizeArrayT

this namespace contains: - a module also called ResizeArray - a Computational Expressions called resizeArray - this will also auto open the extension members on ResizeArray<'T>

then you can do:

let evenNumbers =
    resizeArray {  // a Computational Expression like seq
        for i = 0 to 99 do
            if i % 2 = 0 then
                i
    }

let oddNumbers = evenNumbers |> ResizeArray.map (fun x -> x + 1) // ResizeArray module

let ninetyNine = oddNumbers.Last // Extension member to access the last item in the list

Computational Expression

The resizeArray { ... } builder supports for, while, yield, yield!, try/with, try/finally, and use:

// Yield individual items and sequences
let mixed =
    resizeArray {
        1
        2
        yield! [3; 4; 5]   // yield from any seq
        for i in 6..10 do
            i
    }

// Filter inside the builder
let primes =
    resizeArray {
        for n = 2 to 50 do
            let mutable isPrime = true
            for d = 2 to int (sqrt (float n)) do
                if n % d = 0 then isPrime <- false
            if isPrime then n
    }

Extension Members

Access items with descriptive error messages that include the bad index and the collection size:

let items = ResizeArray([| "a"; "b"; "c"; "d"; "e" |])

items.First        // "a"
items.Second       // "b"
items.Last         // "e"
items.SecondLast   // "d"
items.LastIndex    // 4

// Negative indexing (Python-style: -1 is last item)
items.GetNeg(-1)   // "e"
items.GetNeg(-2)   // "d"

// Looped indexing (wraps around)
items.GetLooped(7) // "c"  (index 7 wraps to index 2)

// Status checks
items.IsEmpty      // false
items.IsNotEmpty   // true
items.HasItems     // true
items.IsSingleton  // false

Slicing

F# slicing notation is fully supported, including indexing from the end with ^.
Just like for F# arrays, out-of-range indices are clamped when getting a slice.
Indexing from the end still needs <LangVersion>preview</LangVersion> in your project, or dotnet fsi --langversion:preview in scripts.

let nums = ResizeArray([| 10; 20; 30; 40; 50 |])

nums.[1..3]        // ResizeArray [20; 30; 40]
nums.[..2]         // ResizeArray [10; 20; 30]
nums.[2..]         // ResizeArray [30; 40; 50]
nums.[1..^1]       // ResizeArray [20; 30; 40]  (from index 1 to second-last)
nums.[^0]          // 50  (last item)
nums.[3..9]        // ResizeArray [40; 50]  (clamped)

To get an exception for out-of-range indices instead, use SliceNeg or SliceIdx. SliceLooped wraps any index around with modulo. They all include the end index:

nums.SliceNeg(1, -2)       // ResizeArray [20; 30; 40]  (negative indices allowed, -1 is the last item)
nums.SliceIdx(1, 3)        // ResizeArray [20; 30; 40]  (throws on negative indices)
nums.SliceLooped(-2, -1)   // ResizeArray [40; 50]      (any index wraps around with modulo)
nums.SliceLooped(5, 6)     // ResizeArray [10; 20]      (5 wraps to 0, 6 to 1)

// Module functions
nums |> ResizeArray.sliceNeg 1 -2
nums |> ResizeArray.sliceIdx 1 3
nums |> ResizeArray.sliceLooped -2 -1

These work the same in ArrayT and Str.
Don't confuse them with the built-in nums.Slice(start, count) method of .NET, which takes a count instead of an end index. For a start index and a count, you can also use ResizeArray.sub.

Pop, Clone, and InsertAtStart

let xs = ResizeArray([| 1; 2; 3; 4; 5 |])

let last = xs.Pop()            // returns 5, xs is now [1; 2; 3; 4]
let second = xs.Pop(1)         // returns 2, xs is now [1; 3; 4]

xs.InsertAtStart(0)            // xs is now [0; 1; 3; 4]

let copy = xs.Clone()          // shallow copy, same as xs.Copy()

ResizeArray Module

All functions from FSharp.Core's Array module are available, plus many extras:

let items = ResizeArray [ 1 .. 100 ]

// Standard functional operations
let doubled = items |> ResizeArray.map (fun x -> x * 2)
let evens   = items |> ResizeArray.filter (fun x -> x % 2 = 0)
let total   = items |> ResizeArray.sum

// Positional access
let first     = items |> ResizeArray.first
let last      = items |> ResizeArray.last
let secLast   = items |> ResizeArray.secondLast

// Grouping and counting
let grouped  = items |> ResizeArray.groupBy (fun x -> x % 3)
let counts   = items |> ResizeArray.countBy (fun x -> x % 3)

// Finding duplicates
let dupes    = items |> ResizeArray.duplicates
let dupesBy  = items |> ResizeArray.duplicatesBy (fun x -> x % 10)

// Partitioning into multiple groups
let trueOnes, falseOnes = items |> ResizeArray.partition (fun x -> x > 3)

let small, medium, large =
    items |> ResizeArray.partition3
        (fun x -> x < 10)
        (fun x -> x < 50)

// Windowed iteration (useful for geometry/polyline processing)
items |> ResizeArray.windowed2 |> Seq.iter (fun (a, b) -> printfn "%A -> %A" a b)
items |> ResizeArray.prevThisNext |> Seq.iter (fun (prev, this', next) -> printfn "%A %A %A" prev this' next)

Grouping into a dictionary

ResizeArray.groupByDict uses F# structural equality for grouping and dictionary lookups on both .NET and Fable, like Array.groupByDict in ArrayT. Keys must support equality ('Key : equality); null and None keys are rejected. Elements within each group keep their input order.

let groups = ResizeArray [1; 2; 3; 4; 5] |> ResizeArray.groupByDict (fun x -> [|x % 2|])
groups.[[|1|]]    // ResizeArray [1; 3; 5], looked up using a fresh, structurally equal array key

Construction and Conversion

let empty  = ResizeArray.empty<int>
let single = ResizeArray.singleton 42
let filled = ResizeArray.create 10 0         // 10 zeros
let inited = ResizeArray.init 5 (fun i -> i * i) // [0; 1; 4; 9; 16]

// From other collections
let fromList  = ResizeArray.ofList [1; 2; 3]
let fromArray = ResizeArray.ofArray [|1; 2; 3|]
let fromSeq   = ResizeArray.ofSeq (seq { 1..10 })

// To other collections
let asArray = items |> ResizeArray.toArray
let asList  = items |> ResizeArray.toList
let asSeq   = items |> ResizeArray.toSeq

Error Messages

When an index is out of range, you get a descriptive exception including the bad index and the collection content:

System.IndexOutOfRangeException:
ResizeArray.Get: Can't get index 5 from:
ResizeArray<String> with 3 items:
  0: a
  1: b
  2: c

Operators

Open the Operators module to combine collections with ++ and +++:

open ResizeArrayT.Operators

let combined = xs ++ ys         // from two ICollection<'T>, preallocates capacity
let combined' = xs +++ ys       // from two seq<'T>

Parallel

A sub module for parallel operations (on .NET only):

let results = items |> ResizeArray.Parallel.map (fun x -> expensiveComputation x)
let chosen  = items |> ResizeArray.Parallel.choose (fun x -> tryProcess x)

Use of AI and LLMs

All core functions are written by hand to ensure performance and correctness.
However, AI tools have been used for code review, typo and grammar checking in documentation
and to generate not all but many of the tests.

Full API Documentation

goswinr.github.io/ResizeArrayT

Tests

All Tests run in both javascript and dotnet, except the ones for the .NET only Parallel module. Successful Fable compilation to typescript is verified too. Go to the tests folder:

cd Tests

The tests use Scriptorium (Scriptorium.Quill as test runner and Scriptorium.Nib for assertions). The same test suite runs unchanged on .NET and in JS via Fable.

For testing with .NET:

dotnet run

for JS testing (Fable compiles the tests and runs them with Node.js) and TS verification:

npm test

License

MIT

Changelog

see CHANGELOG.md

val evenNumbers: obj
val oddNumbers: obj
type ResizeArray<'T> = System.Collections.Generic.List<'T>
val ninetyNine: obj
val mixed: obj
val primes: obj
Multiple items
val int: value: 'T -> int (requires member op_Explicit)

--------------------
type int = int32

--------------------
type int<'Measure> = int
val sqrt: value: 'T -> 'U (requires member Sqrt)
Multiple items
val float: value: 'T -> float (requires member op_Explicit)

--------------------
type float = System.Double

--------------------
type float<'Measure> = float
val items: ResizeArray<string>
val nums: ResizeArray<int>
val xs: ResizeArray<int>
val last: obj
val second: obj
val copy: obj
val items: ResizeArray<int>
val doubled: obj
val evens: obj
val total: obj
val first: obj
val secLast: obj
val grouped: obj
val counts: obj
val dupes: obj
val dupesBy: obj
val trueOnes: obj
val falseOnes: obj
val small: obj
val medium: obj
val large: obj
module Seq from Microsoft.FSharp.Collections
val iter: action: ('T -> unit) -> source: 'T seq -> unit
val a: obj
val b: obj
val printfn: format: Printf.TextWriterFormat<'T> -> 'T
val prev: obj
val this': obj
val next: obj
val groups: obj
val empty: obj
Multiple items
val single: obj

--------------------
type single = System.Single

--------------------
type single<'Measure> = float32<'Measure>
val filled: obj
val inited: obj
val fromList: obj
val fromArray: obj
val fromSeq: obj
Multiple items
val seq: sequence: 'T seq -> 'T seq

--------------------
type 'T seq = System.Collections.Generic.IEnumerable<'T>
val asArray: obj
val asList: obj
val asSeq: obj
namespace System
Multiple items
type IndexOutOfRangeException = inherit SystemException new: unit -> unit + 2 overloads
<summary>The exception that is thrown when an attempt is made to access an element of an array or collection with an index that is outside its bounds.</summary>

--------------------
System.IndexOutOfRangeException() : System.IndexOutOfRangeException
System.IndexOutOfRangeException(message: string) : System.IndexOutOfRangeException
System.IndexOutOfRangeException(message: string, innerException: exn) : System.IndexOutOfRangeException
module String from Microsoft.FSharp.Core

Type something to start searching.