The K-Combinator In C#
After browsing through Programmers.StackExchange I found an interesting post on combinators and how they applied to programming projects. It led me to some interesting links, most notably this post by Reg Braithwaite and saw the Ruby implementation of this as #tag and thought, why not recreate it in C#?
I ran into a few issues, which are due to C# type system, but I was eventually able to overcome them, thanks to the new dynamic keyword in C# 4.0. The definition of the K-combinator (taken from Wikipedia) is (K x) is the function which, for any argument, returns x, so we say". Basically, the K-combinator will take x and then do whatever but return x. So as long as the function doesn't modify x, we're good. Which brings me to the code:
public static class MyExtensions
{
public static dynamic k(this object me, Action<dynamic> action)
{
action(me);
return me;
}
}
We use Action
Here is an example:
int[] i = {1,2,3,4,5};
int[] b = i.k(x=> Console.WriteLine(x));
Pretty useless example, but this will write each int in i to the console before assigning i to b. However, returning the type of the item makes it an invaluable tool to have when logging while also making logging trivial.
November 8th, 2011 - 21:52
You don’t actually need anything .net 4.0 in order to do this; the same can be done using generics (and because you know the type at compile-time, you can usually let the compiler implicitly determine what the type is:
public static class MyExtensions
{
public static T k(this T input, Action action)
{
action(input);
return input;
}
}
and then to use it (note that I don’t need to specify T):
var myList = new List { “one”, “two”, “three” };
myList.k((l) =>
{
foreach (var item in l)
{
Console.WriteLine(item);
}
});
November 8th, 2011 - 21:56
Well, your comment engine doesn’t like generics
. With substitution for angle-brackets to accommodate for this, it would be like this:
The usage came across correctly.
November 8th, 2011 - 22:10
Thanks for your comment Mark. I was getting an error when trying to use generics and you have shown me why (I forgot to put the angle brackets and T around the k). Thanks!
November 8th, 2011 - 22:23
Sure thing; I have yet to find a use for the dynamic keyword, with the exception of COM interop. Any other circumstance that I have run into can be handled with generics
Glad I could help.