Trains

From NARS2000
Jump to navigationJump to search
<apll>Z←  (f g) R</apll> is called a Monadic Hook — <apll>Z ≡ R f g R</apll>
<apll>Z←L (f g) R</apll> is called a Dyadic Hook — <apll>Z ≡ L f g R</apll>
<apll>Z←  (f g h) R</apll> is called a Monadic Fork — <apll>Z ≡ (f R) g h R</apll>
<apll>Z←L (f g h) R</apll> is called a Dyadic Fork — <apll>Z ≡ (L f R) g L h R</apll>
<apll>Z←  (f g h ...) R</apll>
<apll>Z←L (f g h ...) R</apll>
is also defined for longer Trains
<apll>L</apll> and <apll>R</apll> are arbitrary arrays, <apll>f</apll>, <apll>g</apll>, <apll>h</apll>, etc, are arbitrary functions of any type: primitive, user-defined, system, anonymous, and/or derived.


This clever idea from the designers of J is called Trains where a parenthesized sequence of functions (which normally would signal a SYNTAX ERROR) can be interpreted as per the above descriptions. Very nicely, they fit into and extend the spectrum of function definition syntax from user-defined to dynamic to trains to operator expressions. They are another and very interesting form of functional programming.

Note that the spacing between functions is for visual purposes only — it has no effect on the interpretation.

For example,

<apll> (,⍎)'2+3'</apll>
<apll>←→ '2+3',⍎'2+3'</apll>
<apll>←→ '2+3',5</apll>
<apll>2+3 5</apll>

<apll> avg{is}(+⌿ ÷ ≢)</apll> defines a function that computes the average of a numeric vector.
<apll> avg 1 2 3 4</apll>
<apll>←→ (+⌿ ÷ ≢) 1 2 3 4</apll>
<apll>←→ (+⌿1 2 3 4) ÷ ≢1 2 3 4</apll>
<apll>←→ 10 ÷ 4</apll>
<apll>2.5</apll>

Longer Trains are defined as follows:

<apll> (e f g h) ←→ (e (f g h))</apll>
<apll>(d e f g h) ←→ (d e (f g h))</apll>

and in general

Even length: <apll>(a b c ...) ←→ (a (b c ...))</apll>
Odd length: <apll>(a b c ...) ←→ (a b (c ...))</apll>

For more applications of this concept, see the discussion in the Learning J manual.

There is also a series of tables of common function expressions and their corresponding Train.