Loops/Nested: Difference between revisions

Line 1,652:
 
=={{header|Smalltalk}}==
 
original text: "Smalltalk has no ways of escaping from loops (single or nested), even if it is possible to extend its iteration capabilities in several ways. "
 
{{works with|Smalltalk/X}}
 
That is not exactly true; never say never say never...
it looks a bit wierd, but here is: loopWithExit
 
<lang smalltalk>|i|
 
i := 1.
[:exit |
Transcript showCR:i.
i == 5 ifTrue:[ exit value:'stopped' ].
i := i + 1.
] loopWithExit</lang>
these can also be nested, and exited from the inner loop:
<lang smalltalk>|i|
 
i := 1.
[:exit1 |
|j|
 
j := 0.
[:exit2 |
Transcript showCR:('i is %1 / j is %2' bindWith:i with:j).
j == 5 ifTrue:[ exit2 value: nil ].
i == 5 ifTrue:[ exit1 value: nil ].
j := j + 1.
] loopWithExit.
i := i + 1
] loopWithExit</lang>
in case your smalltalk does not have it, here's the definition:
<lang smalltalk>!Block methodsFor:'looping'!
loopWithExit
"the receiver must be a block of one argument. It is evaluated in a loop forever,
and is passed a block, which, if sent a value:-message, will exit the receiver block,
returning the parameter of the value:-message. Used for loops with exit in the middle."
 
|exitBlock|
 
exitBlock := [:exitValue | ^ exitValue].
[true] whileTrue:[ self value:exitBlock ]</lang>
in the same spirit, exits could be added to many other loop constructs. However, this is really only very rarely needed in Smalltalk, because a ^(return) out of a block returns from the enclosing method. This is usually used to exit early from a utility method.
 
{{works with|GNU Smalltalk}}
Smalltalk has no ways of escaping from loops (single or nested), even if it is possible to extend its iteration capabilities in several ways. The following code implements a BiArray class with a method that allows iteration over the elements (by columns and then by rows) and execution of a block if a condition is true.
<lang smalltalk>"this simple implementation of a bidimensional array
lacks controls over the indexes, but has a way of iterating
Anonymous user