Saturday, March 29, 2008

Lazy invocation

Closely related to procrastination is the deferral of work. Unlike procrastination, this does not guarantee the replacement of one useful activity by some other less important (but less stressful or strenuous) activity. Instead, the idea (absurd, surely!) is to defer the less important work, and perform it later, or perhaps not at all. 

Lazy languages take this to one extreme, and guarantee that it will be impossible to observe them doing any work that they do not have to do. Of course, programs then spend more work figuring out what they have to do than actually performing the work, but that is just part and parcel of being truly lazy. As it turns out, compilers for these lazy languages spend lots of time working out when it is possible to not be lazy --- sometimes the programmer has to help out with strictness annotations --- and some even go so far as to be eager, assuming that you might need something in the future, and that they might as well just get it out of the way!

In a more productive case, the work is performed asynchronously, perhaps incrementally, or even by someone else, and if we're so fortunate that it has already been done by the time we need it --- surely in some distant, and unlikely future --- we have to do nothing other than reap the benefits. If not, we have to wait, or even complete the task ourselves. These asynchronous units of work that we hope not to have to do ourselves are often called futures.

sort(array, count) {
if (count > 1)
half = count / 2;
left=future(sort(array, half));
right=sort(array+half, count-half);
return merge(need(left), right, count);
}
return array;
}

(A really clever compiler for a lazy language might be able to figure out that  it could introduce the future above, taking that burden away from the programmer. Writing one of those appears to be hard work.)

A procrastinating version of the program above might look something like this:

sort(array, count) {
if (count > 1)
half = count / 2;
left=future(sort(array, half));
right=future(sort(array+half, count-half));
while(!(done(left) && done(right))) clean_room(); 
result= future(merge(need(left), need(right), count));
while(!done(result)) pot_plants();
return need(result);
}
return array;
}




No comments: