How does one do array accesses in the J programming language? For example, using C++ as my pseudocode language:
int M [100]; // declare an array called M
int j = 5; //index into the array
int y = 10; //value to store or load from the array
M[j] = y; // store y into the array
y = M[j]; // load y from the array
What would these sorts of array accesses look like in idiomatic J?
The literal (but still pretty idiomatic) way to write this in J would be as follows.
m =: 100 $ 0 NB. This means create a 1d array consisting of 100 zeros.
j =: 5
y =: 10
With that initialization out of the way, now we're ready for the meat of the answer, which consists of two different usages of the }
adverb ("Item Amend" and "Amend").
m =: y j } m
Putting two arguments to the left of the }
causes J to replace the j
th element of the right hand argument m
with the value y
. NOTE: we had to assign the result back in to m
because the result of y j } m
was simply to compute a new array which incorporated the change that you requested using the }
verb.
y =: j } m
Putting only one argument to the left of the }
causes J to excerpt the j
th element of m
and return it. In this case, we set y to the result.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With