Sunday, January 31, 2010

The deconstructed for loop

I've been mulling over an idea lately and wanted to run it by folks.

Right now, the syntax for a 'for' loop in Tart looks something like this:

for i = 0; i < 10; ++i {
}

In other words, it looks just like a C for loop, except without the parentheses. I'm not exactly happy with using semicolons as delimiters here - nothing else in Tart looks remotely like this.

I thought about replacing the semicolons with keywords. "while" is a natural keyword for the test element. For the increment part, I thought about using "next" (harkens back to BASIC's for-next loops), however "next" is also a fairly common identifier. Another option is the word "then":

for i=0 while i < 10 then ++i {
}

// Another way to write it
for i=0
  while i < 10
  then ++i {
}

This isn't too bad I suppose.

There is one other advantage of using keywords rather than semicolons, which is the ability to leave out the parts you aren't using:

// This case is relatively common - the increment is inside the body.
for i = 0 while i < 10 {
}

// This case is also relatively common.
for i = 0 then ++i {
}

// An augmented while loop?
while i < 0 then ++i {
}

// Don't know why you would use this but it follows logically from the above.
for i = 0 {
}

// Not sure what this even means - add 2 to i, but return the previous value of i?
then i += 2 { return i; }

In other words, the idea is to deconstruct the 'for' keyword into individual 'atoms' which can be used independently.

In any case, I'm not sure I like this idea, but I wanted to see what other people thought.

No comments:

Post a Comment