Converting blocks to methods
Klaus D. Witzel
klaus.witzel at cobss.com
Sat Jan 19 17:56:43 UTC 2008
This is of course possible in Smalltalk, alt-G the following:
!Object class methodsFor: 'Martin-Methods' stamp: 'kwl 1/19/2008 18:41'!
addMethod: aSelector with: aBlock
"Object addMethod: #doSomethingWith: with: [:argv | Transcript cr; show:
"Object new doSomethingWith: 'Hello World'"
self compile: aSelector, ' argv
#MartinBlock value: argv ' classified: #'Martin-Methods'.
^ (self compiledMethodAt: aSelector) literalAt: 1 put: aBlock; yourself! !
and doIt the two expressions in the comment lines.
IMHO it's rather a matter of taste to spend one new compiled method for
invoking one block.
Also, the scope of the block is related to creation time which may hold
its objects far longer than is wanted for many cases. But it's Smalltalk
and so that can be changed as well (not shown in the above).
On Sat, 19 Jan 2008 17:42:28 +0100, Martin Beck wrote:
> Hi there,
> has anyone tried to accomplish something like
> MyNewClass addMethod:#doSomethingWith: with: [ :arg |
> Transcript show: arg].
> MyNewClass new doSomethingWith: 'Hello World'.
> in Squeak? This would mean, to convert a block into a method, thus
> changing the hole semantics. Outer temporaries or other variables are of
> course forbidden. Literals have to be fetched out of the defining method
> and brought into a new compiled method and so on. Or perhaps there are
> other possibilities? Any ideas?
More information about the Squeak-dev