Skip to content

Instantly share code, notes, and snippets.

@ArisAgnew
Created May 11, 2021 10:21
Show Gist options
  • Save ArisAgnew/ae2bf3f5fc6f0618348391eacb2252b8 to your computer and use it in GitHub Desktop.
Save ArisAgnew/ae2bf3f5fc6f0618348391eacb2252b8 to your computer and use it in GitHub Desktop.
FibonacciInterfaceIterator.cs
public interface IReader<T> where T : notnull
{
IReadOnlyCollection<T> GetElements();
T GetElementAt(int index) => GetElements().ElementAtOrDefault(index);
}
public record FibonacciReader : IReader<int>
{
public IReadOnlyCollection<int> GetElements() => new FibonacciSequence().ToList();
}
public record FibonacciSequence : IEnumerable<int>
{
public IEnumerator<int> GetEnumerator()
{
var value = (Current: 0, Next: 1);
bool flag = true;
while (flag)
{
value = (value.Next, value.Current + value.Next);
if (value.Next < 0)
{
flag = false;
}
yield return value.Current;
}
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
IReader<int> reader = new FibonacciReader();
(reader.GetElements() as List<int>).ForEach(number => Console.WriteLine(number));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment