2010
02.10

Over the past year the way I have developed code has been changing.  I have started to think differently about how I implement my code moving beyond traditional object orientated programming, making use of numerous functional concepts in my solutions.  I think this is due to the fact I have been trying to expose myself to as much code as possible across many different languages and platforms and somethings have just stuck.

One of the concepts I have came to know and love is that of a closure.  This was first exposed to me when C# started to incorporate more functional aspects into the language such as anonymous methods as first class citizens and later lambda expressions.

You might think this is quite odd that I specially call out closures & anonymous functions as being a functional concept, as closures are used heavily in dynamic languages due to the fact functions can be passed about as first class citizens. Passing functions about is the very nature of a functional language.

This is what Wikipedia has to say:

In computer science, a closure is a first-class function with free variables that are bound in the lexical environment. Such a function is said to be “closed over” its free variables. A closure is defined within the scope of its free variables, and the extent of those variables is at least as long as the lifetime of the closure itself.

The closure aspect is simple… the anonymous function is “Trapping” the local variable within the functions context.  That means the local variable in question will remain in scope for the duration of the lifetime of the anonymous function. In the examples below I declare anonymous functions called “closure” and I en-close around variable called “x”.

So here is an example of a closure in my language of the month Groovy:

def loopTo(n, closure)
{
	for(int i = 0; i < n; i++)
	{
		if(closure(i))
			println i
	}
}

//Our variable to be "Closed Over"
int x = 2

// I like this syntax of '{ }' to create an anonymous method,
// in Groovy we can use 'it' by default
// to reference an undefined but passed parameter.
loopTo(100, { it % 2 == x })

Now in JavaScript:

function loopTo(n, closure){
	for(i = 0; i < n; i++){
		if(closure(i)){
			alert(i);
		}
	}
}

//Our variable being "Closed over"
var x = 0;
// In JS we use the 'function' keyword and specify the parameter
loopTo(10, function(i){
	return i % 2 == x;
});

Now in C#:

static void Main(string[] args)
{
    //Our variable being "Closed over"
    int x = 0;

    // In C# we can use a lambda expression.
    LoopTo(100, num => num % 2 == x );
}

// As C# is strongly typed we define the expected
// expression type as a 'Func<param, return type>'
public static void LoopTo(int n, Func<int, bool> closure)
{
    for (int i = 0; i < n; i++)
    {
        if(closure(i))
            Console.WriteLine();
    }
}

And now in Scala:

// Scala is sweet we store our range rather than writing a loop,
// then iterate over the list passing the index 'i' into our closure.
def main(args: Array[String]) :Unit = {
    val range = 0.until(100);
    range.foreach(num =>  if(closure(num)) println(num) );
}
//Our variable to be "Closed over"
val x:int = 0
// Our function is defined like so
def closure(num : Int) = {  num %  2 == x;  }

We can copy the Scala way in C#.
We had to cheat a tad and write a funky ‘Until’ C# Extension Method.
This gives us a nice fluent way to create a range of integers stored as a list like so:

public static void Main(string[] args)
{
    //Extension method 'Until' defined later in this post
    var range = 0.Until(100);
    range.ForEach(num => { if(Closure(num)) Console.WriteLine(num); });
}
int x = 0;
// Our function definition in C#
private static readonly Func<int, bool> Closure = num => num % 2 == x;
public static class Extensions
{
    // Called like so: 0.Until(100)
    public static List<int> Until(this int lower, int upper)
    {
        var range = new List<int>();

        for (int i = lower; i <= upper; i++)
        {
            range.Add(i);
        }

        return range;
    }
}

This is what the code would look like without using anonymous functions:

private static void Main(string[] args)
{
    LoopTo(100);
}

public static void LoopTo(int n)
{
    int x = 0;
    for (int i = 0; i < n; i++)
    {
        //Our logic for filtering is tied to the control structure
        if (i % 2 == x)
            Console.WriteLine(i);
    }
}

As you can see the code is not only verbose but breaks a the DRY rule (Don’t Repeat Yourself).  Closures are powerful because they encapsulate what might almost be described as a “Strategy”. You have separated out the control structure from the logic. This is the strategy design pattern.

Closures become powerful when your reach the level of understanding that the encapsulation of logic allows for some really powerful composition of “Strategy”.

I find this really intriguing.  I like languages, and I love the idea creating domain specific languages / fluent APIs which make the definition of “Strategy” trivial to the end user.  By combining closures (via currying) or by logically appending delegates together we can create something truly powerful.

If you didn’t know what anonymous functions & closures were when you started to read this post, then hopefully you do now and maybe you can see why they are worth using.

Just some food for thought.

No Comment.

Add Your Comment

You must be logged in to post a comment.