tabs ↹ over ␣ ␣ ␣ spaces

by Jiří {x2} Činčura

Composing functions the LINQ way

24 Dec 2011 1 mins .NET, C#, Functional programming, LINQ

Few days ago I was writing a class, that was simply wrapped for a collection of other classes (with same interface), aggregate class. The class also had few methods, where the logic was simple. Let’s say one method M. Other classes having same method as well. This method was simple transformation of data with same output as input. The aggregate class was simply calling M method of first, second, … of other classes.

I started with something like this:

function T M<T>(T data)
{
	T tmp = data;
	foreach (var c in classes)
	{
		tmp = c.M(tmp);
	}
	return tmp;
}

But then I had some weird wave in my brain and started thinking. I could create collection of functions, like IEnumerable<Func<T, T>> and call methods from this collection. Wait a minute… I can create from this collection of function one aggregate function and call just this one. Crazy? 😉 Probably. But it’s a nice way to keep my brain running.

It turned out, it’s pretty easy with LINQ:

public static Func<T, T> Compose<T>(this IEnumerable<Func<T, T>> source)
{
	return source.Aggregate((agg, fn) => (d => fn(agg(d))));
}

I don’t think it’s any more (less) useful than the foreach with direct method calls, but it’s more succinct, more functional and more fun. 😎

Profile Picture Jiří Činčura is .NET, C# and Firebird expert. He focuses on data and business layers, language constructs, parallelism, databases and performance. For almost two decades he contributes to open-source, i.e. FirebirdClient. He works as a senior software engineer for Microsoft. Frequent speaker and blogger at www.tabsoverspaces.com.