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
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:
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
Next comes:
We create a List of type T so that we can hold our results. We then loop through each item in the original Enumerable
Again, self explanatory, but since we want to keep it as generic as possible we will pass it back as an Enumerable
Here is an example of it in action:
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.