Loops/Downward for: Difference between revisions

Line 1,798:
 
=={{header|Smalltalk}}==
<lang smalltalk>10 to: 10 by: -1 do:[:aNumber |
aNumber displayNl.
]
10 downTo: 10 do:[:aNumber |
aNumber displayNl.
]</lang>
Both enumerate 10 to 10 inclusive.
 
Non-Smalltalkers might be confused when seeing:
<lang smalltalk>(10 to: 10 by: -1) do:[:aNumber |
aNumber displayNl.
]</lang>
which has the same effect, but a slightly different mechanism.
 
The first one sends a <tt>"to:by:do:"</tt> message to the Integer 10, passing "10", "-1", and the closure as arguments. There (in the integer), the counting and closure invokation takes place (who cares how it does it?).
 
The second example first instantiates a range-collection object (called Interval in Smalltalk) with the <tt>"to:by:"</tt> message (sent to the integer), and then this Interval object gets a <tt>"do:"</tt> message.<br>Which - like all collections - enumerates its elements, in this case [10..1].
Line 1,819:
 
The nice thing with Intervals is that they can be concatenated with a <tt>","</tt> operator (like all collections); thus, I could also write:
<lang smalltalk>(10 to: 65 by: -1),(10 to: 54) do:[:aNumber |
aNumber displayNl.
]</lang>
to enumerate in a different order,
<br>or combine ranges with a constant array:
<lang smalltalk>(10 to: 20 by: -2),#(99 999),(1 to: 109 by: 2) do:[:aNumber |
aNumber displayNl.
]</lang>
or with a computed array:
<lang smalltalk>(10 to: 20 by: -2),{ 10 factorial . 11 factorial},(1 to: 109 by: 2) do:[:aNumber |
aNumber displayNl.
]</lang>
Anonymous user