Don't Break The Build Software development articles and tutorials

2Nov/114

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:
[code]]czoxOTg6XCINCiAgICBwdWJsaWMgc3RhdGljIGNsYXNzIE15RXh0ZW5zaW9ucw0KICAgIHsNCiAgICAgICAgcHVibGljIHN0YXRpYyB7WyYqJl19ZHluYW1pYyBrKHRoaXMgb2JqZWN0IG1lLCBBY3Rpb248ZHluYW1pYz4gYWN0aW9uKQ0KICAgICAgICB7DQogICAgICAgICAgICBhY3tbJiomXX10aW9uKG1lKTsNCiAgICAgICAgICAgIHJldHVybiBtZTsNCiAgICAgICAgfQ0KICAgIH0NClwiO3tbJiomXX0=[[/code]

We use Action because we don't know what the type will be until compile time, but also, since there is going to be no return value, we don't need to use Func. We also know that all objects in C# inherit from System.Object and that everything is an object, so we use the type "me" as object, which means this method will be available to everything. With a return type of dynamic, it will also allow us to operate on any type that could be imagined. Note, that using T (for generic type) instead of dynamic will result in a compiler error as the type must be known at compile time. Needless to say, this is a neat little function that can be used for logging, among other things, but is only possible in .NET 4.0.

Here is an example:

[code]]czo3MDpcIg0KaW50W10gaSA9IHsxLDIsMyw0LDV9Ow0KDQppbnRbXSBiID0gaS5rKHg9PiBDb25zb2xlLldyaXRlTGluZSh4KSk7DQp7WyYqJl19XCI7e1smKiZdfQ==[[/code]

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.


Tagged as: , Leave a comment
Comments (4) Trackbacks (0)
  1. 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);
    }
    });

    • Well, your comment engine doesn’t like generics :-) . With substitution for angle-brackets to accommodate for this, it would be like this:

      
          public static class MyExtensions
          {
              public static T k{LEFT_ANGLE}T{RIGHT_ANGLE}(this T input, Action{LEFT_ANGLE}T{RIGHT_ANGLE} action)
              {
                  action(input);
                  return input;
              }
          }
      

      The usage came across correctly.

      • 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!

        • 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.





Leave a comment

No trackbacks yet.