[comp.lang.smalltalk] fun with blocks

nicholl@uiucdcsp.cs.uiuc.edu (04/09/87)

------------------------------

Blocks that "call" themselves can do "recursion". Here is
an example that computes factorial:


-------------------------------------------------------------------
'From Smalltalk-80 version T2.2.0, of March 13, 1986 on 7 April 1987 at 2:26:53 pm'!



!Integer methodsFor: 'factorization and divisibility'!

fac
	| loop |
	loop _ [:num :acc | num == 0
				ifTrue: [^acc]
				ifFalse: [loop value: num - 1 value: acc * num]].
	loop value: self value: 1! !

-------------------------------------------------------------------

This can be used to implement a message-passing version of whileTrue:.
Informal tests show that it runs at about 25% of the speed of the 
standard version produced by the Compiler.


-------------------------------------------------------------------
'From Smalltalk-80 version T2.2.0, of March 13, 1986 on 6 April 1987 at 9:16:33 pm'!



!BlockContext methodsFor: 'controlling'!

whileTrue2: aBlock 
	| loop |
	loop _ [:expr | expr
				ifTrue: 
					[aBlock value.
					loop value: self value]
				ifFalse: [^nil]].
	loop value: self value! !

-------------------------------------------------------------------


                            --Sheldon Nicholl