Chapel自定义concat函数异常行为:.type与.eltType问题排查
Ah, I spot the issue right away—it’s a common gotcha with Chapel’s array type system! Let’s break down what’s happening and how to fix it.
The Root Problem
In your code, you declared the result array like this:
var v:[1..d] x.type;
Here, x.type refers to the entire array type of x (for example, if x is [1..3] real, x.type is array(1..3, real)). That means v isn’t an array of real values—it’s an array of arrays, where each element is a full array matching x’s type.
When you assign v[k] = x[i] (a single real value) to this array-of-arrays, Chapel implicitly converts the scalar into an array filled with that scalar. For your test case, each element of v becomes a 3-element array of the same value. That’s why your output shows repeated elements and a total length way larger than the expected 6!
The Fix
You need to use x.eltType instead of x.type to get the type of the elements inside the array, not the array type itself. Here’s the corrected version of your function:
proc concat(x:[], y:[]) { const d:int = x.size + y.size; var v:[1..d] x.eltType; // Use eltType for element type var k = 1; for i in x.domain { v[k] = x[i]; writeln("i: ", i, " k: ", k, " x[i]: ", x[i], " v[k]: ", v[k]); k += 1; } for i in y.domain { v[k] = y[i]; writeln("i: ", i, " k: ", k, " y[i]: ", y[i], " v[k]: ", v[k]); k += 1; } writeln("\n v: ", v); return v; }
A Simpler Alternative
Chapel actually has built-in array concatenation using the + operator—you don’t need to write this function from scratch! This does exactly what you want, with less code and fewer opportunities for bugs:
proc concat(x:[], y:[]) { return x + y; }
When you run your test code with either version, you’ll get the expected result: [1.1, 2.2, 3.3, 9.9, 10.1, 11.11] (note: Chapel may format 10.10 as 10.1 in output).
内容的提问来源于stack exchange,提问作者Brian Dolan

