More convenient array construction?

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

More convenient array construction?

bubkas22
I can create an array, and set its size...

var Array numList;
let numList = Array.new(10);

but now, if I wanted to fill the array, I would need to do the following...

let numList[0] = 1;
let numList[1] = 12;
let numList[2] = 100;
...
let numList [9] = 5;


Is there no way to feed a list of numbers in that is more convenient for typing?

let numList = {1, 12, 100, ... , 5};  ?
Reply | Threaded
Open this post in threaded view
|

Re: More convenient array construction?

cadet1620
Administrator
bubkas22 wrote
I can create an array, and set its size...

var Array numList;
let numList = Array.new(10);

but now, if I wanted to fill the array, I would need to do the following...

let numList[0] = 1;
let numList[1] = 12;
let numList[2] = 100;
...
let numList [9] = 5;


Is there no way to feed a list of numbers in that is more convenient for typing?

let numList = {1, 12, 100, ... , 5};  ?
There is no way to create and initialize an array. You need to do the Array.new and lets.

The Jack language was designed such that it would be easy to write a Jack compiler, at the expense of usability. That's why, for instance, multiple character tokens like >= are not supported.

One thing you can do if you have multiple arrays to allocate and initialize that are all the same length is to write a function that takes the initializers as arguments. Then your your allocation/initialization could be written as
class Foo {
...
    var Array numList;
    let numList = Foo.newArray10(1, 12, 100, ... , 5);
Unfortunately, there is no way to do variable number of arguments, so if you needed to handle arrays of different lengths, you would need to write multiple newArray() functions.

--Mark