Closures in Clojure and C#

So one of the ways I learn a new language is to take new things from the new language and port them back into the old, familiar one. Eventually, I’ll port an entire application (even though that app may be very small) from the old to the new. I find that I learn things much better this way. Tonight’s example is closures in Clojure and C#.

In Clojure, you can do this:

(defn make-greeter [greeting-prefix]
(fn [username] (str greeting-prefix ", " username)))

This basically creates a closure around greeting-prefix that can be used to create custom ways to greet people. For example

(defn hello-greeting (make-greeter "Hello"))

creates a closure than can be called with

(hello-greeting "Brett")

and get “Hello, Brett”

You can do the same thing in C# though it’s a little more work because it’s a statically typed language. In C#, a small console app looks like this:

namespace ClosureToy
    class Program
        static void Main(string[] args)
            //Class1 one = new Class1();
            Func hello = MakeGreeter("Hello");
            Func aloha = MakeGreeter("Aloha");


        static Func MakeGreeter(string greetingPrefix)
            return (username) => String.Format("{0}{1}{2}", greetingPrefix, ", ", username); ;

The MakeGreeter function is a closure around greetingPrefix that allows you to create custom greeter functions on the fly. Essentially, it’s doing the same thing as the Clojure code as you can see from the main body of the console app where it creates two greeter functions on the fly, one that says hello and one that says aloha. Closures make it easier to abstract common pieces of code in your applications.

Leave a Reply

Your email address will not be published. Required fields are marked *