From 034ba56bd6e459bb7dde418eea6d921adaa557d1 Mon Sep 17 00:00:00 2001 From: Atif Aziz Date: Sat, 1 Apr 2023 14:28:42 +0200 Subject: [PATCH] Fix "Unfold" bug so iterations are repeatable --- MoreLinq.Test/UnfoldTest.cs | 13 +++++++++++++ MoreLinq/Unfold.cs | 4 ++-- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/MoreLinq.Test/UnfoldTest.cs b/MoreLinq.Test/UnfoldTest.cs index 0f5a581cb..ef2a3ee1b 100644 --- a/MoreLinq.Test/UnfoldTest.cs +++ b/MoreLinq.Test/UnfoldTest.cs @@ -81,5 +81,18 @@ public void UnfoldEmptySequence() e => e.Result); Assert.That(result, Is.Empty); } + + [Test(Description = "https://github.com/morelinq/MoreLINQ/issues/990")] + public void UnfoldReiterationsReturnsSameResult() + { + var xs = MoreEnumerable.Unfold(1, n => (Result: n, Next: n + 1), + _ => true, + n => n.Next, + n => n.Result) + .Take(5); + + xs.AssertSequenceEqual(1, 2, 3, 4, 5); + xs.AssertSequenceEqual(1, 2, 3, 4, 5); + } } } diff --git a/MoreLinq/Unfold.cs b/MoreLinq/Unfold.cs index c61ef9745..d6f5b8738 100644 --- a/MoreLinq/Unfold.cs +++ b/MoreLinq/Unfold.cs @@ -61,9 +61,9 @@ public static IEnumerable Unfold( if (stateSelector == null) throw new ArgumentNullException(nameof(stateSelector)); if (resultSelector == null) throw new ArgumentNullException(nameof(resultSelector)); - return _(); IEnumerable _() + return _(state); IEnumerable _(TState initialState) { - while (true) + for (var state = initialState; ;) { var step = generator(state);