Friday, March 24, 2006

C# Partial Function Application

Sriram Krishnan wrote a great article which really blew my mind.
After reading it 327 times, I was left with one question...

public class Lambda
{
  public delegate T Function<T,T1>(params T1[] args);

  public static Function<K,K1> Curry<K,K1>(Function<K,K1> func, params K1[] curriedArgs)
  {
    return delegate(K1[] funcArgs)
    {
      // Create a final array of parameters
      K1[] actualArgs = new K1[funcArgs.Length + curriedArgs.Length];
      curriedArgs.CopyTo(actualArgs, 0);
      funcArgs.CopyTo(actualArgs, curriedArgs.Length );

      // Call the function with our final array of parameters
      return func( actualArgs );
    };
  }
}

public static int Add (params int[] numbers)
{
  int result =0;
  foreach (int i in numbers)
  {
    result += i;
  }
  return result;
}

// Test call...
Lambda.Function<int,int> adder=Lambda.Curry<int,int>(Add,7);
adder(5, 6); // Returns 18


How is the scope of curriedArgs managed?

So, after a bit of research it turns out that the captured variables of anonymous methods are member variables of the class. Hence it stays in scope (in this case with a value of 7), between the anonymous delegate being created and invoked.

This may be cool, but may also lead to problems like this.

None the less, I'm impressed and given the direction of C# in 2.0 it looks like developers are soon going to have to open their eyes to
Functional Programming or perhaps leave it to the F# guys =]

Comments on "C# Partial Function Application"

 

post a comment