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
foreach (float x in result)
Console.WriteLine("{0:f4}", x);
Console.ReadKey();
}
}
static class Extensions
{
public static IEnumerable
{
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
Map
new MapPredicate
foreach (float x in result) {
Console.WriteLine("{0:f4}",x);
}
}
static float Calc(float x) {
return x+2*x+x/2;
}
// using List
static IEnumerable
List
foreach (T item in data) {
items.Add(predicate(item));
}
return (IEnumerable
}
delegate R MapPredicate
}
}