Last active
March 27, 2021 04:03
-
-
Save vritant24/5196e824fb2496f7c3fd16d714d52b4a to your computer and use it in GitHub Desktop.
A sequence with additional state https://gist.github.com/vritant24/0e39482ac2c91f6368d1f13eaacaf2b0
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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