For loop for array in Pharo Smalltalk

2019-06-24 07:29发布

I'm trying to make an array with random numbers (just 0 or 1), but when I run it, it just prints this: End of statement list encountered ->

This is my code:

GenList
 | lista |
  lista := Array new: 31.
  1 to: 30 do: [ :i | lista at: i put: 2 atRandom - 1]
  ^lista

What can I do?

1条回答
闹够了就滚
2楼-- · 2019-06-24 07:59

Some interesting things to consider:


1. The method selector doesn't start with a lowercase letter


It is a tradition for selectors to start with a lowercase letter. In this sense, genLista would be more correct than GenLista.


2. The method selector includes the abbreviated word 'gen'


For instance, genLista could be renamed to genereLista o listaAlAzar (if you decide to use Spanish)


3. The Array named lista has 31 elements, not 30


The result of Array new: 31 is an array of 31 elements. However, the code below it only fills 30 of them, leaving the last one uninitialized (i.e., nil). Possible solution: lista := Array new: 30.


4. A dot is missing causing a compilation error


The code

  1 to: 30 do: [ :i | lista at: i put: 2 atRandom - 1]
  ^lista

does not compile because there is no dot indicating the separation between the two sentences. Note that the error happens at compilation time (i.e., when you save the method) because the return token ^ must start a statement (i.e., it cannot be inlined inside a statement).

There are other cases where a missing dot will not prevent the code from compiling. Instead, an error will happen at runtime. Here is a (typical) example:

1 to: 10 do: [:i | self somethingWith: i]     "<- missing dot here"
self somethingElse

the missing dot will generate the runtime error self not understood by block.


5. There is a more expressive way of generating 0s and 1s at random


The calculation 2 atRandom - 1 is ok. However, it forces the reader to mentally do the math. A better way to reveal your intention would have been

#(0 1) atRandom

6. When playing with random numbers don't forget to save the seed


While it is ok to use atRandom, such a practice should only be used with "toy" code. If you are developing a system or a library, the recommended practice is to save the seed somewhere before generating any random data. This will allow you to reproduce the generation of random quantities later on for the sake of debugging or confirmation. (Note however, that this will not suffice for making your program deterministically reproducible because unordered (e.g. hashed) collections could form differently in successive executions.)

查看更多
登录 后发表回答