Re: Use "range," not "for"?

From: Glenn Jackman (xx087_at_freenet.carleton.ca)
Date: 02/13/04


Date: 13 Feb 2004 01:10:24 GMT

David McClamrock <mcclamrock@locl.net> wrote:
> I've found that a simple "foreach" loop fairly often won't do the jobs I
> want done,

Really? Why?

[...]
> Instead of writing this:
> for {set i 1} {$i<= 10} {incr i} {puts "$i. \"for\" is ugly!"}
> you can write this:
> range i 1 to 10 {puts "$i. \"range\" is beautiful!"}
>
> Or, if you have a list called "lum," instead of writing this:
> for {set i 0} {$i < [llength $lum]} {incr i} {puts [lindex $lum $i]}
> you can write this:
> range i 0 no [llength $lum] {puts [lindex $lum $i]}
>
> To go backward, skipping every other number, instead of this:
> for {set i 10} {$i >= 0} {incr i -2} {puts $i}
> you can write this:
> range i 10 to 0 -2 {puts $i}
[...]

Woof, it looks needlessly complicated. You don't have to muck about
with uplevel at all. Have a look at http://wiki.tcl.tk/10795
It demonstrates an "integer range generator" proc called [..]
Using it would change your examples to:

1 foreach i [.. 1 10] {puts "$i. '..' is beautiful"}

2 foreach i [.. 0 [expr {[llength $lum] - 1}]] {puts [lindex $lum $i}
    # OK, that's not as pretty as your [range], but it's a crummy
    # example anyway

3 foreach i [.. 10 0 -2] {puts $i}

Here's a wiki page showing a "do ... until ..." loop, which demonstrates
how to neatly handle executing a script body that's passed as an
argument to a proc:
    http://wiki.tcl.tk/917

-- 
Glenn Jackman
NCF Sysadmin
glennj@ncf.ca


Relevant Pages

  • Re: equality and errors
    ... This seems to me like a non-standard use of the catch mechanism. ... you have a proc which validates the contents of two ... If I were writing this program, though, I would use a different approach ... have the calling code respond intelligently to that value, ...
    (comp.lang.tcl)
  • Use "range," not "for"?
    ... Thanks to everyone who suggested ways to get a proc to recognize all ... So, here's my first effort. ... Or, if you have a list called "lum," instead of writing this: ... proc range {var star cutoff fin args} { ...
    (comp.lang.tcl)
  • Re: Getting proc to recognize all global variables
    ... David McClamrock wrote: ... >Would somebody please remind me how it's possible to get a proc ... Business: http://www.Phaseit.net ...
    (comp.lang.tcl)
  • Re: New to MuPad
    ... I am now in the process of writing a ... domain constructor in MuPad, and I can not get the 'new' proc to work. ...
    (sci.math.symbolic)
  • Re: Getting proc to recognize all global variables
    ... David McClamrock wrote: ... > Would somebody please remind me how it's possible to get a proc ... > to recognize all variables in the global scope, ...
    (comp.lang.tcl)