How to dynamically create a library to curry Func delegates.

Dynamic currying: part 1

Recently, I was thinking about the difference between lambdas in C# and Haskell. The one that seemed interesting to me is that in Haskell, you actually can't create a function that has more than one parameter. You can either create a function whose sole parameter is a n-tuple, or, more frequently, a function that returns a function. The returned function can return a function again and, thanks to closures, it can also use the parameter of the function that returned it.

This way of doing things has the advantage that you can specify some of the parameters now, and some later. In Haskell syntax, this also looks good.

You can do the same with C# lambdas, and even though synatx like f(1)(2)(3) doesn't look that good, I think it has its uses. So, how can we use it in C#? There's this thing called currying: converting a function that takes multiple arguments into a function with one argument that returns another function.

The conversion itself is pretty simple:

public static Func<T1, Func<T2, TResult>> Curry<T1, T2, TResult>(Func<T1, T2, TResult> func)
    return p1 => p2 => func(p1, p2);

The method signature is actually longer than the method body. It's an extension method, so that you can call it directly on a delegate: f.Curry(). And, of course, it's a generic method.

But there is 16 methods in the Func family, and I certainly don't want to have almost the same code 16 times, do I? Actually, yeah, that would be the sensible thing to do. Fortunately, nobody is forcing me to do the sensible thing, so I can do something cool instead.

Which leads us to another thing I was looking into recently: ways to dynamically generate .Net code like DynamicProxy and CodeDOM.

CodeDOM is way to create and manipulate source code programmatically, in a language-independent way. And since I am interested only in C# code, this independence is the source of several pains with CodeDOM, but I'll come to that later.

In a next post, I will describe how to actually use CodeDOM and what problems did I encounter while using it.

dotnet c# codedom
Posted by: Petr Onderka
Last revised: 16 Jul, 2018 04:24 AM History


Marcel Valdez
Marcel Valdez
12 Sep, 2012 06:27 AM

There is a project specifically meant to be used for manipulating C# code, this is the project the VS team uses for all their refactoring extensions in visual studio's editor.

That project is Project Roslyn.

12 Sep, 2012 08:44 AM

Yeah, I know about Roslyn, but it wasn't available at the time when I wrote this article.

But Roslyn isn't finished yet, I don't think the VS team actually uses it in production yet. The license of the Roslyn CTPs even doesn't allow you to run it in production.

Your Comments

Used for your gravatar. Not required. Will not be public.
Posting code? Indent it by four spaces to make it look nice. Learn more about Markdown.