by raganwald · 13y ago · 0 comments
Perhaps what the article needs is a disclaimer such as:
We can easily rewrite this in iterative style, but there are other functions that aren’t so amenable to rewriting and using a simple example allows us to concentrate on the mechanism rather than the “domain.”
;-)
[0] http://raganwald.com/2013/01/03/function_and_method_decorato...
Ever find yourself writing a "main loop" full of unrelated code which only appears in the same place because you're forced to keep it all between the loop's braces? That's a prime candidate for mutual recursion, made safe using tail-call optimisation:
var foo = function() {
//
};
var bar = function() {
//
};
var baz = function() {
//
};
var main = function() {
while (true) {
foo();
bar();
baz();
}
};
main();
Can be replaced with: var foo = function() {
//
bar();
};
var bar = function() {
//
baz();
};
var baz = function() {
//
foo();
};
foo();
This is how I tend to write Javascript; although I generally handle tail-call optimisation by using setTimeout(foo, 0), which has the same effect.OK, but couldn't you then still complain that each of those are "Simple, shorter, no overhead from function calls, etc." as while loops?
As a matter of fact, I was struggling with Stack Overflow problems when constructing huge kd-trees recursively. I read this article a week ago, but failed to translate the pure recursive formulation of constructing a tree into a tail-recursive one -- since the recursion goes two ways instead of one
Here's an example from Wikipedia:
function kdtree (list of points pointList, int depth)
{
// Select axis based on depth so that axis cycles through all valid values
var int axis := depth mod k;
// Sort point list and choose median as pivot element
select median by axis from pointList;
// Create node and construct subtrees
var tree_node node;
node.location := median;
node.leftChild := kdtree(points in pointList before median, depth+1);
node.rightChild := kdtree(points in pointList after median, depth+1);
return node;
}http://raganwald.com/2013/03/29/high-level-trampolining.html