Loops/Nested: Difference between revisions

Line 1,696:
[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.
 
There exists an additional valueWithExit, which can be used to get out of a block early. Using that, the tasks solution is:
<lang smalltalk>|v result|
 
v := 1 to:20 collect:[:i |
1 to:20 collect:[:j | Random nextIntegerBetween:1 and:20 ]
].
 
result :=
[:exit |
1 to:20 do:[:row |
1 to:20 do:[:col |
|element|
 
(element := (v at:row) at:col) printCR.
element == 20 ifTrue:[ exit value:(row @ col) ].
]
].
] valueWithExit.
 
result isNil ifTrue:[
'ouch - no 20 found' printCR.
] ifFalse:[
'20 found at ' print. result printCR
]</lang>
Output:
<pre>19
6
1
7
12
20
20 found at 1@6</pre>
 
 
{{works with|GNU Smalltalk}}
Anonymous user