Skip to content

Instantly share code, notes, and snippets.

@einarwh
Created December 9, 2023 14:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save einarwh/17fc075fdae2632b90cb1ce121767e80 to your computer and use it in GitHub Desktop.
Save einarwh/17fc075fdae2632b90cb1ce121767e80 to your computer and use it in GitHub Desktop.
Printing Hello, World! with nested enumerables.
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