Java vs C#

As Jon Skeet pointed out in this excel­lent arti­cle on clo­sures, the strate­gies of cap­tur­ing the exe­cu­tion con­text which the behav­iour is bound to dif­fer­ent between Java and C#. C# cap­tures the vari­able itself, whereas Java cap­tures the value of the vari­able. To illus­trate the dif­fer­ence, here’s Jon’s orig­i­nal exam­ple in C#:

// First build a list of actions
List<Action> actions = new List<Action>();

for (int counter = 0; counter < 10; counter++)
{
    actions.Add(() => Console.WriteLine(counter));
}

// Then execute them
foreach (Action action in actions)
{
    action();
}

This code actu­ally writes 10 ten times instead of 0 to 9 because the con­text the actions are bound to is the vari­able counter, and at the time of exe­cu­tion the value of counter is 10 hence why each Action del­e­gate writes 10 instead of the value of counter at the time the Action del­e­gate was created.

The equiv­a­lent code in Java would print 0 to 9 because Java’s clo­sure imple­men­ta­tion cap­tures the value of the vari­able instead.

How­ever, as Jon pointed out, whilst Java’s imple­men­ta­tion is more intu­itive and eas­ier to under­stand (less WTF bugs), C#‘s imple­men­ta­tion is more flex­i­ble as you can just eas­ily mimic the effect of cap­tur­ing the variable’s value by using a local variable:

// First build a list of actions
List<Action> actions = new List<Action>();

for (int counter = 0; counter < 10; counter++)
{
    int copy = counter;
    actions.Add(() => Console.WriteLine(copy));
}

// Then execute them
foreach (Action action in actions)
{
    action();
}

Javas­cipt vs C# (Updated 16/01/2011)

Thanks for Jens for point­ing out my ini­tial incor­rect assess­ment (see com­ment), so I revised my test and used a more straight for­ward test using just one pri­vate variable:

function test () {
    var i = 10;
    
    // create the closure
    var func = function () { return i; };

    // 10
    alert(func());

    i = 11;
    // 11? or 10?
    alert(func());
}

The test here is sim­ple, we cre­ate a func­tion func which returns the value of the pri­vate vari­able i, whose value is then changed later on. If Javascript cap­tures the value of the vari­able then the sec­ond time func is invoke the alert mes­sage would still be 10, oth­er­wise it’ll be 11 which is the cur­rent value of i.

And the answer is?

.

.

.

Javascript cap­tures the ref­er­ence of the vari­able, and the sec­ond alert mes­sage is 11.

Ref­er­ences:

Jon Skeet’s arti­cle on closures

Arti­cle on Javascript closures

Share

In my last post I explained the dif­fer­ence between the tech­niques of Cur­ry­ing and Par­tial Appli­ca­tion, fol­low­ing on where there let me show you how you might apply these two tech­niques in F#, Javascript and C#.

F#

Start­ing with F#, being a func­tional lan­guage it makes cur­ry­ing and par­tial appli­ca­tion dead easy (con­sid­er­ing that they are pri­mar­ily func­tion pro­gram­ming con­cepts). Take for exam­ple, a sim­ple func­tion f which takes 3 parameters:

// base function f
let f a1 a2 a3 = a1 + a2 + a3

// partial function fixes two of the parameters
let partial a1 = f a1 5 10

// currying creates a china of functions each taking one parameter
let curry a1 =
    // create the next function in the chain which takes another parameter
    // and returns another function
    let curry' a2 =
        // the inner most function gives you the full application
        // of the original function
        let curry'' a3 = f a1 a2 a3
        curry''
    curry'

From the method sig­na­tures you can see how the result of the two approaches differs:

image

To use the par­tially applied func­tion par­tial:

partial 1 // returns 16

clearly, this is equiv­a­lent to calling

f 1 5 10 // returns 16

see­ing as the par­tial func­tion has fixed a2 and a3 to 5 and 10 respectively.

With the curry func­tion, how­ever, it’s slightly more interesting:

((curry 1) 5) 10 // returns 16

