Silly Question about Blocks and whileTrue:

Raab, Andreas Andreas.Raab at disney.com
Thu Feb 8 05:09:11 UTC 2001


Jerome,

Actually that's a really interesting question. I had to think about a little
but reformulating the problem made it perfectly clear. Let's rewrite
#whileTrue: into #whileTrueRecursive: and see what this yields:

BlockContext>>whileTrueRecursive: aBlock
	^self value 
		ifTrue:[aBlock value.
			  self whileTrueRecursive: aBlock].

This is a 100% equivalent to #whileTrue: except that the end-recursion is
replaced with a jump. So what happens is that #whileTrue: effectively
returns the result of the #ifTrue: message. However, since #ifTrue: is only
a short version of #ifTrue:ifFalse: the above code should actually read:

BlockContext>>whileTrueRecursive: aBlock
	^self value 
		ifTrue:[aBlock value.
			  self whileTrueRecursive: aBlock]
		ifFalse:[].

Since the final value returned will be the result of the #ifFalse: branch
(otherwise we'd go on with the recursion) the return value is the result of
evaluating an empty block. And an empty block evaluates to nil.

That's it (or at least my explanation). Hope it helps, and thank you for
asking such an interesting question!

Cheers,
  - Andreas


> -----Original Message-----
> From: Jerome Chan [mailto:eviltofu at earthlink.net]
> Sent: Wednesday, February 07, 2001 5:57 PM
> To: squeak at cs.uiuc.edu
> Cc: recipient list not shown
> Subject: Silly Question about Blocks and whileTrue:
> 
> 
> 
> | index |
> 
> index := 1.
> 
> result := [ index < 100 ] whileTrue: [ index := index + 1 ].
> result inspect.
> 
> When I run this, result is nil. When I look at the implementation of
> whileTrue: I see the following.
> 
> whileTrue: aBlock 
>     "Ordinarily compiled in-line, and therefore not overridable.
>     This is in case the message is sent to other than a literal block.
>     Evaluate the argument, aBlock, as long as the value of 
> the receiver is
> true."
> 
>     ^ [self value] whileTrue: [aBlock value]
> 
> Why does whileTrue: return anything?
> 
> 





More information about the Squeak-dev mailing list