Quoting constructs: Difference between revisions

Line 430:
#++ " same as #'++' "
#a:b:c: " same as #'a:b:c:' "</lang>
 
====Blocks====
Somewhat between literal constants and instantiated object are blocks which represent a closure (lambda function). Here, the code object is constructed as literal at compile time, and a closure object (which wraps the code plus the visible variables) into an object at execution time.
Blocks thus represent a piece of code which can be stored in an instance variable, passed as argument or returned from a method.
<br>Block syntax is very compact:
<lang smalltalk>[ expression . expression ... expression ]</lang>
or for a block with arguments:
<lang smalltalk>[:arg1 :arg2 :... :argN | expression . expression ... expression ]</lang>
Blocks are one of the fundamental building blocks of Smalltalk (no pun here), as the language (Compiler) does not specify any syntax for control structures. Control structures like if, while, etc. are all implemented as library functions, and defined eg. in the Boolean, Block or Collection classes.
<br>
If you have a block at hand, it can be evaluated by sending it a "value"message:
<lang smalltalk>aBlock value. "evaluate the block, passing no argument"
anotherBlock value:1 value:2. "evaluate the block, passing two arguments"</lang>
The most basic implementation of such a control structure is found in the Boolean subclasses True and False, which implement eg. "ifTrue:arg" and "ifFalse:". Here are those two as concrete example:
<lang smalltalk>in the True class:
ifTrue: aBlock
^ aBlock value "I am true, so I evaluate the block"
 
in the False class:
ifTrue: aBlock
^ nil "I am false, so I ignore the block"</lang>
Thus, the expression "someBoolean ifTrue:[ 'hello print' ]" will either evaluate the lambda or not, depending on the someBoolean receiver.
 
 
In addition, some Smalltalk dialects implement additional syntax extensions.
Anonymous user