Loops/Nested: Difference between revisions

Content added Content deleted
Line 1,653: Line 1,653:
=={{header|Smalltalk}}==
=={{header|Smalltalk}}==


Notice that the original answer (see below) was wrong.
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}}
{{works with|Smalltalk/X}}
Line 1,695: Line 1,695:
exitBlock := [:exitValue | ^ exitValue].
exitBlock := [:exitValue | ^ exitValue].
[true] whileTrue:[ self value:exitBlock ]</lang>
[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.
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 which usually used to exit early from search utility methods.


There exists an additional valueWithExit, which can be used to get out of a block early. Using that, the tasks solution is:
There is also valueWithExit, which can be used to get out of a block early and provide an alternative value. Using that, the tasks solution is:
<lang smalltalk>|v result|
<lang smalltalk>|v result|


Line 1,714: Line 1,714:
]
]
].
].
nil
] valueWithExit.
] valueWithExit.


Line 1,732: Line 1,733:


{{works with|GNU Smalltalk}}
{{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.
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
<lang smalltalk>"this simple implementation of a bidimensional array