Late there has been quite a lot of talk about functional programming in C#. Efforts by Don Box, have been note and used on this blog several times and now that and now Sriram Krishnan has produced this nice piece on currying in C# 2.0.

 

One area that seams to have been over looked so far is folding. A folding function is similar to a mapping function and mapping functions are supported by the framework library in version 2.0, expect it calls it ConvertAll. For example, the framework defines the following method on the List<T> class:

 

public List<TOutput> ConvertAll<TOutput>(Converter<T, TOutput> converter);

 

It’s not hard to see this can be used to map one list to another, like so:

 

List<string> stringList =

intList.ConvertAll<string>(

delegate(int intput) { return intput.ToString(); }

);

 

Folding is similar, except that where a mapping function applies a transformation to a list a folding function produces a summary. F# defines a folding function on this list type like so:

 

let rec fold f acc l =

  match l with

    [] -> acc

  | (h::t) -> fold_left f (f acc h) t 

 

This is a function that has 3 parameters; the fist one of these is function that takes two parameters, the second is the accumulator and the third is the list to be folded. This translates to C# something like:

 

public delegate TReturn AStarBToB<TInput, TReturn>

(TInput value1,

TReturn value2);

 

public static TAcc Fold<TList, TAcc>(

AStarBToB<TList, TAcc> funct,

TAcc acc,

IEnumerable <TList> list)

{

         foreach (TList item in list)

{

                   acc = funct(item, acc);

         }

         return acc;

}

 

This provides a very easy to create summaries of lists:

 

// intList = {1, 2, 3, 4, 5, 6}

int result1

= Fold(

delegate(int value1, int value2) { return value1 + value2; },

0,

intList

);

// result1 = 21

 

string result2 =

Fold(

delegate(int value1, string value2) { return value2 + ", " + value1; },

"",

intList);

// result2 = “, 1, 2, 3, 4, 5, 6”

 

 

And that’s it! It takes just one line of code to produce a summering of a list and the technique can be applied to any object that supports the IEnumberable<T> interface, which is quite a few.