<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" /><o:p>
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:
// intList = {1, 2, 3, 4, 5, 6}
string result2 =
Fold(
delegate(int value1, string value2) { return value2 + ", " + value1; },
"",
intList);
// result2 = “, 1, 2, 3, 4, 5, 6”
string result3 =
Fold(
delegate(int value1, string value2) { return value1 + ", " + value2; },
"",
intList);
// result3 = “6, 5, 4, 3, 2, 1,”
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:
public static TAcc FoldLeft<TList, TAcc>(
AStarBToB<TList, TAcc> funct,
TAcc acc,
IList<TList> list)
{
for (int index = 0; index < list.Count; index ++ )
{
acc = funct(list[index], acc);
}
return acc;
}
public static TAcc FoldRight<TList, TAcc>(
AStarBToB<TList, TAcc> funct,
TAcc acc,
IList<TList> list)
{
for (int index = list.Count - 1; index >= 0 ; index--)
{
acc = funct(list[index], acc);
}
return acc;
}
So here we can that processing a list of integers in different direction, will give different results:
// intList = {1, 2, 3, 4, 5, 6}
double result4 =
FoldLeft(
delegate(int value1, double value2) { return value1 / value2; },
1d,
intList);
// result4 = 3.2
// intList = {1, 2, 3, 4, 5, 6}
double result5 =
FoldRight(
delegate(int value1, double value2) { return value1 / value2; },
1d,
intList);
// result5 = 0.3125
Download the source for all these samples here.