Block Closures

Ron Teitelbaum Ron at
Wed Jan 4 15:28:41 UTC 2006


Block closures are truly wonderful things in Smalltalk.  It does take a
second to wrap your mind around them, but once that is done they are almost
as addictive as associations.

The basic idea is to wrap up a section of code to be used later and it
allows you to pass in variables use during execution.

In your example you are saying execute this code with no variables.  So
"[aFoo bar] value" would give you the same thing as "aFoo bar".  You could
make your block work by doing "[Transcript show: 'hello world'] value" but
there is little value in doing that.  

You might instead try: [:a | Transcript show: a] value: 'Hello World'.

Which reads execute the block [:a | Transcript show: a] with the value of
'Hello World' substituted for the temp variable :a.

Or even try: [:a :b | Transcript show: a; cr; show: b] value: 'Hello' value:

Which reads as execute the block [:a :b | Transcript show: a; cr; show: b]
with the values of 'Hello' and 'World' substituted for the temp variable :a
and :b.  (the ; cr; is a cascade that says send cr to Transcript to cause a
carriage return).

But wait there's more.  Since Block is an instance of a class you can pass
it around!

MyClass class >> salutationBlock

^[:a | Transcript show: ('Hello World especially ', a)]

And now you can execute: MyClass salutationBlock value: 'Ron'.  


MyClass >> myFriend

MyClass >> sayHelloToMyLittleFriend: aBlock
	aBlock value: self myFriend.

aMyClass sayHelloToMyLittleFriend: aMyClass class salutationBlock.

There is more since blocks to take the context with them when they are
created but I'm thinking that's enough for now.

It really is a lot of fun, and extremely powerful once you understand how it
works.  Just be careful.  They are addictive and I've seen block programming
that became more of a curiosity then a necessity.  (I should talk you should
see what I did with associations!)

Ron Teitelbaum

> -----Original Message-----
> From: squeak-dev-bounces at [mailto:squeak-dev-
> bounces at] On Behalf Of Hernan Tylim
> Sent: Wednesday, January 04, 2006 9:47 AM
> To: The general-purpose Squeak developers list
> Subject: Block Closures
> Hi,
> I wanted to try some experiments with BlockClosures on 3.9, but I can't
> find how to make the Compiler to use them.
> For example, If I inspect [Transcript show: 'hello world'] I get a
> BlockContext instance, not a BlockClosure one. Is that correct ? Do I
> need to do something to start using BlockClosure ?
> Thanks in advance
> Regards,
> Hernán
> ___________________________________________________________
> 1GB gratis, Antivirus y Antispam
> Correo Yahoo!, el mejor correo web del mundo

More information about the Squeak-dev mailing list