Code is Poetry

Saturday, March 5, 2005

I am inspired after reading a blog post with one of the most beautiful iterative constructs I have ever seen. The elegance of the for loop in the third function is unmatched.

for ( selIndex = fromObj.length; selIndex -- ; selIndex > 0 ){ ... }

The first thing to notice is that the loop will count backwards through the collection, from length to 0. But the real genius comes with the positioning of the decrement. A traditional for loop looks something like this:

for (var i=0; i < fromObj.length; i++) { ... }

As you can see, the loop test condition (i < fromObj.length) occurs as the second item in the for construct. The loop will execute the first item once at the beginning of the loop, then it will execute the second, then the body of the loop, and lastly the third item in the construct.

  1. In this unorthodox code, selIndex is first set to the length of the collection, as it is the first item in the construct.
  2. By placing the decrement as the second item, it is executed before the body of the loop and thus is immediately decremented to length - 1, something we all know is necessary (because arrays and collections in JavaScript are zero-based and thus there is no element at the length position, but only up to length - 1).
  3. Next, the body of the loop executes with the correct value for the collection index, as it loops through the elements from last to first.
  4. After a single execution of the body, the loop will go to the 3rd item in the construct–selIndex > 0. The interesting part here is that this block is simply executed–its return value is never used. So this simply evaluates to true and thus has no effect on anything. This means that he could have totally omitted this 3rd part of the construct, but it serves more as documentation for what is going on.
  5. The culmination of genius for this loop is the stop condition, which must be in the 2nd part of the construct, namely selIndex -- ;. When selIndex gets to 1 it will be decremented from 1 to 0, but because of the postfix notation of the decrement, it will still be evaluated as 1 (true). Therefore the body will execute again and on the next condition test, it will be evaluated as 0 (false) and thus end execution of the loop, having just dealt with the 0th element.

Wow. The cunning in this code makes me grin. It reminds me much of a story I read about Mel: A Real Programmer. Well now that I’m humbled again, I will go dabble in philosophy.

written by Brad Fults

Archived at: http://h3h.net/2005/03/code-is-poetry/

9 responses

  1. Bethany

    NERD <3

  2. Phalanx

    I like Mel. He is a swell guy.

  3. jcraveiro.com

    Less is more

    E agora um link-post muito curto e rápido: o artigo Code is Poetry dá-nos a conhecer uma construção muito elegante de um ciclo for (agora ia-me enganando a escrever isto—é que eu, apesar de não ser muito velho, ainda sou do tempo dos ciclos for…

  4. James Grimmelmann

    It’s strange. It’s elegant. It’s bad code.

    Swapping the test and the increment is flirting with disaster, because it makes the code a trap for the unwary. It runs against the normal expectations of C programmers, and thereby increases the risk that some subsequent programmer will innocently try to modify the code and inadvertently unleash disaster by not realizing that the second and third pieces are “flipped.”

    The only safe way to release this fragment into the wild is with extensive documentation. But that still raises the risk that someone will cut-and-paste it without bringing the documentation along, or will tweak it in a way that moves the documentation out of sync. You’re right that it’s classic Mel code: It’s close to unusuable by any programmer other than the original.

    But Mel at least used strange constructs that produced significantly more efficient code . . .

  5. Ian

    This is terrible code. From what I assume is your comment in the original page: After spending 10 minutes on analysing the for loop in selectEntireList I have to admit it is pure zen. It shouldn’t take TEN MINUTES to figure out what a simple for loop does. What’s wrong with for(selIndex = fromObj.length – 1; selIndex >= 0; selIndex– ){ … } ? Nothing. It’s immediately obvious how it works for anyone who stumbles across it. Yes, someone else may have to maintain your code in the future, believe it or not! Leave unreadable, “elegant” code to the Perl guys. Read http://ask.metafilter.com/mefi/17135#287882 for more analysis from another person.

  6. Tom

    What a bunch of crap.

  7. And Clover

    I find this similar idiom for backwards-iteration much easier to read:

    for (selIndex= fromObj.length; selIndex–>0;) { … }

    The ‘arrow’ looking like what it effectively means.

    Personally I find the use of a ‘dummy’ term in the original version rather questionable. Alter the code without looking too closely at what’s really going on and you’ve got a tricky bug to track down.

  8. And Clover

    (substitute the en-dash above with minus-minus, natch)

  9. Brad

    Funny that everyone seemed to equate “beautiful” and “cunning” with “good practice”. I don’t condone the use of this code at all–it is a logistical and practical nightmare. But poetry isn’t supposed to be efficient and practical; it’s beautiful.

    I was highlighting the elegance of the code and nothing more. That said, always use the standard for loop format so that your code will be readable. Unless of course, you don’t want it to be. :)

  10. Comment Preview