Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arrays in J programming Language

Tags:

c++

j

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?

like image 230
Daniel Robert Webb Avatar asked May 21 '12 22:05

Daniel Robert Webb


1 Answers

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 jth 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 jth element of m and return it. In this case, we set y to the result.

like image 58
sblom Avatar answered Sep 28 '22 02:09

sblom