How to return a reference to a slice of an array in Chapel?
Asked Answered
C

1

6

I'm trying to return a reference to a slice of an array , but am getting the following compile-time error (where the offending line is in slice

test.chpl:9: error: illegal expression to return by ref

Returning the full array works fine, as does taking a reference to a slice in the main program.

Is there a correct way to return a ref to a slice? Thanks in advance!

record R {
  var A : [0.. #10] int;

  proc full() ref {
    return A;
  }

  proc slice() ref {
    return A[0.. #5];
  }
}

var r : R;
ref x1 = r.full();
ref x2 = r.slice();
ref x3 = x1[0.. #5];

Just for completeness :

chpl Version 1.16.0 pre-release (2659cc6)

Confiteor answered 7/7, 2017 at 15:44 Comment(0)
E
2

As of the current version of the compiler you're using, this is an open question which is being debated on GitHub issue #5341. I agree with you that ref seems like an appropriate way to indicate the intent to return a slice of an array, but we haven't reached closure on the discussion yet.

In the meantime, you should be able to use the following pragma-based workaround (please note that Chapel pragmas are not generally intended for end-user use and that this pragma is unlikely to be supported in the long-term, though I wouldn't expect us to retire it without having come up with a replacement approach like the proposed ref):

record R {
  var A : [0.. #10] int;

  proc full() ref {
    return A;
  }

  pragma "no copy return"
  proc slice() {
    return A[0.. #5];
  }
}

var r : R;
ref x1 = r.full();
ref x2 = r.slice();
ref x3 = x1[0.. #5];
x1[0] = 1;
x2[1] = 2;
x3[2] = 3;
writeln(r);
Eparchy answered 7/7, 2017 at 16:11 Comment(1)
Just a quick follow-up -- it appears that I can return a ref to a slice in an iterator (using a ref return intent). That's an interesting difference with return from a proc....Confiteor

© 2022 - 2024 — McMap. All rights reserved.