Re: Use "range," not "for"?
From: Arjen Markus (arjen.markus_at_wldelft.nl)
Date: 02/13/04
- Previous message: Arjen Markus: "Re: How can I tell when a Tcl extension is providing stubs support?"
- In reply to: David McClamrock: "Use "range," not "for"?"
- Next in thread: David McClamrock: "Re: Use "range," not "for"?"
- Reply: David McClamrock: "Re: Use "range," not "for"?"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Fri, 13 Feb 2004 08:47:59 +0100
David McClamrock wrote:
>
> Thanks to everyone who suggested ways to get a proc to recognize all
> variables in the global scope--here's why I wanted to know. (Maybe someone
> has done this better already--if so, don't hesitate to let me know!)
>
> I've found that a simple "foreach" loop fairly often won't do the jobs I
> want done, and I need to use "for"--ugh! Well, I recently read at least
> part of a book about Python. It didn't look like an improvement over Tcl
> for the most part, but it has at least a few good features, one of which is
> the "range" expression. I thought a "range" procedure in Tcl might be a
> good substitute for the clumsy "for." So, here's my first effort. 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}
>
> The usage is pretty obvious: "range var start cutoff end ?incr? body." In
> other words, (1) the word "range"; (2) a variable to change through the
> range; (3) the beginning of the range; (4) "to" if the range is inclusive
> or "no" if it excludes the last number; (5) the end of the range; (6) a
> number for the increment if it isn't 1 (for an ascending range) or -1 (for
> a descending range); and (7) a body of code to execute on each iteration of
> the loop.
>
On the Wiki there is something similar - produce a list of integers that
you
can use in a foreach.
And I am very much reminded of the Fortran way of specifying for-loops
... :)
Yes, I usually avoid for-loops in Tcl, as foreach is much more elegant.
Care to put this on the Wiki? Or submit it for Tcllib?
Regards,
Arjen
- Previous message: Arjen Markus: "Re: How can I tell when a Tcl extension is providing stubs support?"
- In reply to: David McClamrock: "Use "range," not "for"?"
- Next in thread: David McClamrock: "Re: Use "range," not "for"?"
- Reply: David McClamrock: "Re: Use "range," not "for"?"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|