Tuesday, March 8, 2016

JavaScript: Identity Combinator

The identity combinator is a function that takes a function and returns a function with identical behavior. By itself, this is kind of useless, but it can be used as the building block for combinators.

Here is a super simple version of the identity combinator:

var identityCombinator = (fn) => {
    return fn;
}

Pretty meaningless. Let's make it do the same thing only with more code!

var identityCombinator = (fn) => {
    return function(...args) {
        return fn.apply(this,args);
    }
}

Do a tiny refactoring and add some comments

var identityCombinator = (fn) => {
    // I can put stuff in here the will be preserved between calls
    // and is accessible by the function below
    return function(...args) {
        // I can do stuff here
        var returnValue = fn.apply(this,args);
        // I can do stuff here
        return returnedValue
    }
}

I can now use this as a base for writing more interesting combinators. Let's create a trivial logging example.

var log = (fn, loggingComponent) => {
    return function(...args) {
        loggingComponent.doArgLogging(arguments);
        var returnValue = fn.apply(this,args);
        loggingComponent.doReturnLogging(returnValue);
        return returnedValue
    }
}

Now, for any arbitrary function I can do this:

arbitraryFunction = log(arbitraryFunction, loggingComponent);

Combinators give you nice encapsulation and reuse benefits that would otherwise be difficult to get. The Lambda Calculus has been around for almost 80 years. It has existed as a kind of mathy notion of computation that is slowly working it's way into mainstream. IMHO, we should begin to think about increasing the expressivity of our code using combinators.

No comments:

Post a Comment