Monday, August 5, 2013

map in C#

I was recently at a meeting where someone remarked that you could not write a higher-order function like map in C# because of strong typing.  In fact, you can write the map (and similar) functions in C# using generic type parameters, but there are other weaknesses.

For the curious, here is one way to write map in C#:

class HigherOrderFunction<T1, T2> {
  public delegate T2 function(T1 p);

  public static IEnumerable<T2> Map(function f, IEnumerable<T1> ps) {
    List<T2> result = new List<T2>();

    foreach (T1 p in ps) {
      result.Add(f(p));
    }

    return result;
  }
}

The problem with this function is that it is not lazy.  If the input array is huge, but you only need a few values out of it, you still have to process all of the other values before you can get the one you want. If you want lazy evaluation here, the code becomes very convoluted.

In my next post, I'll write the map function in F#, compile it, disassemble it, and see how it works under the covers.

No comments:

Post a Comment