Is it possible to declare an array with config?

空扰寡人 提交于 2019-12-07 05:35:45

问题


Or any similar data structure of dynamic length, which, can be cast easily to an array. The only workaround I have found is entering the array as a string and manually parsing it.

config var not_array: string = '[1,2,3,4,5]' ;

proc main() {
    // config array workaround
    writeln("I am string. Definitely not array ", not_array) ;

    // parse string
    not_array = not_array.replace(' ','') ;
    not_array = not_array.replace('[','') ;
    not_array = not_array.replace(']','') ;
    var still_not_array = not_array.split(',') ;

    // prepare array
    var dom = 0..#still_not_array.size ;
    var array: [dom] real ;

    // populate array
    for (i, x) in zip(dom, still_not_array) {
        array[i] = x:real ;
    }
    writeln("Ha! Tricked you, am actually array ", array) ;
}

This works as intended, but is there a better way?


回答1:


Is it possible to declare an array with config?

No, this is not yet supported in Chapel as of Chapel 1.16.

That said, there are ways to work around this as you demonstrate.

As an alternative work-around, you can utilize IO calls to write the input string to memory and then read it in as an array, e.g.

config type  arrType = int;
config const arrSize = 3,
             arrString = '1 2 3';

var A : [1..arrSize] arrType;

// Create a memory buffer to write in
var f = openmem();

// Create a writer on the memory buffer and write the input string
var w = f.writer();
w.writeln(arrString);
w.close();

// Create a reader on the memory buffer and read the input string as an array
var r = f.reader();
r.readln(A);
r.close();

writeln(A);

Note this requires the array size up front. I think you'd have to do some string processing like your original example to compute that on the fly.

Some resources:

  • IO.openmem()
  • IO.channel.readln()


来源:https://stackoverflow.com/questions/47712619/is-it-possible-to-declare-an-array-with-config

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!