this way of invok­ing the chained func­tion in turn is in fact the same as:

curry 1 5 10 // returns 16

Javascript

Despite being con­sid­ered an object-oriented lan­guage, Javascript shares more than a hand­ful of sim­i­lar­i­ties with func­tion lan­guages, take its dynamic, loose type sys­tem, or the abil­ity to treat func­tion as objects, for instance. It’s there­fore of lit­tle sur­prise to see that you can imple­ment cur­ry­ing in Javascript with ease.

Here’s the exam­ple I used in the last post:

// original function that takes three parameters a1, a2 and a3
function f(a1, a2, a3) {
    return a1 + a2 + a3;
}

// curried function which takes one parameter at a time
function curry(a1) {
    // each stage takes another parameter and get you closer to the
    // full application of f
    return function (a2) {
        // but only with the inner most function do you actually get
        // the return value you wanted
        return function (a3) {
            return f(a1, a2, a3);
        };
    };
}

// partial applied function which takes one parameter and fixes
// the other 2
function partial(a1) {
    // a partially applied function of the original function f can
    // get you the full application straight away
    return f(a1, 5, 10);
}

curry(1)(5)(10); // returns 16
partial(1); // returns 16

C#

Yes, it’s pos­si­ble! Here’s a sim­ple exam­ple of how using the Func delegate:

// base function f
Func<int, int, int, int> f = ( a1, a2, a3 ) => a1 + a2 + a3;

// note that partial is a reserved keyword in C#
Func<int, int> partialf = a1 => f(a1, 5, 10);

Func<int, Func<int, Func<int, int>>> curryf = a1 => a2 => a3 => f(a1, a2, a3);

f(1, 5, 10);  // returns 16
partialf(1);  // returns 16
curryf(1)(5)(10);  // returns 16

Part­ing thoughts…

There is one impor­tant lan­guage fea­ture which all three lan­guages sup­port, which is what enables us to apply both cur­ry­ing and par­tial appli­ca­tion so effort­lessly – clo­sure. If you’re not famil­iar with the con­cept of clo­sure, it’s def­i­nitely worth spend­ing a bit of time famil­iarise your­self with it as it’s a very pow­er­ful (albeit often over­looked) lan­guage feature.

Ref­er­ences:

Wikipedia page on Currying

John Resig’s post on cur­ry­ing in JavaScript

Angus Croll – Curry: cook­ing up tastier functions

Angus Croll – par­tial: curry’s flashy cousin

Olivier Steel – Func­tional Javascript

SO ques­tion – what is the dif­fer­ence between cur­ry­ing and par­tial application

Lambda the Ulti­mate – Cur­ry­ing != Gen­er­al­ized Par­tial Application?!

Good blog posts which explains the dif­fer­ences between Cur­ry­ing and Par­tial Application

Did it with .Net – The Art of Currying

Share

Recently I have come across some really inter­est­ing ques­tions and debates around these two terms and how they dif­fer from one another. There seems to be wide­spread con­fu­sions with many exam­ples demon­strates one whilst intends another, and some sim­ply uses the terms interchangeably.

Whilst admit­tedly not being a func­tion pro­gram­ming expert, I’ve spent a bit of time scour­ing the web for infor­ma­tion from those who are and I think I’ve finally come to under­stand the dif­fer­ence between the two!

In case you’re not famil­iar with what Cur­ry­ing and Par­tial Appli­ca­tion means, here’s some quick def­i­n­i­tions for you.

Def­i­n­i­tions

Cur­ry­ing

Accord­ing to Wikipedia, cur­ry­ing is:

the tech­nique of trans­form­ing a func­tion that takes mul­ti­ple argu­ments in such a way that it can be called as a chain of func­tions each with a sin­gle argument.

This means for a given func­tion f, which takes three para­me­ters x, y, and z and returns R:

f(x, y, z) => R

once cur­ried it becomes:

curriedf(x) => g(y) => h(z) => R

When you sup­ply x to the cur­ried func­tion cur­riedf, you get back a new func­tion g, g takes a sin­gle para­me­ter and returns another func­tion h which also takes a sin­gle para­me­ter but this time returns R.

