Map and Apply in C#

Don Box's Spoutlet

Syndication

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

Comments

Drazen Dotlic wrote re: Map and Apply in C#
on 04-23-2005 12:29 PM
Extremely contrived, but infinitely cool example of what you can do with C# 2.0...
Sriram wrote re: Map and Apply in C#
on 04-24-2005 3:04 AM
I tried the same thing in C# 1.0 and didn't fare so well

http://dotnetjunkies.com/WebLog/sriram/archive/2004/12/27/39119.aspx
Jelle Druyts wrote Generics at the Indigo service boundary
on 05-23-2005 4:05 PM
Jamie Fristrom wrote re: Map and Apply in C#
on 09-09-2006 8:38 PM
Didn't work for me...

Error 2 Using the generic type 'System.Collections.Generic.IEnumerable<T>' requires '1' type arguments

This is with VS Express C# 2005 - I thought that was 2.0 but maybe I have my head up?

If you want to e-mail me and tell me what I'm doing wrong jdfristrom@gmail.com.

Add a Comment

(required)  
(optional)
(required)  
Remember Me?