Main Page | Report Page

 

  Computers Forum Index » Computer Languages (Smalltalk) » Implementation of whileTrue: in VisualAge

Author Message
Guest
Posted: Fri Jan 27, 2006 1:25 am
 
Here's the implementation of whileTrue: in VisualAge:

Block>>whileTrue: aBlock

"Evaluate the receiver and aBlock repeatedly until the receiver
evaluates
to false."

[ self value ] whileTrue: [ aBlock value]


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

How does this work? Shouldn't this go into an infinite loop? The
original block (aBlock) receives value only when the outer block
([aBlock value]) receives it. When does that happen? After 3 recursive
calls, it should end up like this:

[[[[self value] value] value] value] whileTrue: [[[[aBlock value]
value] value] value]

Where am I wrong?
 
David Buck
Posted: Fri Jan 27, 2006 1:40 am
 
vasuadiga@gmail.com wrote:
Quote:
Here's the implementation of whileTrue: in VisualAge:

Block>>whileTrue: aBlock

"Evaluate the receiver and aBlock repeatedly until the receiver
evaluates
to false."

[ self value ] whileTrue: [ aBlock value]


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

How does this work? Shouldn't this go into an infinite loop? The
original block (aBlock) receives value only when the outer block
([aBlock value]) receives it. When does that happen? After 3 recursive
calls, it should end up like this:

[[[[self value] value] value] value] whileTrue: [[[[aBlock value]
value] value] value]

Where am I wrong?


Yup. It looks weird. It turns out that the compiler specially
optimizes whileTrue: and never actually dispatches a whileTrue: message
under normal operations. It replaces the whileTrue: with conditional
branching within the bytecodes to do the looping but it never actually
sends whileTrue:. The method is effectively never called.

If, however, you used perform: to execute the above method, it would
work fine because it would actually hit the method then run the
optimized code to do the whileTrue:.

It's one of the VERY few places in Smalltalk where the code you see
isn't actually executed and is instead optimized out by the compiler.

David Buck
Simberon Inc.
www.simberon.com
 
Thomas Koschate
Posted: Sat Jan 28, 2006 2:29 am
 
David Buck wrote:
Quote:
It's one of the VERY few places in Smalltalk where the code you see
isn't actually executed and is instead optimized out by the compiler.


Just to really drive home this point, it's worth looking for senders of
#whileTrue:. Make sure you've actually got some code that you know is
sending it before doing this.

Tom
 
 
Page 1 of 1    
All times are GMT
The time now is Mon Sep 01, 2014 12:03 pm