<?xml:namespace prefix = o ns = “urn:schemas-microsoft-com:office:office” />

Last time we took a look at folding. It may not have escaped the readers notice that some operations are dependent on the order the parameters are processed. For instance in the string concatenation example the order the parameters are processed affects the order they appear in the output string. But in this example to reverse the order of result does not actually require access to the list in both directions, it is only necessary to reverse the order that the parameters are concatenated in:/o:p

 /o:p

// intList = {1, 2, 3, 4, 5, 6}/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

string result3 = /o:p

Fold(/o:p

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

”“, /o:p

intList);/o:p

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

 /o:p

However some operations such as division are trickier and process the list in different directions will give different results; we can just get away with process the parameters differently. So here we need to define a fold left and fold right functions:/o:p

 /o:p

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

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

TAcc acc, /o:p

IList<TList> list)/o:p

{/o:p

         for (int index = 0; index < list.Count; index ++ )/o:p

         {/o:p

                   acc = funct(list[index], acc);/o:p

         }/o:p

         return acc;/o:p

}/o:p

 /o:p

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

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

TAcc acc, /o:p

IList<TList> list)/o:p

{/o:p

         for (int index = list.Count - 1; index >= 0 ; index–)/o:p

         {/o:p

                   acc = funct(list[index], acc);/o:p

         }/o:p

         return acc;/o:p

}/o:p

 /o:p

So here we can that processing a list of integers in different direction, will give different results:/o:p

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

double result4 = /o:p

FoldLeft(/o:p

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

1d, /o:p

intList);/o:p

// result4 = 3.2/o:p

 /o:p

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

double result5 = /o:p

FoldRight(/o:p

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

1d, /o:p

intList);/o:p

// result5 = 0.3125/o:p

 /o:p

Download the source for all these samples here./o:p

/o:p