Just sharing some of my inconsequential lunch conversations with you... RSS  

Saturday, July 14, 2007

Some of the some C#2, C#3, LINQ, Ruby, Python and Haskell code

Diditwithdotnet post this great article about a higher order calling. Here's the compilation of the final code (without the generic implementations) from the article comments.

C#2

static void Main()
{
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
IEnumerable<int> evens = Filter(numbers, IsEven);
IEnumerable<int> squares = Map<int, int>(evens, Square);
int sum = Reduce(squares, 0, Add);

Console
.WriteLine("Sum: {0}", sum);
}

C#3

static void Main()
{
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };

int sum = numbers.Filter(x => (x % 2) == 0).Map(x => x * x).Reduce(0, (x, y) => x + y);

Console
.WriteLine("Sum: {0}", sum);
}

LINQ
static void Main()
{
var numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };

var sum = (from n in numbers
where (n % 2) == 0
select n * n).Sum();

Console
.WriteLine("Sum: {0}", sum);
}

Python

sum([x*x for x in range(1,16) if x%2==0])

Ruby

(1..15).select { |x| x % 2 == 0 }.map { |x| x ** 2 }.inject { |x,y| x + y }


Haskell

sum (map (^2) (filter (\x -> x `mod` 2 == 0) [1..15]))


This post will not end with a conclusion nor a preference, because we are talking about a choice of flavor. In respect to this sample, all languages have the capability to solve it.

No comments:

Development Catharsis :: Copyright 2006 Mário Romano