Created
December 9, 2023 14:41
-
-
Save einarwh/17fc075fdae2632b90cb1ce121767e80 to your computer and use it in GitHub Desktop.
Printing Hello, World! with nested enumerables.
This file contains 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
namespace Tailor; | |
using System.Collections; | |
using System.Collections.Generic; | |
public static class EnumerableExt | |
{ | |
public static IEnumerable<T> Tail<T>(this IEnumerable<T> source) | |
{ | |
return new TailEnumerable<T>(source); | |
} | |
} | |
public class TailEnumerable<T> : IEnumerable<T> | |
{ | |
private readonly IEnumerable<T> _enumerable; | |
public TailEnumerable(IEnumerable<T> enumerable) | |
{ | |
_enumerable = enumerable; | |
} | |
public IEnumerator<T> GetEnumerator() | |
{ | |
return new TailEnumerator<T>(_enumerable.GetEnumerator()); | |
} | |
IEnumerator IEnumerable.GetEnumerator() | |
{ | |
return GetEnumerator(); | |
} | |
} | |
public class TailEnumerator<T> : IEnumerator<T> | |
{ | |
private readonly IEnumerator<T> _enumerator; | |
public TailEnumerator(IEnumerator<T> enumerator) | |
{ | |
_enumerator = enumerator; | |
if (!MoveNext()) { | |
throw new Exception("No tail!"); | |
} | |
} | |
public bool MoveNext() | |
{ | |
Console.Write("->"); | |
return _enumerator.MoveNext(); | |
} | |
public T Current | |
{ | |
get { return _enumerator.Current; } | |
} | |
object? IEnumerator.Current | |
{ | |
get { return Current; } | |
} | |
public void Dispose() { } | |
public void Reset() | |
{ | |
_enumerator.Reset(); | |
} | |
} | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
IEnumerable<char> s = "Hello, World!"; | |
while (s.Any()) { | |
var ch = s.First(); | |
Console.WriteLine(ch); | |
s = s.Tail(); | |
} | |
Console.ReadKey(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment