[Newbies] Does Smalltalk have "break" method to jump out of a loop ?

Bernhard Pieber bernhard at pieber.com
Fri Nov 17 06:54:21 UTC 2017


Well, the first statement is the keyword message #to:do: sent to the receiver 1 with the parameters 130 and a one-argument block. The second is the keyword message #timesRepeat: sent to the receiver 100 with a zero-argument block as a parameter. What I meant is that it is no different from any other message send like 3 + 4. Neither looping nor conditionals are part of the syntax. None of the usual suspects like if, else, for, while etc. are reserved words. What follows is you can easily implement all kinds of useful „loop“ types yourself just by using messages and block closures.

main
	1 to: 5 do: [:i | i = 50 ifTrue: [^self]]

However, this is not an ideal example to show idiomatic Smalltalk. Here is one from the Collection class:

allSatisfy: aBlock
	"Evaluate aBlock with the elements of the receiver.
	If aBlock returns false for any element return false.
	Otherwise return true."

	self do: [:each | (aBlock value: each) ifFalse: [^ false]].
	^ true

The message enumerates the collection and as soon as an element is found, which does not satisfy the condition given by the block, it returns false from the method and therefore also breaks out of the loop.

Cheers,
Bernhard
 
> Am 17.11.2017 um 07:00 schrieb RedTigerFish <chihuyu at gmail.com>:
> 
> *1 to: 130 do: [:i| ] *  or  *100 timesRepeat: [ ] *
> 
> Maybe because I learned some C before. I thought the above two are loops.
> 
> 
> The following is "break" example in C. How to implement that in Smalltalk? 
> 
> #include <stdio.h>
> void main() 
> {   
>     for (int i = 0; i < 100; i++) 
>         if (i == 50) 
>              break; 
> }
> 
> 
> 
> -----
> Dig, dig where you are,
> Down below's well.
> Let those that walk in darkness shout, 
> Down below's hell.
> --
> Sent from: http://forum.world.st/Squeak-Beginners-f107673.html
> _______________________________________________
> Beginners mailing list
> Beginners at lists.squeakfoundation.org
> http://lists.squeakfoundation.org/mailman/listinfo/beginners



More information about the Beginners mailing list