So to get the full appli­ca­tion of the orig­i­nal func­tion f, you need to call

curriedf(x)(y)(z).

With cur­ry­ing, para­me­ters must be sup­plied from left to right start­ing from the left-most parameter.

Par­tial Application

Again, bor­row­ing from Wikipedia, Par­tial appli­ca­tions refers to:

the process of fix­ing a num­ber of argu­ments to a func­tion, pro­duc­ing another func­tion of smaller arity.

This means for a given func­tion f, which takes three para­me­ters x, y, and z and returns R:

f(x, y, z) => R

If you fix the first para­me­ter x to 1 then you get another func­tion g that takes two para­me­ters and returns R:

g(y, z) => R    <=>    f(1, y, z) => R

Equally if you fix both x and y to val­ues 1 and 2 respec­tively then you get another func­tion h that takes one para­me­ter and returns R:

h(z) => R    <=>    f(1, 2, z) => R

Cur­ry­ing vs Par­tial Application

At first glance the sim­i­lar­i­ties are hard to miss, and one might be tempted to sug­gest (well, many have!) that they are two of the same thing or that one is sim­ply a spe­cial case of the other. How­ever, there are some cru­cial dif­fer­ences between the two which ulti­mately dic­tates their very dif­fer­ent appli­ca­tions in practice.

imageTo help you under­stand the dif­fer­ences, try and ignore the fact that both Cur­ry­ing and Par­tial Appli­ca­tion takes a func­tion and returns a func­tion with less input para­me­ters and instead think about the func­tion that’s returned (see image):

Cur­ry­ing

- when you curry a func­tion F, you get back a chain of func­tions that returns another func­tion at every stage, except the last func­tion in the chain

- you still have to apply all the nec­es­sary para­me­ters if you want to get the full appli­ca­tion of the orig­i­nal func­tion (i.e. R)

- you have to sup­ply para­me­ters one at a time to a chain of functions

- you have to sup­ply para­me­ters from left to right in the same order as the orig­i­nal func­tion F

Par­tial Application

- when you par­tially apply a func­tion F, you get back a func­tion that allows you to get the full appli­ca­tion (i.e. R) of the orig­i­nal func­tion F with less parameters

- you don’t have to sup­ply para­me­ters in any par­tic­u­lar order

Exam­ples

So, the main dif­fer­ence between cur­ry­ing and par­tial appli­ca­tion lies in the return type of the new func­tion pro­duced, let’s see how they dif­fer­en­ti­ate in prac­tice with a sim­ple exam­ple in Javascript:

// original function that takes three parameters a1, a2 and a3
function f(a1, a2, a3) {
    return a1 + a2 + a3;
}

// curried function which takes one parameter at a time
function curry(a1) {
    // each stage takes another parameter and get you closer to the
    // full application of f
    return function (a2) {
        // but only with the inner most function do you actually get
        // the return value you wanted
        return function (a3) {
            return f(a1, a2, a3);
        };
    };
}

// partial applied function which takes one parameter and fixes
// the other 2
function partial(a1) {
    // a partially applied function of the original function f can
    // get you the full application straight away
    return f(a1, 5, 10);

}

curry(1)(5)(10); // returns 16
partial(1); // returns 16

Part­ing thoughts…

In gen­eral, both tech­niques pro­duce reusable, help­ful func­tions which fixes some para­me­ters of the orig­i­nal func­tion. For exam­ple, with Cur­ry­ing the func­tion returned at each and every stage of the chain can be reused and poten­tially cre­ate a tree of functions:

image

though in prac­tice I can think of few exam­ples where you would require such level of reusable functions…

I’m of the opin­ion that Par­tial Appli­ca­tion has greater appli­ca­tions (not pun intended!) in solv­ing real world prob­lems. In fact, using Partial Appli­ca­tion is some­thing we’ve all done before – e.g. take a gen­eral pur­pose func­tion which needs lots of para­me­ters and make a more high level func­tion out of it by fix­ing some para­me­ters with sen­si­ble defaults:

