Loops/With multiple ranges: Difference between revisions

Content added Content deleted
Line 1,732: Line 1,732:
Transcript show:'prod = '; showCR:prod</lang>
Transcript show:'prod = '; showCR:prod</lang>
The above creates a temporary "collection of ranges" and enumerates that, which might be inconvenient, if the collections are huge.
The above creates a temporary "collection of ranges" and enumerates that, which might be inconvenient, if the collections are huge.
<br>An alternative is to loop over each individually (whichever you prefer).
<br>One alternative is to loop over each individually.


Of course, we definitely don't want to retype the loop body
Of course, we definitely don't want to retype the loop body
and we usually don't want to the code to be non-local (i.e. define another method for it).
and we usually don't want to the code to be non-local (i.e. define another method for it).
<br>That's what blocks are perfect for:
<br>That's what blocks (aka lambdas or anonymous functions) are perfect for:
<lang smalltalk>prod := 1.
<lang smalltalk>prod := 1.
sum := 0.
sum := 0.
Line 1,764: Line 1,764:
Transcript show:'prod = '; showCR:prod</lang>
Transcript show:'prod = '; showCR:prod</lang>


As an alternative to the first solution above, we could loop over the ranges. This avoids the concatenations and possible generation of the intermediate big collection - which does not make a difference here, but would, if each collection consisted of millions of objects):
As another alternative to the first solution above, we can loop over the ranges. This avoids the concatenations and generation of the intermediate big collection (which does not really make a difference here, but would, if each collection consisted of millions of objects):
<lang smalltalk>...
<lang smalltalk>...
{
{