Reputation: 24565
I have a few simple questions, hence I am putting them together:
What is the best way to create a series of numbers. Following works but is there a simpler method like 1:10 available in some languages?
myseries: []
repeat i 10 [append myseries i]
print myseries
(1a. Why is above code not making usual code block on this page?)
Similarly, what is the best way to create a series of 10 elements, all initialized to 0 or ""? Do I have to use there also repeat i 10
or loop 10
and serially append
an initially blank series?
Also, should I specify the number of elements as in following code while creating the series initially? What is the disadvantage of not doing this?
myseries: make block! 10
Thanks for your help.
Upvotes: 1
Views: 256
Reputation: 22570
1) My preference would be to go with COLLECT here:
myseries: collect [repeat i 10 [keep i]]
2) See ARRAY function:
>> array/initial 10 0
== [0 0 0 0 0 0 0 0 0 0]
You can also pass it a anonymous function:
>> i: 0 array/initial 10 does [i: i + 1]
== [1 2 3 4 5 6 7 8 9 10]
3) Generally it is good practise to use myseries: make block! 10
(or just 0 if size of block is unknown) to avoid unnecessary gotchas! See To copy or not to copy, that is the question & Is REBOL a Pure Functional Language?
Upvotes: 6
Reputation: 6436
1) I do not know about a better way at this time, although on https://gitter.im/red/... there are discussions about a range data type or for implementations
a) It makes a block. You see that with probe myseries
. What do you expect?
2) >> append/dup [] 0 10
== [0 0 0 0 0 0 0 0 0 0]
3) If you do not initialize/reserve the needed memory, Red has to make a guess how much memory is needed. This can be more than needed or less. If less then Red has to allocate another chunk of memory. This can happen a few times if you need more memory. Maybe it has to move around memory blocks too if it wants continuous memory, but I do not know about the strategy used.
Upvotes: 1