Arithmetic mean forwards vs backwards?

110 Views Asked by At

I'm familiar with this way of doing an arithmetic mean in J:

+/ % #

But it's also shown here as

# %~ +/

Are these two versions interchangeable, and if not when should I use one versus the other?

3

There are 3 best solutions below

0
On BEST ANSWER

Dyadic ~ reverses the arguments of a verb. x f~ y is equivalent to y f x. You use ~ when you, um, want to reverse the arguments of a verb.

One of its most common uses is for forks and hooks composition. For example, because y f (g y) is (f g) y you can use ((f~) g) y when you need (g y) f y.

0
On

Dyadic ~ is the "Passive" adverb, which swaps the left and right arguments. Thus x f~ y is the same as y f x. +/ % # and # %~ +/ are equivalent. 2 % 5 gives you 0.4, but 2 %~ 5 gives 2.5.

Among the places this can be handy is checking the results of a line you are working with. While you would presumably be testing something more complicated, you can check yourself by repeating your last line and just adding to the left without rearranging anything or adding parentheses.

   string =. 'J is beyond awesome.'
   'e' = string
0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 1 0
   string #~ 'e' = string
eee

The monadic ~ is the "Reflex" adverb, which causes the modified verb to operate as a dyad, duplicating the single argument for both left and right. While this is another shortcut to arranging your arguments, it is quite different from the dyadic ~. *~ 4 is 16, because you are multiplying y by itself (y * y).

0
On

In the reverse mean example I don't really see a reason that one way would be more effective than the other (V V V form of fork), but because forks in J can be non-symmetric (in the N V V form) I can see some reasons that reversing the middle tine of the fork would be an advantage. Take for example:

   (5 # $) 1 2 3  NB. (N V V) form
3 3 3 3 3
   (5 #~ $) 1 2 3 NB. (N V~ V) becomes effectively (V V N)
5 5 5
   ($ # 5) 1 2 3  NB. (V V N) is a syntax error  
|syntax error
|       ($#5)1 2 3