Home > C#, Uncategorized > Functional Programming in .Net

Functional Programming in .Net

When I was developing my mobile port of Frozen Bubble, I noticed a behaviour that developers should be aware of when they do functional programming. At first I was wondered, but if you think a little bit about it is actually very logical.

I we have the following piece of c# functional code:

Func<IEnumerable<Func<int>>, int> Sum = (enumerable) =>
	{
		int sum = 0;
		foreach (Func<int> i in enumerable)
			sum += i();
		return sum;
	};

Func<int>[] data = new Func<int>[5];
for (int i = 0; i < data.Length; i++)
{
	data[i] = () => i * 2;
}

int result = Sum(data);
Console.WriteLine(string.Format("Result: {0}", result));

What do you think that the result will be?

1 * 2 + 2 * 2 + 3 * 2 + 4 * 2 + 5 * 2 = 30

You are wrong, the result is actually 50.

Because what computer is actually calculating:

5 * 2 + 5 * 2 + 5 *3 + 5 *4 + 5 * 5 = 50

The cause of this is the variable i, the variable is used after the for loop and at that moment the value of i is 5. So the Sum function receives 5 times the value 5. Very logical if you think about it, right?

So how can we fix it? You just have to declare a variable in the scope of the for loop. Then 5 different variables will be created, each containing a number from 1 to 5.

Func<IEnumerable<Func<int>>, int> Sum = (enumerable) =>
	{
		int sum = 0;
		foreach (Func<int> i in enumerable)
			sum += i();
		return sum;
	};

Func<int>[] data = new Func<int>[5];
for (int i = 0; i < data.Length; i++)
{
	int number = i
	data[i] = () => number * 2;
}

int result = Sum(data);
Console.WriteLine(string.Format("Result: {0}", result));

If we now execute the code we get the correct result 30.

Advertisements
Categories: C#, Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: