Fix inefficient Seq.item usage in sumSeq example causing O(n²) complexity #49135
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Problem
The
sumSeq
function insnippet15.fs
usedSeq.item
within aSeq.unfold
loop, which caused O(n²) complexity and made it a poor example for developers learning about F# sequences:Each call to
Seq.item i
iterates from the beginning of the sequence to reach indexi
, causing the function to recalculate intermediate items every time. This made the code extremely slow for large sequences—taking 381ms for 10,000 terms.Solution
Replaced the implementation with an efficient functional pipeline using standard sequence operations:
This approach:
Seq.scan
to efficiently generate running sums in O(n) timeVerification
✅ All mathematical results remain identical to the original implementation
✅ Correctly computes infinite series approximations for ln2, π/4, and π²/6
✅ Produces the same running sums for all test cases
✅ Performance scales linearly instead of quadratically
This change provides a better teaching example for developers learning about F# sequences and IEnumerables, demonstrating proper usage patterns and efficient sequence processing.
Original prompt
Fixes #35428
💬 Share your feedback on Copilot coding agent for the chance to win a $200 gift card! Click here to start the survey.