Loops/Downward for: Difference between revisions

→‎{{header|Smalltalk}}: more info and alternatives
(→‎{{header|Smalltalk}}: more info and alternatives)
Line 1,799:
=={{header|Smalltalk}}==
<lang smalltalk>10 to: 1 by: -1 do:[:aNumber |
aNumber displayNl.
]</lang>
Enumerates 10 to 1 inclusive.
By the few in case non-Smalltalkers are confused, but:
<lang smalltalk>(10 to: 1 by: -1) do:[:aNumber |
aNumber displayNl.
]</lang>
can also be written, with the same effect, but a slightly different mechanism.
 
The first one sends a <tt>"to:by:do:"</tt> message to the Integer 10, passing "1", -1, and the closure as arguments. There, probably, the number implements the counting (but who cares how it does it).
 
The second example 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].
 
Thus the above is one message send (aka virtual function call) to the number, whereas the second is two message sends and an object instantiation.
 
The nice thing with Intervals is that they can be concatenated with a <tt>","</tt> operator (like all collections); thus, I could als write:
<lang smalltalk>(10 to: 6 by: -1),(1 to: 5) do:[:aNumber |
aNumber displayNl.
]</lang>
to enumerate in a different order,
or combine ranges with a constant array:
<lang smalltalk>(10 to: 2 by: -2),#(99 999),(1 to: 10 by: 2) do:[:aNumber |
aNumber displayNl.
]</lang>
or with a computed array:
<lang smalltalk>(10 to: 2 by: -2),{ 10 factorial . 11 factorial},(1 to: 10 by: 2) do:[:aNumber |
aNumber displayNl.
]</lang>
Anonymous user