Thursday, August 16, 2012

Mean of a list

This blog is here for me to share to the world my own personal struggles with the J language. I have only been programming in this language for less than two days, so forgive my incompetence.
I intend this blog to give examples of common and perhaps uncommon functions using J. The purpose is for my own learning more than anything.

The first post will be the easiest function of all, finding the mean of some set of data.
Suppose I want to find the average (mean) age of a collection of adults.

          data=: 20 21 23 23 24 25 27 30 33 34 45 50 56 63
    mean=: +/data%#data

And the answer is... 33.8571. That's it. Easy. Now just a quick explanation:

  • As you might guess + means "plus". 
  • +/ indicates that we are to plus through the list, i.e. 20+21+23+... Forward slash is a special operator that can be used with functions, or "verbs".
  • % is "divide" in J. 
  • # is a special function called "tally" which gives the size of the list.

But what if the answer is too precise? I don't need to know the mean age to 6 significant digits. How about I round it up to three?

        mean=: 3": +/data%#data
or two:
   mean=: 2": +/data%#data

or just round it up to the next integer (i.e. ceiling):
        mean=: >. +/data%#data 

(naturally, <. is the floor function)

We can also turn our function into a more general use function:
         mean=: monad : '3": +/y%#y ' 

Here, we have changed three things. We stuck a "monad" in the middle of the code, and we changed "data" to "y". And then we wrapped the code in single quotes.

Monad - indicates the function is monadic, i.e. takes one argument, on the right side. The other option (that I'm aware of) is Dyadic, which takes two arguments - one on the left, one on the right.
"y" is just a general variable to indicate the list which we will use as the argument. In C related languages it would look something like this:
       float mean(int[] y){
     ...
   }

Finally, the single quotes (never double) wraps the actual code of the function (or verb as they're called).

 




   

No comments:

Post a Comment