Saturday, May 3, 2008

I've been spending alot of time recently on learning to use Ubuntu, as well as some dynamic "P*" languages like Pyton and PHP.
I must admit after spending so long in the world of the strictly staticly typed CLR, the switch to a language with such a lenient type system what quite a paradigm shift. My initial thought was something along the lines of, "OK, so you have classes with multiple inheritance. Cool. But tell me, what's the point of a class when you can shove whatever data you want into it? What's the use of a Point2D class when the x coordinate could be a collection?"
Misunderstandings aside, though, Python does offer one thing that I have recently fallen in love with. So much so that I decided to try my hand at pulling it off in C#. Not surprisingly, the actual functional code very similar, but it's just another testiment to the simplicity of Python's syntax vs that of other static languages.

/*
* test.cs
*
* A simple test of what list comprehension would be like in C# 3.0.
* Demonstrates performing the function ƒ(x) = (x+2*x+x/2)
* on a set of datapoints (4.2, 5.3, 6.2).
*/

namespace Test {
using System;
using System.Collections.Generic;

///
/// Small program intended to demonstrate manual (non-
///

static class Program {
static void Main() {
/*
* Python code for this code would be best approached with
* list comprehension one-liner:
* [x+2*x+x/2 for x in [4.2,5.3,6.2]]
* C# requires the helper function.
*/

var result =

new List(new float[] { 4.2f, 5.3f, 6.2f }).Map(x => x+2*x+x/2);

foreach (float x in result)

Console.WriteLine("{0:f4}", x);

Console.ReadKey();
}
}
static class Extensions

{

public static IEnumerable Map(this IEnumerable data, Func predicate)

{

foreach (T item in data) yield return predicate(item);

}

}
}

/*
* Curious about how this would be done in C# 2.0?
*/
namespace Test {
using System;
using System.Collections.Generic;

static class Program {
static void Main() {
// ugly, ugly, ugly.
IEnumerable result =
Map(new List(new float[] {4.2f,5.3f,6.2f}),
new MapPredicate(Calc));
foreach (float x in result) {
Console.WriteLine("{0:f4}",x);
}
}
static float Calc(float x) {
return x+2*x+x/2;
}
// using Lists, just to make it easy. Could be IEnumerables.
static IEnumerable Map(IEnumerable data, MapPredicate predicate) {
List items = new List(); // just to make it easy
foreach (T item in data) {
items.Add(predicate(item));
}
return (IEnumerable)items;
}
delegate R MapPredicate(T val);
}
}