// base method which provides a way to encapsulate common logic, but
// needs a number of parameters in order to 'tune' its behaviour
// NOTE: this C# code won't compile, it's just to illustrate a common
// pattern of using partial application
public void DoFileIoOperation(
    FileReadWriteMode mode,
    string path, string content,
    FileOverwriteMode overwriteMode)
{
    …
}

// high level methods more useful to anyone who's trying to get things done
public void DoFileRead(string path)
{
    DoFileIoOperation(
        FileReadWriteMode.Read, path, null, FileOverwriteMode.None);
}

public void DoFileWrite(string path, string content)
{
    DoFileIoOperation(
        FileReadWriteMode.Write, path, content, FileOverwriteMode.Overwrite);
}

Also, the fact that you don’t need to sup­ply each and every para­me­ters one at a time, in a par­tic­u­lar order makes Par­tial Appli­ca­tion eas­ier to apply in prac­tice. As much as one would love to stay ‘pure’, it’s sim­ply far more prag­matic to repack­age the orig­i­nal func­tion sig­na­ture and fix mul­ti­ple para­me­ters in one go!

Share

I saw this in last month’s .Net mag­a­zine and thought it was pretty cool and worth­while sharing.

With­out giv­ing away too much of the intri­ca­cies (see­ing as this is not my own work), this tech­nique essen­tially boils down to using Javascript to append a <span> ele­ment to mask over each of the links on the hover event. The <span> ele­ments are set with 0 width ini­tially, on the hover event, an ani­ma­tion is played to change the width to match that of the <a> ele­ments they’re mask­ing, a reverse ani­ma­tion is played when mouse moves out of the <a> elements.

The HTML for the page is sim­ple enough:

<div id="wrapper">
<h1>Link swipe Demo</h1>
    <nav>
        <ul>
            <li><a href="#">Home</a></li>
            <li><a href="#">Previous</a></li>
            <li><a href="#">Next</a></li>
        </ul>
    </nav>
</div>

Some sim­ple CSS is used to style the links and the <span> ele­ments but the main thing is really is this linkswipe func­tion which is called once the doc­u­ment fin­ishes load­ing, I’ve filled in some more com­ments so hope­fully it should be fairly self-explanatory:

function linkswipe() {
    $("li a").each(function (i) {
        // keep a reference to the current <a> element
        var a = $(this);

        // get the title of the link
        var title = a.html();

        // get the width of the element
        var aWidth = a.outerWidth();

        // add a span with the title of the link to mask over the link for the hover event
        // set its initial width and display so that it's invisible
        a.append("<span class='mask' style='width: 0; display: none;'>" + title + "</span>");

        // keep a reference to the new span element
        var span = a.find("span");

        // add the hover event handler
        a.hover(function () {
            // stop any ongoing animation to stop the animation from flickering
            span.stop();

            // expand the width of the span to completely cover the <a> element
            // when the mouse moves over
            span.show().animate({
                width: aWidth + "px"
            }, 200);
        }, function () {
            // do a fade off animation when mouse moves off
            span.animate({
                width: "0px"
            }, 400, function () {
                span.hide(); // hide the span once the fade animation completes
            });
        });
    });
}

Here’s a quick demo of the effect, just hover over the links to see it in action:

Share

