Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Synchronous and Asynchronous Lazy Lists in C#
void Main()
{
var k1 = integers(1);
// Expect 5
k1.nth(5).Dump();
var k2 = factorials(1);
// Expect 120
k2.nth(5).Dump();
// A hint to what's coming up next
AsyncMain();
}
#region LazyLists
public static LazyList<int> integers(int n)
{
return new LazyList<int> {value = n, rest = () => integers(n + 1)};
}
public static LazyList<int> factorials(int n)
{
return new LazyList<int>
{
value = (n <= 1) ? 1 : n * factorials(n - 1).value,
rest = () => factorials(n + 1)
};
}
public class LazyList<T>
{
public T value;
public Func<LazyList<T>> rest;
public T nth(int n)
{
return
(n <= 1) ?
value :
rest().nth(n - 1);
}
}
#endregion
public static void DumpThreadId(string msg = "")
{ System.Threading.Thread.CurrentThread.ManagedThreadId.Dump(msg + "Thread Id");
}
public static async void AsyncMain()
{
DumpThreadId("Async main, k3: ");
var k3 = asyncIntegers(1);
(await k3.nth(5)).Dump();
DumpThreadId("Async main, k4: ");
var k4 = asyncFactorials(1);
(await k4.nth(5)).Dump();
var z0 = (await Task.Run(() =>
{ DumpThreadId("Anonymous task: ");
Thread.Sleep(ran.Next(200));
return 42;
}));
DumpThreadId("Async main, z0: ");
}
#region AsyncLists
public static Random ran = new Random();
public static AsyncList<int> asyncIntegers(int n)
{ return new AsyncList<int>
{ value = n,
rest = () =>
{ DumpThreadId("AsyncIntegers, rest: ");
Thread.Sleep(ran.Next(200));
return asyncIntegers(n + 1);
}
};
}
public static AsyncList<int> asyncFactorials(int n)
{ return new AsyncList<int>
{ value = (n <= 1) ? 1 : n * asyncFactorials(n - 1).value,
rest = () =>
{ DumpThreadId("AsyncFactorials, rest: ");
Thread.Sleep(ran.Next(200));
return asyncFactorials(n + 1);
}
};
}
public class AsyncList<T>
{ public T value;
public Func<AsyncList<T>> rest;
public async Task<T> nth(int n)
{ return
(n <= 1) ?
await (Task.Run(() =>
{ DumpThreadId("AsyncList, nth: ");
return value;
})) :
await ((await Task.Run(() =>
{ Thread.Sleep(ran.Next(200));
return rest();
})).nth(n - 1));
}
}
#endregion
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment