I was reading F# language specification and I thought, wow this can be done in C# too. I was starting with the experiment on the first F# example which was simple square function.
#light let numbers = [1 .. 10] let square x = x * x let squares = List.map square numbers printfn "N^2 = %A" squares System.Console.ReadKey(true)
Now how do do this with C#? Well it can be done with several tekniques but I will use som Extension methods and lambda expressions which are new in the C# 3.0.
Let’s start with the simple example, return square of the int number.
static void Main(string[] args)
{
Func<int, int> firstsquare = x => x * x;
Console.WriteLine(firstsquare(2));
}
Hm, ok but not good enough. Let’s create an function that returns result.
static Func<int> SquareIT(int n)
{
return () => n * n;
}
static void Main(string[] args)
{
var funct = SquareIT(2);
Console.WriteLine(funct());
}
Ok, how do we do with the list of integers?
static void Main(string[] args)
{
var numbers1 = Enumerable.Range(1, 10);
Func<ienumerable><int>, IEnumerable<int>> secondSquare = items =>
{
var nr = new List<int>();
foreach (var item in items)
{
nr.Add(item * item);
}
return nr;
};
foreach (var nr in secondSquare(numbers1))
{
Console.WriteLine(nr);
}
}
That works but it is too much code, it has to be simple and clean like F#. Let us create Extension methods for that.
First extension method will take IEnumerables of some type and perform som action with them.
Second one (DoAction) will take IEnumerable and execute custom defined function.
public static class CustomExtensions
{
public static void ForEach<t>(this IEnumerable<t> items, Action<t> myaction)
{
foreach (var item in items)
myaction(item);
}
public static IEnumerable<u> DoAction<t, u>(this IEnumerable<t> items, Func<t, u=> f)
{
foreach (var item in items)
yield return f(item);
}
}
How we have F# look alike.
class Program
{
static void Main(string[] args)
{
var numbers = Enumerable.Range(1, 10);
Func<int, int> square = x => (x * x);
var squares = numbers.DoAction(square);
squares.ForEach(Console.WriteLine);
}
}
Wow, this was nice, but it can be do with even less code.
Enumerable.Range(1, 10).DoAction(x => x * x).ForEach(Console.WriteLine);
Here is the link to the source code for all examples.
![Reblog this post [with Zemanta]](http://img.zemanta.com/reblog_e.png?x-id=8d521627-eba1-4882-b2ea-9c2734e709a6)
[...] bookmarks tagged static Learn F# (FSharp) with C# or (learn C# with F# (FS… saved by 2 others umbumgo bookmarked on 09/15/08 | [...]
By: Pages tagged "static" on September 15, 2008
at 10:47 pm