The other day I put up a post with some quick bul­let points about objects in javascript to help some­one from a sta­tic, strongly typed lan­guage (like C# or Java) back­ground under­stand javascript’s dynamic and loose type sys­tem. One impor­tant thing I haven’t talked about yet is the way inher­i­tance work in javascript, which again, is very dif­fer­ent from those found in C# or Java.

Most object ori­ented lan­guages like C# and Java use classes to define types, which are basi­cally blue­prints for cre­at­ing objects, this approach to inher­i­tance is referred to as clas­si­cal inher­i­tance. Javascript on the other hand, has no classes, instead objects inherit from other objects, this approach is referred to as pro­to­typal inher­i­tance.

Con­struc­tor functions

You can use func­tions, which them­selves are objects to act as con­struc­tors and pro­vide blue­prints for cre­at­ing objects:

function Person(name, age) {
    // properties
    this.Name = name;
    this.Age = age;

    // methods
    this.sayHello = function () {
        return "Hello, my name is " + this.Name + "!";
    }
}

This cre­ates a new object Person.prototype, which all new Per­son objects will inherit from. You can then use the new oper­a­tor to cre­ate a new Per­son object using this constructor:

var person = new Person("John", 10);

The per­son object inher­its all the mem­bers (prop­er­ties and func­tions) that are defined by the con­struc­tor func­tion above, as can be seen in Chrome’s debug­ger (CTRL+SHIFT+J):

image

Dynam­i­cally mod­i­fy­ing the prototype

It is pos­si­ble to make changes to Person.prototype object out­side of its con­struc­tor func­tion, to add a say­Bye func­tion to the Person.prototype object:

Person.prototype.sayBye = function (recipient) {
    return "Good bye, " + recipient + "!";
}

Once defined, this new func­tion will be avail­able on all Per­son objects, even if they were cre­ated prior to the new function:

var goodbyeMsg = person.sayBye("Yan"); // returns "Good bye, Yan!"

Under­stand­ing how mem­bers are looked up

This is all the code we have writ­ten so far:

function Person(name, age) {
    // properties
    this.Name = name;
    this.Age = age;

    // methods
    this.sayHello = function () {
        return "Hello, my name is " + this.Name + "!";
    }
}

var person = new Person("John", 10);

Person.prototype.sayBye = function (recipient) {
    return "Good bye, " + recipient + "!";
};

var goodbyeMsg = person.sayBye("Yan"); // returns "Good bye, Yan!"

If you run the code to the end, you will see the say­Bye func­tion we added at the end of the example:

image

It falls under the per­son object’s __proto__ mem­ber rather than on the object itself (as is the case for the con­struc­tor defined mem­bers – Name, Age and the say­Hello func­tion) but it’ll still be acces­si­ble directly on the per­son object.

When access­ing a mem­ber on an object, Javascript will check in that object first, if the mem­ber is not found it will then fol­lows the inher­i­tance chain until either the mem­ber is found or it will return unde­fined if it has exhausted all the objects on the inher­i­tance chain.

In order for javascript to keep track of this chain and fig­ure out where next to look for a mem­ber, an inter­nal prop­erty __proto__ is used to point to the next object in the chain. Because every object is ulti­mately inher­ited from Object, it’ll be at the top of every object’s inher­i­tance chain and the last object you’ll be able to fetch if you con­tin­u­ously invoke the __proto__ mem­ber before you get unde­fined returned:

myObj.__proto__.__proto__….

Extend­ing objects

Nor­mally to extend an object you need to per­form a two step process:

1. Invoke the base constructor

function Employee(name, age, salary) {
    // equivalent to calling base(name, age) in C#
    // this invokes the base class's constructor on the current object
    Person.call(this, name, age);

    // new property and method
    this.Salary = salary;
    this.reportSalary = function () {
        return "Hi, my name is " + this.Name + ", my salary is " + this.Salary + ".";
    }
}

As you can see, this invokes the Per­son con­struc­tor func­tion (see above) on the cur­rent object, if you try to cre­ate a new object using this constructor:

var employee = new Employee("Jane", 20, 12000);

this is what the object looks like:

image

Notice any­thing miss­ing? What hap­pened to the say­Bye func­tion we added to the Per­son object out­side of its constructor?

Well, because the say­Bye func­tion is not defined in the Per­son object’s con­struc­tor func­tion and all we’ve done so far is to invoke that func­tion to set up some prop­er­ties and func­tions for a new Employee object so of course it won’t include any­thing that’s dynam­i­cally added to the object out­side of its con­struc­tor function.

2. Set up the inher­i­tance relationship

This sec­ond step is sim­ple but cru­cial, this is how you set up the ‘rela­tion­ship’ between the Per­son and Employee objects:

// make Employee inherit from Person
Employee.prototype = new Person();

Doing this tells Javascript to use Per­son as the pro­to­type for Employee, i.e. pro­to­typal inheritance’s way of say­ing using Per­son as super­class to Employee. Now that you’ve done this step, if you try to cre­ate a new Employee object now this is what your object looks like:

var employee = new Employee("Jane", 20, 12000);

image

Check­ing an object’s inher­i­tance chain

You can check if an object appear in another object’s inher­i­tance chain using the isPro­to­typeOf func­tion. For exam­ple, using the Per­son and Employee con­struc­tor func­tions (remem­ber, they are objects) defined above:

var person = new Person("John", 10);
var employee = new Employee("Jane", 20, 10000);

Employee.prototype.isPrototypeOf(person); // false
Person.prototype.isPrototypeOf(person); // true
Object.prototype.isPrototypeOf(person); // true

Employee.prototype.isPrototypeOf(employee); // true
Person.prototype.isPrototypeOf(employee); // true
Object.prototype.isPrototypeOf(employee); // true

Where the inher­i­tance tech­nique fails

Whilst the method of extend­ing an object above works it does have an implicit require­ment for the par­ent object’s con­struc­tor func­tion to allow a para­me­ter­less con­struc­tor to work, which can be a prob­lem in cer­tain situations.

For instance, if the Per­son object’s con­struc­tor explic­itly requires the para­me­ters name and age to be specified:

function Person(name, age) {
    if (!name || !age) {
        throw new Error("A person must have a name and age");
    }

    // properties
    this.Name = name;
    this.Age = age;

    // methods
    this.sayHello = function () {
        return "Hello, my name is " + this.Name + "!";
    }
}

In sit­u­a­tions like this, this line will except:

Employee.prototype = new Person(); // Uncaught Error: A person must have a name and age

Other inher­i­tance techniques

Besides the tech­nique I men­tioned above, here are two other ways to cre­ate object inher­i­tance for your reference.

Dou­glas Crockford’s ini­tial­ize technique

In Dou­glas Crockford’s post here he wrote about a dif­fer­ent tech­nique on ini­tial­iz­ing objects, in his last update in 2008 this is his pre­ferred method:

if (typeof Object.create !== 'function') {
    Object.create = function (o) {
        function F() { }
        F.prototype = o;
        return new F();
    };
}

and to use it, sup­pose we have already cre­ated an Employee object called employee, to cre­ate another just like it:

var employee2 = Object.create(employee);

This tech­nique is more about cloning an exist­ing object, employee2 will there­fore inherit all of employee’s cur­rent state:

image

MooTools

MooTools is a mod­u­lar Object-Oriented Javascript frame­work, it includes a Class con­struc­tor func­tion which includes some nice fea­tures such as:

  • Extends – allows you to spec­ify a base class which to extend from
  • Imple­ments – allows you to spec­ify one or more classes to adopt prop­er­ties from (think imple­ment­ing an interface)

So using MooTools, this is how you can cre­ate the Per­son and Employee classes:

// create a new Person class
var Person = new Class({
    initialize: function (name, age) {
        // properties
        this.Name = name;
        this.Age = age;

        // methods
        this.sayHello = function () {
            return "Hello, my name is " + this.Name + "!";
        }
    }
});

// add the sayBye function to the Person class
Person.implement({
    sayBye: function (recipient) {
        return "Good bye, " + recipient + "!";
    }
});

// create a new Employee class which inherits from the Person class
var Employee = new Class({
    Extends: Person,
    initialize: function (name, age, salary) {
        this.parent(name, age); // calls initialize method of Person class
        this.Salary = salary;

        // new property and method
        this.Salary = salary;
        this.reportSalary = function () {
            return "Hi, my name is " + this.Name + ", my salary is " + this.Salary + ".";
        }
    }
});

var person = new Person("John", 10);
var employee = new Employee("Jane", 20, 12000);

This is how the per­son and employee objects look in the Chrome Debugger:

image

Ref­er­ences:

Dou­glas Crock­ford on Pro­to­typal Inheritance

MooTools Class examples

Share