Isaac Asimov

The most exciting phrase to hear in science, the one that heralds new discoveries, is not “Eureka!” (I’ve found it!), but “That’s funny…”

Sometimes everybody wants to get off the beaten track and see the world. See how many exciting discoveries are waiting for you there.

I want to bring your attention to a language, which changed the vision of some things for me. This language is J.

J is an array programming language; it is also functional and even object-oriented. And extremely concise. If you ever called F# ‘cryptic’ because of its operators or started to hate a Scala dev writing /: instead of fold – stop right here, because this language is definitely not for you.

If you have a suspicion that J is for aliens, relax – it’s just different. In terms of grammar J is literally closer to English than C or Java. Who said ‘token’? It’s time to remember the good old ‘word’. Functions are verbs, objects – nouns, statements - sentences etc.

Now let’s experiment!

J is a very rich language. You could study and use it for years, and still consider yourself a beginner.

You’ll get it later =).

But what trapped me for a weekend? I suspect it’s all about unusual code and the new ways of thinking. Maybe something is wrong with me, but J is really fun to write and read! (though the latter requires more effort…)

### Some operators

*: - square
/ - ‘insert’, f/ x y z = x f y f z
% - division
_ - unary minus
>: - increment
# - ‘tally’, the number of elements
@ - ‘atop’, composition
@. – ‘agenda’/switch conjunction
=: - assignment
 - ‘tie’ conjunction
|. – reverse the order
|: - transpose matrix
+/ .* - matrix multiplication

### Conjunctions

First of all, note, that the rightmost function is applied first, so 3*2+1 = 3*(2+1) = 9. How do we calculate, say, the sum of squares?

Square numbers (output is provided in comments starting with NB.):

 1 2   *: 1 2 3 NB. 1 4 9

J has a special operator /, called ‘insert’, I prefer to think about it as ‘reduce’:

 1 2  +/ 1 2 3 NB. 6

The equivalent is 1 + 2 + 3.
So the sum of squares can be written as

 1 2  +/ *: 1 2 3 NB. 14

Conjunction & allows to ‘fix’ the left or right argument:

 1 2 3 4  (^&2) 1 2 3 NB. 1 4 9 (2&^) 1 2 3 NB. 2 4 8

Those who like the forbidden M-word may be confused. But APL-style definition is actually older: monad is a function taking a single argument on the right (like *: above). Dyad takes two arguments, on the left and on the right (40 + 2).

### Hooks and Forks

When two verbs come together, we call it a hook:
(f g) y = y f (g y)

Let’s normalize the list of elements so that their sum is equal to 1 (note, that division is denoted with %). See the naïve variants and a hook:

 1 2 3 4  1 2 5 % (1 + 2 + 5) 1 2 5 % +/ 1 2 5 (% +/) 1 2 5 NB. 0.125 0.25 0.625

Three verbs form a fork:
(f g h) y = (f y) g (h y)

My favorite fork example is mean:

 1 2  (+/ % #) 1 2 3 4 NB. 2.5

The same as

 1 2  (+/ 1 2 3 4) % (# 1 2 3 4) +/ 1 2 3 4 % # 1 2 3 4

### Gerund

The things are getting even more interesting: meet a gerund (the result of )! The sense is similar to English: derived from a verb, but functions as a noun.

 1 2 3 4  +  - NB. ┌─┬─┐ │+│-│ └─┴─┘

We can choose one of the ‘boxes’ with switch conjunction @.:

 1 2 3 4  +  - @. 0 NB. + +  - @. 1 NB. -

Look at the abs implementation:

 1 2 3 4 5  abs =: +  - @. (< & 0) abs 42 NB. 42 abs _42 NB. 42

Gerund can be used together with ‘insert’, e.g. the following statement sentence is equivalent to (50 * 2 % 100):

 1 2  *  % / 50 2 100 NB. 1

### More Verbs!

#. – dyad ‘base’ or monad ‘from base 2’

 1 2 3 4  #. 1 0 0 1 NB. 9 3 #. 2 1 NB. 7

[ and ] – ‘same’, id or argument

 1 2 3 4 5 6 7 8  [ 2 NB. 2 1 [ 2 NB. 1 ] 2 NB. 2 1 ] 2 NB. 2

+/\ – running sum (the same works for * etc)

 1 2 3 4 5 6 7  +/\ 2 3 4 NB. 2 5 9 acc =: /\ + acc 2 3 4 NB. 2 5 9 * acc 2 3 4 NB. 2 6 24

{. - take (n {. L)

 1 2  2 {. 3 4 5 NB. 3 4

}. - drop (n }. L)

 1 2  2 }. 3 4 5 NB. 5

{ - fetch

 1 2 3 4  1 { 3 4 5 6 NB. 4 _1 { 3 4 5 6 NB. 6

/: - sorting

 1 2  /: 10 2 5 3 NB. 1 3 2 0

Remember fork, id and fetch?

 1 2  (/: { ]) 10 2 5 3 NB. 2 3 5 10

q: - prime factors

 1 2  q: 20 NB. 2 2 5

p: - generate nth prime

 1 2  p: 3 NB. 7

sum 100 primes:

 1 2  +/ p: i. 100 NB. 24133

### Modelling Transitions

Having several states and markov-process like transitions probabilities, what is the probability of one of these states at some time? Credit rating migrations can be taken as an example of such transitions.

So we define matrix and initial state probabilities:

 1 2  T =: 3 3 \$ 0.6 0.3 0.1 0.1 0.5 0.4 0 0.1 0.9 x =: 0.3 0.2 0.5

At time y the result is T^y (x u^:n y is equivalent to x u x u …(n times) y). What is the probability of state 3?

 1 2 3 4 5 6 7  T3 =: T +/ .*^:2 T +/ x * (2 {|: T3) NB. 0.6668 +/ x * [ 2 {|: T3 NB. 0.6668 2 { x +/ .* T3 0.6668

The first two options transpose matrix, select the column with index 2 and calculate dot-product with x. The last one uses matrix multiplication verb.

### Present Value

Given the stream of cashflows and rate (in %), we want to calculate PV.
Cashflows: 100 50 Rate: 5%
PV = 100 + 50 / (1 + 5%) = 147.61905

Splitting by steps:
- transform %

 1 2 3  pv =: >:@(] % 100"_) pv 5 NB. 1.05
• compute discount factor
 1 2 3 4 5  pv =: %@>:@(] % 100"_) pv 5 NB. 0.952381 1 % 1.05 0.952381
• reverse cashflows list and sum the discounted values (50 * df^1 + 100 * df^0):
 1 2 3 4  |. 100 50 NB. 50 100 0.952381 #. |. 100 50 NB. 147.619
• combine everything
 1 2 3  pv =: %@>:@(] % 100"_) #. |.@[ 100 50 pv 5 NB. 147.619
 1: pv =: %@>:@(] % 100"_) #. |.@[
2: 100 50 pv 5
147.619
`

### Bonus

If you’re still able to follow this post, here’s a couple of references:
- J Reference Card (2 pages to your rescue);
- financial phrases;
- essay on piano tuning;
- linear recurrences and matrix powers;
- simplex method in J.

Happy crazy coding!