My last post for the morning is for the
schemers out there.
I make no claims as to the utility of this code, but it's a nice demonstration of all of the pieces that have been discussed.
class app {
public static object Apply(Delegate proc, params object[] args) {
return proc.DynamicInvoke(args);
}
public static IEnumerable Map(Delegate proc, params IEnumerable[] lists) {
IEnumerator[] iterators = Array.ConvertAll<IEnumerable, IEnumerator>(
lists, delegate(IEnumerable e) { return e.GetEnumerator(); });
bool keepGoing = true;
while (true) {
Array.ForEach(iterators, delegate(IEnumerator e) {
if (keepGoing)
keepGoing = e.MoveNext();
});
if (!keepGoing)
break;
object[] args = Array.ConvertAll<IEnumerator, object>(iterators,
delegate(IEnumerator e) { return e.Current; });
object result = Apply(proc, args);
yield return result;
}
}
delegate T Function<T1, T2, T3, T>(T1 a, T2 b, T3 c);
static void Main() {
double total = 0;
int count = 0;
Function<string, double, bool, string> proc
= delegate(string name, double age, bool isDead) {
count++;
total += age;
return string.Format("{0}{1} is {2} years old",
(isDead ? "The late " : ""), name, age);
};
foreach (string s in Map(proc,
new string[] { "Don", "Sam", "Kurt" },
new double[] { 42, 33, 72 },
new bool[] { false, false, true })) {
Console.WriteLine(s);
}
Console.WriteLine("Visited {0} with an average of {1}", count, total / count);
}
}
Posted
Apr 23 2005, 02:54 PM
by
don-box