Serial matrix in J

J is an APL-like array programming language. It was developed in collaboration with Ken Iverson. The documentation online, especially the tutorials and educational material, is exemplary. This weekend I worked through the J primer. If you can ignore the rhapsodic evangelism for the language, then it’s a robust and thought-provoking introduction to a very different way of programming.

One of my motivations for learning something about J is to understand this article about a combinatorics problem with an application in music theory. Because arrays (and their generalization, n-dimensional matrices) are of fundamental importance in J, it is possible to write a very terse program to compute a twelve-tone matrix. Not a “for” loop in sight!

Let’s have a look at the code, bit by bit.

mod12 =: 12 & |

The | verb consumes an array of numbers on the right and gets remainder mod whatever is the left argument. mod12 uses the & (bond) verb to do partial application. mod12 makes the two-argument form of | a one-argument verb (a monad), where the modulus is fixed.

matrix =. monad : 0
m =. mod12 y -/ (y - (0 { y))
)

This verb definition is designed to operate on an array of integers. The normal order of operations is from right to left, except for parens. Remember that y is an array of integers representing the twelve pitch classes. The { (from) verb is like an indexer, so 0 { y is like head. Let’s call the result first_val. Now we have (y - first_val). The left argument is an array, while right is an atom. No problem for J. The treatment of the concept of verb rank in the primer provides more information.

What does -/ mean? We have - already as a verb with a familiar meaning (subtraction). The J nomenclature calls / an adverb, since it modifies a verb (or a noun) an typically has a “derived verb” as its output. In this case, the commonly-used / can be applied to -. And, like most (all?) J verbs, can itself be used either in a monadic or dyadic case (one- or two-argument use, respectively). Here, -/ generates a table by appending the results from repeated subtraction of the values taken in succession from array the right-hand side from the left-hand side. Oops, almost forgot, do mod12 on the whole thing.

pcs =: i. 12
shuf =: {~ ?~@#

i. is a J “facility” that constructs an array of integers. The implementation of a shuffle function here just serves to come up with a random series for the purpose of computation. It’s interesting how it works, but probably too much to go into here.

newrow =: shuf pcs
matrix newrow

And finally, this is our incantation putting it all together. I think that the expression matrix newrow is “lazily evaluated”, like in Haskell. That is to say that the evaluation of newrow - a verb (shuf) applied to a noun (pcs) doesn’t happen until the expression matrix newrow is evaluated at interpretation time. Anyway, my interest is piqued. To further J adventures!