Arrays in J programming Language
Asked Answered
L

1

5

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?

Lethia answered 21/5, 2012 at 22:31 Comment(1)
RosettaCode might be a better forum for this type of comparison.Chrono
C
7

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.

Cavit answered 10/6, 2012 at 19:29 Comment(5)
Note that the amend above will be executed "in place". J recognizes that the new array is being assigned to the same name and only writes the changes to the new array. See the jsoftware.com/jwiki/Essays/In-Place%20Operations . In my experience the dyadic verb From jsoftware.com/help/dictionary/d520.htm {is more often used to retrieve items from an array.Chrono
Very good point, @Tikkanz. And thanks for the corrections in your edit.Cavit
OMG! I had no idea amend } had the single left argument feature! I just use the regular take {...Dulcinea
@MPelletier, @Tikkanz's correction that } is technically an adverb helped me internalize an important clarification here. Namely, in my examples above, the actual verb ends up being (j }), which when applied dyadically results in an amended array and when applied monadically does the same thing as Take.Cavit
The appearance of the phrase "two arguments to the left" telegraphs that misunderstanding. J syntax never involves two arguments to a single side. When arguments apply to a dyadic verb, or conjunction, it's an infix form with one argument on each side. In this case j is an argument to the adverb and y an argument to the resulting verb.Ferrand

© 2022 - 2024 — McMap. All rights reserved.