Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can one create a standalone method/function (without any class)

Tags:

smalltalk

I am trying to understand smalltalk. Is it possible to have a standalone method/function, which is not part of any particular class, and which can be called later:

amethod ['amethod called' printNl]. 
amethod.

Above code gives following error:

simpleclass.st:1: expected Eval, Namespace or class definition

How can I use Eval or Namespace as being suggested by error message?

I tried following but none work:

Eval amethod [...
amethod Eval [...
Eval amethod Eval[...        "!"

Eval [... works but I want to give a name to the block so that I can call it later.

Following also works but gets executed immediately and does not execute when called later.

Namespace current: amethod ['amethod called' printNl]. 

Thanks for your insight.

like image 461
rnso Avatar asked Sep 21 '25 10:09

rnso


1 Answers

In Smalltalk the equivalent to a standalone method is a Block (a.k.a. BlockClosure). You create them by enclosing Smalltalk expressions between square brackets. For example

[3 + 4]

To evaluate a block, you send it the message value:

[3 + 4] value

which will answer with 7.

Blocks may also have arguments:

[:s | 3 + s]

you evaluate them with value:

[:s | 3 + s] value: 4  "answers with 7"

If the block has several sentences, you separate them with a dot, as you would do in the body of a method.


Addendum

Blocks in Smalltalk are first class objects. In particular, one can reference them with variables, the same one does with any other objects:

three := 3.
threePlus := [:s | three + s].

for later use

threePlus value: 4    "7"

Blocks can be nested:

random := Random new.
compare := [:p :u | u <= p]
bernoulli60 := [compare value: 0.6 value: random next].

Then the sequence:

bernoulli60 value.  "true"
bernoulli60 value.  "false"
...
bernoulli60 value.  "true"

will answer with true about 60% of the times.

like image 148
Leandro Caniglia Avatar answered Sep 23 '25 15:09

Leandro Caniglia