Skip to content

Commit

Permalink
Expand & reuse implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
atifaziz committed Nov 19, 2022
1 parent 1f3315b commit 8917f27
Showing 1 changed file with 28 additions and 7 deletions.
35 changes: 28 additions & 7 deletions MoreLinq/Sequence.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@

namespace MoreLinq
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;

static partial class MoreEnumerable
Expand Down Expand Up @@ -77,8 +77,23 @@ public static IEnumerable<T> Sequence<T>(T start, T stop)
/// </remarks>

public static IEnumerable<T> Sequence<T>(T start, T stop, T step)
where T : INumber<T> =>
Generate(start, n => n + step).TakeWhile(n => T.IsPositive(step) ? stop >= n : stop <= n);
where T : INumber<T>
{
var current = start;

while (step >= T.Zero ? stop >= current : stop <= current)
{
yield return current;
try
{
current = checked(current + step);
}
catch (OverflowException)
{
yield break;
}
}
}
}
}

Expand Down Expand Up @@ -107,10 +122,12 @@ static partial class MoreEnumerable
/// The <c>result</c> variable will contain <c>{ 6, 5, 4, 3, 2, 1, 0 }</c>.
/// </example>

public static IEnumerable<int> Sequence(int start, int stop)
{
return Sequence(start, stop, start < stop ? 1 : -1);
}
public static IEnumerable<int> Sequence(int start, int stop) =>
#if !NO_STATIC_ABSTRACTS
Sequence<int>(start, stop);
#else
Sequence(start, stop, start < stop ? 1 : -1);
#endif

/// <summary>
/// Generates a sequence of integral numbers within the (inclusive) specified range.
Expand All @@ -134,6 +151,9 @@ public static IEnumerable<int> Sequence(int start, int stop)

public static IEnumerable<int> Sequence(int start, int stop, int step)
{
#if !NO_STATIC_ABSTRACTS
return Sequence<int>(start, stop, step);
#else
long current = start;

while (step >= 0 ? stop >= current
Expand All @@ -142,6 +162,7 @@ public static IEnumerable<int> Sequence(int start, int stop, int step)
yield return (int)current;
current += step;
}
#endif
}
}
}

0 comments on commit 8917f27

Please sign in to comment.