Search code examples
functional-programmingprogramming-languageslanguage-featurescode-injectionhomoiconicity

Are there any programming languages that consider functions as data structures that can be operated on?


I wrote the following function as a part of a jQuery plugin I am developing:

$.fn.append2 = function(collection, callback) {
    var $this = this;

    $.each(collection, function(key, value) {
        $this.append(callback ? callback(key, value) : value);
    });

    return this;
};

After testing a highly recursive function that heavily depended on .append2, I optimized .append2 to:

$.fn.append2 = function(collection, callback) {
    var $this = this;

    $.each(collection, callback
        ? function(key, value) { $this.append(callback(key,value)); }
        : function(key, value) { $this.append(value); }
    );

    return this;
};

While this code is more efficient in terms of speed, it still left me unsatisfied. I have, essentially, defined the same function twice:

function(key, value) { $this.append(callback(key,value)); }
function(key, value) { $this.append(value); }

And I wondered if there is any language that lets me defined the function only once as:

function(key, value) { $this.append(value); }

And then operate on it by replacing the argument to $this.append from value to callback(key, value). (And, no, not by manipulating strings. By manipulating the function itself.)

Is there any such programming language?


Solution

  • Any homoiconic language lets you do this do some degree or another. All of the Lisp languages let you build functions procedurally out of bits and pieces and then invoke them as normally. The Io language is rare in that I believe it will let you go the other way: given a function, you can pull apart its source code and manipulate it.