Functional programming in C# – Reloaded!


My avid readers (all 3 of them) may remember my old post on functional programming in C#. Well, with all the coolness in Linq, functional programming in C# just got a lot easier.


Here’s my old code

    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, having the curried parameters at the beginning, followed
                    // by the arguments at the time the generated delegate is called

                    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 );

                };

        }

And here’s the new C# 3.0/Linq code (just compiled this using the PDC bits. You can get it here)


public static Function<K, K1> Curry<K, K1>(Function<K, K1> func, params K1[] curriedArgs)
{

    return funcArgs => func(Sequence.Concat(curriedArgs, funcArgs).ToArray());

}


The ‘=>’ is C# 3.0’s lambda operator. Lambda expressions are of the form


 (params) => expr.


Un-freaking-believably cool!

P.S Thanks to Don Box for pointing this out when I posted that entry a few weeks ago. And Anders for thinking up of all this stuff 🙂


Comments (2)

  1. CN says:

    It would be highly interesting (to performance geeks also in love with some syntactic sugar, like me), if this gets any more efficient than your original code, in practice. To get the full functional programming style on equal footing, the operation of creating a new delegate itself might need some optimization, maybe even caching behind the scenes.

    Anyway, highly cool code, but I can also easily see that many rigid business coding guidelines would disallow touching this, just like there has been a tendency to disallow things like templates in C++, because of the fact that:

    a) not all maintainers will understand it

    and

    b) "it looks strange"

  2. Bruce says:

    Yeah, when I first read about the language features supporting LINQ (infered types, anonymous type constructors, lambdas, etc) my first thought was "Forget this databinding stuff! Just give me these new language tools to play with!"