Last active
August 7, 2025 15:49
-
-
Save TheAngryByrd/8b7d02f8835482e17fd53230fea1fa9e to your computer and use it in GitHub Desktop.
F# TryGetNonEnumeratedCount helper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Seq = | |
open System.Linq | |
/// Attempts to determine the number of elements in a sequence without forcing an enumeration. | |
let inline tryLength (xs : seq<_>) = | |
match Enumerable.TryGetNonEnumeratedCount xs with | |
| true, count -> ValueSome count | |
| _ -> | |
match xs with | |
// F# list implements IReadOnlyCollection/IReadOnlyList | |
// but TryGetNonEnumeratedCount doesn't support it | |
// see https://github.com/dotnet/runtime/issues/42254 | |
| :? List<_> as l -> ValueSome (List.length l) | |
| _ -> ValueNone |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment