Brian Dolan
Brian Dolan

Reputation: 3136

Assign an array to a property in a Chapel Class

Here is a Python-like pattern I need to re-create in Chapel.

class Gambler {
  var luckyNumbers: [1..0] int;
}

var nums = [13,17,23,71];

var KennyRogers = new Gambler();
KennyRogers.luckyNumbers = for n in nums do n;

writeln(KennyRogers);

Produces the run-time error

Kenny.chpl:8: error: zippered iterations have non-equal lengths

I don't know how many lucky numbers Kenny will have in advance and I can't instantiate Kenny at that time. That is, I have to assign them later. Also, I need to know when to hold them, know when to fold them.

Upvotes: 3

Views: 153

Answers (2)

Brad
Brad

Reputation: 4008

A way to approach this that simply makes things the right size from the start and avoids resizing/rewriting the array is to establish luckyNumbers in the initializer for Gambler. In order to do this without resizing, you'll need to declare the array's domain and set it in the initializer as well:

class Gambler {
  const D: domain(1);          // a 1D domain field representing the array's size
  var luckyNumbers: [D] int;   // declare lucky numbers in terms of that domain

  proc init(nums: [?numsD] int) {
    D = numsD;                 // make D a copy of nums's domain; allocates luckyNumbers to the appropriate size
    luckyNumbers = nums;       // initialize luckyNumbers with nums
    super.init();              // mark the initialization of fields as being done
  }
}

var nums = [13,17,23,71];

var KennyRogers = new Gambler(nums);

writeln(KennyRogers);

Upvotes: 2

David Iten
David Iten

Reputation: 545

This is a good application of the array.push_back method. To insert lucky numbers one at a time you can do:

for n in nums do
  KennyRogers.luckyNumbers.push_back(n);

You can also insert the whole array in a single push_back operation:

KennyRogers.luckyNumbers.push_back(nums);

There are also push_front and insert methods in case you need to put elements at the front or at arbitrary positions in the array.

I don't think I can help on when to hold them or when to fold them.

Upvotes: 4

Related Questions