Skip to content

Instantly share code, notes, and snippets.

@vritant24
Last active March 27, 2021 04:03
Show Gist options
  • Select an option

  • Save vritant24/5196e824fb2496f7c3fd16d714d52b4a to your computer and use it in GitHub Desktop.

Select an option

Save vritant24/5196e824fb2496f7c3fd16d714d52b4a to your computer and use it in GitHub Desktop.
using System;
using System.Collections;
using System.Collections.Generic;
namespace Streamable
{
public class Sequence<T, U> : IEnumerable<T>, IEnumerator<T>
{
private readonly Func<T, U, ulong, (T element, U state, bool isLast)> formulae;
private readonly T firstElement;
private readonly U initialState;
private bool isEnded;
private ulong index;
private readonly object valueGate = new();
public Sequence(
Func<T, U, ulong, (T nextElement, U state, bool isLast)> formulae,
T firstElement,
U initialState)
{
this.formulae = formulae;
this.firstElement = firstElement;
this.initialState = initialState;
this.isEnded = false;
this.index = 0;
this.Current = this.firstElement;
this.State = this.initialState;
}
#region IEnumerator
public T Current { get; private set; }
public U State { get; private set; }
object IEnumerator.Current => Current;
public bool MoveNext()
{
lock (valueGate)
{
if (isEnded)
{
return false;
}
this.index++;
(Current, State, isEnded) = formulae(Current, State, this.index);
}
return true;
}
public void Reset()
{
lock (valueGate)
{
this.isEnded = false;
this.index = 0;
this.Current = this.firstElement;
this.State = this.initialState;
}
}
public void Dispose()
{
// Do nothing
}
#endregion
#region IEnumerable
public IEnumerator<T> GetEnumerator()
{
return this;
}
IEnumerator IEnumerable.GetEnumerator()
{
return this;
}
#endregion
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment