Don't Break The Build Software development articles and tutorials

8Dec/110

The B-Combinator In C#

My last post was implementing the K combinator in C# as an extension method. Today, I am moving on to the B-Combinator. The B combinator has the form:


B f g x = f(g(x))

The code that I will show can be used on any collection that implements the IEnumerable interface. Here we go:

public static IEnumerable<T> b<T>(this IEnumerable<T> me, Func<T, T> f, Func<T, T> g)
{
    List<T> output = new List<T>();
    foreach (var i in me)
    {
        output.Add(f(g(i)));
    }

    return output.AsEnumerable<T>();
}



So let's review this, shall we?

First off, it is important to note which namespaces we will need to include (I hate when I have to google or guess since the writer doesn't include them in the tutorial/post). This one is nice and easy and only requires:

  • System.Collections.Generic
  • System.Linq

Now, to examine the code. The first line is:

public static IEnumerable<T> b<T>(this IEnumerable<T> me, Func<T, T> f, Func<T, T> g)



With this we make use of the polymorphism in C# and have the type this is available on be IEnumerable (which includes just about all, if not all, of the generic collections). Next you will notice:



This is declaring a delegate that takes type T and returns type T. Since there needs to be passing of a result from function g to function f, we need to use Funcinstead of Action, which is what we used in the K combinator. This also means that the return type must be the same type as the input.

Next comes:

List<T> output = new List<T>();
foreach (var i in me)
{
    output.Add(f(g(i)));
}
return output.AsEnumerable<T>();



We create a List of type T so that we can hold our results. We then loop through each item in the original Enumerable (me) and apply f(g(i)) to them while adding it to the output list. This part should be self-explanatory. We then finish it up with:

Again, self explanatory, but since we want to keep it as generic as possible we will pass it back as an Enumerable type instead of a list.

Here is an example of it in action:

int[] numbers = { 1, 2, 3, 4, 5 };
numbers.b(x => (x * 5), x => (x - 3));

/* Output: -10, -5, 0, 5, 10 */


While the B combinator has a little more complexity than the K combinator, it is still a cinch to implement in C#. Please stay tuned because I will definitely be updating this with more of the combinators.


Tagged as: , Leave a comment
Comments (0) Trackbacks (0)

No comments yet.





Leave a comment

No trackbacks yet.