Can I use pass-by-reference to change the size of a container?

73 Views Asked by At

I want my function to add an element to the end of a container, particularly a matrix. It seems that I can use pass-by-reference to alter an existing element within a container, but if I try to alter the size of the container using concat() I get the wrong result.

Here's a working example:

v=[1];
r(~x)=x=concat(x,2);
v \\ Should be [1,2]
%3 = [1]

Can I do this by reference, or will I need to pass by value and make a fresh assignment? If so, is this behaviour expected? I'm using GP/Pari 2.15.0.

1

There are 1 best solutions below

2
Elián On BEST ANSWER

First, in order to pass it as a reference you must also explicitly indicate it with "~" when passing v to r: r(~v).

There are also other problems:

  • The signature of concat() doesn't receive a vector as reference.
  • A vector is immutable so there's no way to achive what you want with it.

You should use a list instead:

v = List([1])
listput(v, 2)

To get the values it's just like any regular vector using the "[]".