Map in ruby and C#
20 April 2008
Using C# 3.0's new extension methods, it's now possible to implement Map, which is pretty awesome.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FunctionalMap
{
static class Program
{
static IEnumerable<U> Map<T, U>(this IEnumerable<T> s, Func<T, U> f)
{
foreach (var item in s)
yield return f(item);
}
static int SumOfSquares(IEnumerable nums)
{
return nums.Map(delegate(int x) { return x*x; }).Sum();
//return nums.Map(x => x * x).Sum(); // <== same as above
}
static void Main(string[] args)
{
int[] xs = new int[] { 1, 2, 3, 4, 5 };
Console.WriteLine(Program.SumOfSquares(xs));
Console.ReadLine();
return;
}
}
}
The Sum() function is a built-in extension, while Map is one you'd add yourself. The this in front of the first parameter signifies an extension method.
In Ruby, the situation is the opposite: map (alias for collect) is built-in, but sum isn't.
sum = 0
xs = [1,2,3,4,5]
xs.map { |n| n*n }.each { |n| sum += n }
puts sum
The C# version requires more syntax but it's a welcome addition that I hope we end up using at work soon.
