<< >> Contents Help

# 6. Starting To Write In J

It's time to write some simple J programs. Writing code without loops will be a shock at first. Many accomplished C programmers give up because they find that writing every program is a struggle, and they remember how easy it was in C. I hope you will have more persistence. If you do, you will soon stop thinking in loops, translating each one into J; instead, you will think directly about operand cells, and the code will flow effortlessly.

In C, when you are going to operate on some array, say x[3][4][5], you write the code from the outside in. You know you are going to need 3 nested loops to touch all the cells; you write the control structure for each loop (possibly after thinking a bit about the order of nesting); finally, you fill in code at whatever nesting level it fits. Even if all your work is in the innermost loop, you have to write all the enclosing layers just to be able to index the array. When I was writing in C, I made sure my output was measured in lines of code, so that I could call this 'productivity'.

In J, you grab the heart of the watermelon rather than munching your way in starting at the rind. You decide what rank of operand cell you are going to work on, and you write the verb to operate on a cell. You give the verb the rank of the cells it operates on, and then you don't care about the shape of the operand, because J's implicit looping will apply the verb to all the cells, no matter how many there are. A pleasant side effect of this way of coding is that the verbs you write can be applied to operands of any shape: write a verb to calculate the current value of a loan, and you can use that very verb to calculate the current value of all loans at a branch, or at all branches in the city, or all over the state.

We will write a number of J verbs starting from their C counterparts so you can see how you need to change your thinking. For these examples, we will imagine we are in the payroll department of a small consulting business, and we will answer certain questions concerning some arrays defined as follows:

empno[nemp] (in J, just empno) - employee number for each member of the staff. The number of employees is nemp.

payrate[nemp] - number of dollars per hour the employee is paid

billrate[nemp] - number of dollars per hour the customer is billed for the services of this employee

clientlist[nclients] - every client has a number; this is the list of all of them. The number of clients is nclient.

emp_client[nemp] - number of the client this employee is billed to

hoursworked[nemp][31] - for each employee, and for each day of the month, the number of hours worked

To get you started thinking about cells rather than loops, I am going to suggest that you use C-style pseudocode written in a way that is easily translatable into J. Your progress in J will be measured by how little you have to use this crutch.

Problem 1: How many hours did each employee work? The C code for this is:

void emphours(hrs)

int hrs[ ]; // result: hrs[i] is hours for employee i

{

int i, j;

for(i = 0;i<nemp;++i)

for(j = 0,hrs[i] = 0;j<31;++j)hrs[i] += hoursworked[i][j];

}

The first step in translating this into J is to write the loops, but without loop indexes: instead, indicate what elements will be operated on:

for (each employee)

for(each day)take the sum of hoursworked

Now, figure out what ranks the operands have. The hoursworked items that are added are scalars, so we will be looping over a list of them; that means we want the sum of items of a rank-1 list. So the inner loop is going to be +/"1 . What about the outer loop? The information for each employee has rank 1 (each employee is represented in hoursworked by a single row), so a verb applied to each employee should have rank 1. Note that we don't worry about the actual shape of hoursworked—once we figure out that our verb is going to operate on 1-cells, we let J's implicit looping handle any additional axes. We build up the loops by applying the rank conjunction for each one, so we have the inner loop +/"1 and the outer loop of rank 1; combined, they are +/"1"1 . The "1"1 can be changed to a single "1, and we get the final program:

emphours =: monad : '+/"1 hoursworked'

Problem 2: How much did each employee earn in wages? The C code is:

void empearnings(earns)

int earns[ ]; // result: earns[i] is wages for employee i

{

int i, j;

for(i = 0;i<nemp;++i) {

for(j = 0,earns[i] = 0;j<31;++j)earns[i] += hoursworked[i][j];

earns[i] *= payrate[i];

}

}

When we write the pseudocode, we will change the algorithm just a bit: rather than multiplying each total by the billing rate just after the total is calculated, we will make one loop to calculate the totals, and then a second pass to multiply by the billing rate. This is a case where good J practice differs from good C practice. Because of the implicit looping that is performed on all verbs, you get better performance if you let each verb operate on as much data as possible. You may at first worry that you're using too much memory, or that you might misuse the processor's caches; get over it. Apply verbs to large operands. The pseudocode is:

for (each employee)

for(each day)take the sum of hoursworked

for(each pair of wage_rate and sum)multiply the pair

The first two loops are just +/"1 hoursworked as before. The last loop clearly multiplies scalars, so it is *"0 . We note that dyad * has rank 0, so we don't need to specify the rank, and we get the final program:

empearns =: monad : 'payrate * +/"1 hoursworked'

Problem 3: How much profit did each employee bring in? C code:

void empprofit(profit)

int profit[ ]; // result: profit[i] is profit from employee i

{

int i, j, temp;

for(i = 0;i<nemp;++i) {

for(j = 0, temp = 0;j<31;++j)temp += hoursworked[i][j];

profit[i] = temp * (billrate[i] - payrate[i]);

}

}

Again, we create a new loop to calculate the list of profit for each employee:

for (each employee)

for(each day)take the sum of hoursworked

for (each employee)take billing_rate - wage_rate;

for(each pair of profit and sum)multiply the pair

The profit is clearly a difference of scalars applied to two lists, therefore it will be -"0 or equivalently simply - . The program then is

empprofit =: monad define

(billrate - payrate) * +/"1 hoursworked

)

<< >> Contents Help