I\'ve just recently discovered the functional programming style and I\'m convinced that it will reduce development efforts, make code easier to read, make software more main
I came up with a little trick recently to make lambdas, passed into my extension methods look more F# ish. Here it goes:
What I wanted to do was something like:
3.Times(() => Console.WriteLine("Doin' it"));
Now the extension method for that is easily implemented:
public static void Times(this int times, Action action)
{
Enumerable.Range(1, times).ToList().ForEach(index => action());
}
What I didn't like is that I am specifying the index here: ForEach(index => action()) although it never is used, so I replaced it with a _ and got ForEach(_ => action())
That's nice, but now I was motivated to have my calling code look similar
(I never liked the "()" at the beginning of the lambda expression), so instead of: 3.Times(() => ...); I wanted 3.Times(_ => ...);
The only way to implement this was to pass a fake parameter to the extension method, which never gets used and so I modified it like so:
public static void Times(this int times, Action action)
{
Enumerable.Range(1, times).ToList().ForEach(_ => action(byte.MinValue));
}
This allows me to call it like this:
3.Times(_ => Console.WriteLine("Doin' it"));
Not much of a change, but I still enjoyed, that it was possible to make that little tweak so easily and at the same time removing the "()" noise makes it much more readable.