Geeks With Blogs
A Software Engineering Blog by Nick Holmes

I previously said that C#’s lambda functions were not curried, and it wasn’t possible to partially apply them. However, it’s usually possible to manually curry functions, if you need to. Here is an example:

static void Main(string[] args)
    int t = f(1)(3)(5)(7);

    Console.WriteLine("{0}", t);

    var g = f(1);
    var h = g(3);
    var i = h(5);
    int j = i(7);

    Console.WriteLine("{0}", j);

static Func<int, Func<int, Func<int, int>>> f(int a)
    return (b => c => d => (a + b + c + d));

It’s interesting to step through that code in Visual Studio. As the complex lambda expression is repeatedly returned to, the highlighting outlines exactly which sub-function is being evaluated. However, the return type of the f is not at all easy to read (although the new C# 3.0 var keyword means we don’t need to repeat this horror for g, h, & i). The equivalent code in F# is far more svelte:

let f a b c d = a + b + c + d

Even with my cryptically short function name, its clear what this function does. There’s one more thing on curried functions I want to look at, but before that I’m going to look at implementing Web Services in F# and WCF.

Posted on Tuesday, May 5, 2009 11:37 AM Functional Programming | Back to top

Comments on this post: Curried Functions In C#

No comments posted yet.
Your comment:
 (will show your gravatar)

Copyright © Nick Holmes | Powered by: