Tuesday, April 6, 2010

Tail Recursion and Good Sentence Structure

As a guy who writes both prose and computer code, sometimes the similarities between the two media seem too great to ignore. They are surely different, and require largely different skill sets—nevertheless, there are patterns that bridge the gap. Here, I'll attempt to explain one such parallel:

Tail recursion is a sort of esoteric computer science concept, but let's give it a go. Let's assume we have a simple, recursive function describing a factorial:
f(x) = f(x - 1) * x
f(0) = 1
Let's evaluate this for x = 3:
f(3) = f(3 - 1) * 3 = f(2) * 2
f(2) = f(1) * 2
f(1) = f(0) * 1
f(0) = 1
f(1) = 1 * 1 = 1
f(2) = 1 * 2 = 2
f(3) = 2 * 3 = 6
Note that we had to go back through all the equations we had used earlier, substituting in our results back into each earlier step.

Now let's try a different method:
f2'(x, a) = f2'(x - 1, a * x)
f2'(0, a) = a
f2(x) = f2'(x, 1)
And, evaluating for x = 3:
f2(3) = f2'(3, 1)
f2'(3,1) = f2'(3 - 1, 1 * 3) = f2'(2, 3)
f2'(2,3) = f2'(1,6)
f2'(1,6) = f2'(0,6)
f2'(0,6) = 6
Interesting—it took an extra step because of the helper function, but once we had the answer to our final function, we were done! (Really, this sort of thing does make computer programmers happy.) *

Okay, we're done with the math, but hang with me for a second. This idea has a similarity in the written word. Let's talk about sentence structure. Specifically, about the use of modifying and qualifying clauses.

I don't know of a standard notation for this sort of thing, but let's mark up our sentences with parentheses to explicitly show a clause. Here's a sample sentence:

While Windows will let you switch keyboard layouts in software, my current work environment, (which involves dozens of different computers, including virtual machines), makes this a little difficult.

The parenthetical aside is all well and good, but try contrasting it with this rework of the sentence:

While Windows will let you switch keyboard layouts in software, this is a little difficult to manage in my current work environment, (which involves dozens of different computers, including virtual machines).

Moving a clause like this to the end of the sentence can make it easier to understand on anyone reading it.

* For a fuller explanation of tail recusion, here's an article with further information.

No comments:

Post a Comment