That great minds think alike is a reflection of the fact that certain ideas have an appeal that is, if not innate, then compelling in context. Hence the use of dot notation in the creation of domain specific languages in Javascript: dot is a handy way of succinctly representing a computation with a context. This is closely related to monads, and many javascript libraries relying heavily on dot for syntactic sugar are very closely related to one monad or another (eg _ to the sequence monad, promises to a sort of continuation monad, etc).

(NB. Much of the code here is inspired by a pointfree/function level programming library I am building for Javascript called puff , available here);

What I aim to prove today is that function composition subsumes the functionality of dot in this regard and that we can embed in Javascript a powerful, succinct function-level programming language in the vein of APL, J, or K/Q based primarily on function composition.

First of all, the traditional definition of function composition:

/** compose functions * return a new function which applies the last argument to compose * to the values passed in and then applies each previous function * to the previous result. The final result is returned. */ function compose(){ var fs = Array.prototype.slice.call(arguments, 0, arguments.length); return function(){ var inArgs = Array.prototype.slice.call(arguments, 0, arguments.length); var i = fs.length-1; var res = fs[i].apply(null, inArgs); i = i - 1; for(; i>=0; i = i - 1){ res = fs[i](res); } return res; } }

This version of compose allows the programmer to pass in an unlimited number of functions and returns a new function which takes any number of arguments and then threads the result through all the previous functions, transforming it each time, starting with the last function and ending with the first.

This order of composition is inspired by the fact that the function in a traditional application expression precedes the argument (on the left), transforming:

f(h(g(o)))

“naturally” to

compose(f,h,g)(o)

or, if succinctness is of interest:

var c = compose; c(f,h,g)(o)

In this way we drop a few parentheses and hopefully express more clearly our intent.

Of course we might not wish to apply our composition immediately: we can produce useful functions via composition, after all.

var plusOne(x){ return x + 1 }; var timesTen(x){ return x*10 }; var plusOneTimesTen = c(timesTen, plusOne);

We can now apply plusOneTimesTen to as many values as we wish. Handy. However, now our intuition about naming and the order of the arguments to c are at odds. Hence, we introduce:

function rCompose(){ return compose.apply(null, Array.prototype.slice.call(arguments, 0, arguments.length).reverse()); } var r = rCompose;

So that the above looks a bit nicer:

var plusOne(x){ return x + 1 }; var timesTen(x){ return x*10 }; var plusOneTimesTen = r(plusOne, timesTen);

This reverse composition operator is similar in many respects to dot in javascript except we have abstracted away this , to which each method invocation is implicitly addressed in a dot chain. In addition, instead of simple method names, each element in our r list can be any Javascript expression which evaluates to a function. This means that we can denote any sequence of operations this way without worrying whether or not they have been associated with any particular Javascript object.

With the right set of primitives and combinators, r forms the basis of a powerful, succinct function level programming language in which we can build, among other things, expressive domain specific languages. Or with which we can rapidly denote complex operations in a very small number of characters.

Well, first of all we want the bevy of basic functions:

plus, minus, div, times, split, join, toString, index, call, apply, etc, array

These behave as you might expect, more or less (eg, some plausible implementations to give you the spirit of the idea):

function plus(){ var out = arguments[0]; Array.prototype.slice.call(arguments, 1, arguments.length) .forEach(function(x){ out = out + x; }); return out; } function index(o, i){ return o[i]; } function call(f){ return f.apply(null, Array.prototype.slice.call(arguments, 0, arguments.length)); }

You get the idea.

Astute readers may realize that our composition function seems to only work with functions of a single argument. Remedying this will be a matter of some interest. The simplest approach is to provide for partial application:

/** partially fix arguments to f (on the right) * */ function partialRight(f /*... fixedArgs */){ var fixedArgs = Array.prototype.slice.call(arguments, 1, arguments.length); var out = function(/*... unfixedArgs */){ var unfixedArgs = Array.prototype.slice.call(arguments, 0, arguments.length); return f.apply(null,unfixedArgs.concat(fixedArgs)); } out.toString = function(){ return "partialRight("+f.toString()+","+fixedArgs.join(",")+")"; } return out; } /** partially fix arguments to f (on the left) * */ function partialLeft(f /*... fixedArgs */){ var fixedArgs = Array.prototype.slice.call(arguments, 1, arguments.length); var out = function(/*... unfixedArgs */){ var unfixedArgs = Array.prototype.slice.call(arguments, 0, arguments.length); return f.apply(null,fixedArgs.concat(unfixedArgs)); } out.toString = function(){ return "partialLeft("+f.toString()+","+fixedArgs.join(",")+")"; } return out; }

These functions (they might be adverbs in J ) take a function and a set of values and return a new function, “fixing” the arguments to the left or right of the argument list, depending on whether we’ve used partialLeft or partialRight .

Its handy to introduce the following bindings:

var p_ = partialRight; var _p = partialLeft;

I hope these are relatively mnemonic (Javascript unfortunately isn’t an ideal environment for very short, expressive names).

We can get a surprising amount of mileage out of these ingredients already. For instance, a function to remove break tags from a string and replace them with newlines (sort of contrived):

var remBreaks = r(p_(split,'<br>'),p_(join,'

'));

compared to

function remBreaks(s){ return s.split('<br>').join('

'); }

(NB. If split and join are written as curried functions, as they are in puff, the above is a little shorter:

var remBreaks = r(split('<br>'),join('

'));

Providing a meaningful default currying (which args should be applied first) is a little tricky, though.)

Going Further

The above example demonstrates that we can do some handy work with r as long as it involves simply transforming a single value through a set of functions. What may not be obvious here is that a determined programmer can denote any computation whatsoever this way, even if multiple values might need to be kept around and transformed.

Consider the function which I will call augment or au :

/** given a function f and a additional functions gs * return a new function h which applies each g * to its single argument and then applies f to the * resulting list of values */ function augment(f /*... gs*/){ var gs = Array.prototype.slice.call(arguments, 1, arguments.length); var out = function(a){ return f.apply(null, gs.map(function(g){ return g(a); })); } out.toString = function(){ return "augment("+f.toString()+","+gs.map(toString).join(", ")+")"; } return out; }

And a nice default currying of index :

function index(o, ix){ if(typeof ix === "undefined"){ var realIx = o; return function(o){ return o[realIx]; } } else { return o[ix]; } } var ix = index;

Now:

var fullName = augment(join(' '), ix('first'), ix('last'));

Such that:

fullName({first:'Ronald',last:'Reagan'}) -> "Ronald Reagan"

What have we just accomplished? We’ve demonstrated that we can take an arbitrary function of any arity and automatically transform it into a function which reads its input arguments from a single object. The sort of single object which we might be passing from function to function via r .

Putting it Together

To go further we need to add just one more utility function: cleave

function cleave(v /*... fs*/){ var fs = Array.prototype.slice.call(arguments, 1, arguments.length); return fs.map(function(f){ return f(v); }); }

and the shortcut:

function cl_(){ return function(f){ return cleave.apply(null, [f].concat(Array.prototype.slice.call(arguments,0,arguments.length))); } }

(This is just cleave curried on the right, eg in puff: c_(cleave) .)

// replaceMiddleName name newMiddleName -> transformedName var replaceMiddleName = r(args(2), cl_(r(first, split(' ')), second), cl_(r(first,first),second,r(first, third)), au(join(' '), first, second, third));

Let’s go nuts with some of the extra utility functions in puff:

var replaceMiddleName = f(2, cl_(r(n0,split(' ')),n1), cl_(n00, n1, n02), join(' '));

Puff lets you do all of this insanity quite easily. There are browser and nodejs builds. You use it by saying, in node:

require('puff').pollute(global);

Which pollutes the global namespace with the puff functions. Since terseness is the rule I can’t imagine why you’d do otherwise, but you can also say:

var puff = require('puff'); puff.r(...)

In the browser, add:

<script src="./build/puff-browser.js"></script>

To your head. This will define a global puff object, which you can then use directly or say: