Archive

Archive for the ‘Uncategorized’ Category

Functional Programming in .Net

October 21, 2010 Leave a comment

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

Hello world

My name is Pieter De Rycke and for quite some time I wanted to start a technical blog about informatics. This blog will mainly be about DB2, C# and Java.

Who am I you will properly wonder? Well, I currently work in Brussels at the IT department of an insurance company; “AG Insurance”. I was graduated as civil engineer in computer science at the university of Ghent in Belgium and since recently I am also an IBM certified application developer for DB2 9.

Informatics is both a job and my hobby. I like reading in my free time about software design patterns, programming languages, database development, … I am also constantly busy writing small and larger software applications and experimenting with new technologies. At work, I am currently responsible for the KPI’s (Key Performance Indicators) and also for an in-house developed Cobol code quality checker (written in C#).

Categories: Uncategorized