Learning J

I recently decided it had been too long since I taught myself a random obscure programming language. (Something like five years, in fact. Yikes!) So I started to pick up J. J is a descendant of APL, which is known mostly for being typed with the world’s craziest character set:

World’s craziest character set.

APL uses those characters for one- and two-letter mnemonics of every array manipulation primitive (and higher-order function of array manipulation primitives) you could ever want, and then about 10x more. J is like APL that you can write without a custom keyboard.

What does J do differently from your garden-variety functional language? The most interesting thing is probably how functions work. Most programming languages use the standard functional syntax: prefix notation with comma-separated arguments. J, by contrast, has only unary prefix operators and binary infix operators, and function notation is more linguistically structured (even going so far as to call the functions verbs).

This isn’t as nice as prefix-paren notation for complicated architecture-astronautics, but it makes up for it by allowing concise primitives for function combination (like forks and hooks) that would be impossible to parse in other languages. For instance, you can define an average function as average =: +/ % #—to be read as “the average is the running sum divided by the length.” This uses a fork (_ ? _ where the left and right verbs are unary and the middle is binary) and an adverb (/, the equivalent of “fold” or “reduce”) to write in one line (and tacitly) what could take three or four in a less-expressive language.

You can write average in one line in something like Python (lambda x: sum(x) / len(x)), but you can’t do that with some of the more complex things people do in J. Rosetta Code is a great place to find examples of this; the most classic one is Conway’s Game of Life in one line:

life=: (_3 _3 (+/ e. 3+0,4&{)@,;._3 ])@(0,0,~0,.0,.~])

It’s certainly harder to parse than the same thing in e.g. Python, but it’s kind of fun to try and figure out how everything works!

Comments

email me replies

format comments in markdown.

Your comment has been submitted! It should appear here within 30 minutes.