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.<?xml:namespace prefix = o ns = “urn:schemas-microsoft-com:office:office” />/o:p

 /o:p

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:/o:p

 /o:p

public List<TOutput> ConvertAll<TOutput>(Converter<T, TOutput> converter);/o:p

 /o:p

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

 /o:p

List<string> stringList = /o:p

intList.ConvertAll<string>(/o:p

delegate(int intput) { return intput.ToString(); }/o:p

);/o:p

 /o:p

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:/o:p

 /o:p

let rec fold f acc l = /o:p

  match l with /o:p

    [] -> acc/o:p

  | (h::t) -> fold_left f (f acc h) t  /o:p

 /o:p

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:/o:p

 /o:p

public delegate TReturn AStarBToB<TInput, TReturn>/o:p

(TInput value1, /o:p

TReturn value2);/o:p

 /o:p

public static TAcc Fold<TList, TAcc>(/o:p

AStarBToB<TList, TAcc> funct, /o:p

TAcc acc, /o:p

IEnumerable <TList> list)/o:p

{/o:p

         foreach (TList item in list)/o:p

{/o:p

                   acc = funct(item, acc);/o:p

         }/o:p

         return acc;/o:p

}/o:p

 /o:p

This provides a very easy to create summaries of lists:/o:p

 /o:p

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

int result1 /o:p

= Fold(/o:p

delegate(int value1, int value2) { return value1 + value2; }, /o:p

0, /o:p

intList/o:p

);/o:p

// result1 = 21/o:p

 /o:p

string result2 = /o:p

Fold(/o:p

delegate(int value1, string value2) { return value2 + “, ” + value1; }, /o:p

”“, /o:p

intList);/o:p

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

 /o:p

 /o:p

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./o:p