% $Header: /climod/cm2/hld/j/doc/local/j_intro/j_intro.tex,v 1.4 1994/12/14 23:22:33 hld Exp $

% \input{include}
% $Header: /climod/cm2/hld/j/doc/local/j_intro/j_intro.tex,v 1.4 1994/12/14 23:22:33 hld Exp $

\documentstyle[twoside,titlepage]{article}

\makeatletter

%$$$ theapa.sty $$$  --- Version 2.0 (Nov. 1991)
%    by Young U. Ryu (young@emx.utexas.edu)

% copyright (C) 1991.
%    Young U. Ryu (young@emx.utexas.edu)
% newapa.sty 2.0 - 1991.
%    Young U. Ryu (young@emx.utexas.edu)
% newapa.sty - copyright (C) 1989, 1990.
%    Stephen N. Spencer (spencer@heinlein.cgrg.ohio.state.edu)
% apalike.sty - copyright (C) 1986, 1988.
%    Susan King (???) and Oren Patashnik (patashnik@score.stanford.edu)
% ulem.sty - copyright (C) 1989.
%    Donald Arseneau (???)

%%
%% A Note on Version Numbering, e.g. `X.Y'
%%    - `X' changes as major updates are done.
%%    - `Y' changes as bugs are fixed or minor updates are done.
%%    - Thus, versions numbered `X.0' could be buggy.
%%    - The bigger 'Y', the less buggy!
%%    - Even if one of `theapa.sty' or `theapa.bst' changes,
%%      version numbers of both will change.
%%

% Version 2.0 Update Notes
%
%    `ulem.sty' (1989) by Donald Arseneau is included
%             - Underlined book titles, etc. are optionally allowed.
%             - The general replacement of emphasized texts by
%               underlined texts is optionally allowed.
%             - See note [6] B.
%
%    Same author, different years
%             - \cite{Apt,MinA,MinB,Bond}
%               ===> Apt (1989), Minsky (1967, 1983), Bond, (1991)
%             - \citeB{Apt,MinA,MinB,Bond}
%               ===> Apt, 1989; Minsky, 1967, 1983; Bond, 1991
%
%    Some Bugs Fixed
%             - \theapasectioning replaces for \newapasectioning
%             - \paragraph replaces for \a@paragraph
%             - \subparagraph replaces for \a@subparagraph

% Copying of this file is authorized only if either
% (1) you make absolutely no changes to your copy, including name, or
% (2) if you do make changes, you name it something other than
% btxbst.doc, plain.sty, unsrt.sty, alpha.sty, and abbrv.sty.
% This restriction helps ensure that all standard styles are identical.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% CAUTION: `theapa' may complain about including `.aux' and `.bbl'  %
%          files generated by using other bibliography styles, even %
%          those by using `newapa'.                                 %
%                                                                   %
%          Be sure to delete `.aux' and `.bbl' files if you switch  %
%          to `theapa' from other bibliography styles.              %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%
% SEE THE FOLLOWING COMMENTS.
%   1 - theapa.bst and \bibitem entry
%   2 - citation formats
%   3 - changing citation functions (if you want)
%   4 - changing citation labels (if you want)
%   5 - enforcing APA style section heading (if you want)
%   6 - notes (including things not implemented and to be implemented)
%
%%%%%
% [1] theapa.bst and \bibitem entry
%
% The ``theapa.bst'' BibTeX bibliography style creates citations with labels:
%       \BCAY{author-info}{abbrev. author-info}{year}
%
%%%%%
% [2] Citation Formats
%
% The citations are enclosed within parentheses. ``(,)''
%     as default. But one may change them.
% Short author lists use the ``et al.'' construct.
% These labels are processed by the following LaTeX commands:
%
%%%
% See Version 2 Update Notes
% ^^^^^^^^^^^^^^^^^^^^^^^^^^
% \cite[optional notes]{Key(s)}
%     -> automatically switches from \fullcite to \shortcite
% \citeA[optional notes]{key}
%     -> automatically switches from \fullciteA to \shortciteA
%     Note: ONE AND ONLY ONE KEY.
% \citeB{keys}
%     -> automatically switches from \fullciteB to \shortciteB
%     Note: if \citeB[Notes]{keys} if given, notes will be ingored.
% \citeC[optional notes]{key} or \fullciteauthor[optional notes]{key}
%     -> automatically switches from \fullciteC to \shortciteC
%
% \citeyear[optional notes]{key(s)} -> (Year1, Year2, ...)
%
%%%
% \fullcite[optional notes]{Key(s)}
%     -> (Authors1, Year1; Authors2, Year2; ..., optional notes)
% \fullciteA[optional notes]{key}
%     -> Authors (Year, optional notes)
%     Note: ONE AND ONLY ONE KEY.
%           \fullciteA[pp.~3--5]{Apt88,Lloyd87} does not make sense at all.
%           In this case, the outcome will look aweful.
% \fullciteB{keys}
%     -> Authors1 (Year1), Authors2 (Year2), ...
%     Note: if \fullciteB[Notes]{keys} if given, notes will be ingored,
%           because it does not make sense at all.
% \fullciteC[optional notes]{key} or \fullciteauthor[optional notes]{key}
%     -> Authors1, Authors2, ...
%
%%%
% The difference between `\shortciteXXX' and `\fullciteXXX':
% is that `\shortciteXXX' gives `First author et al.'
% if no. authors >= 3.
%    
% \shortcite[optional notes]{Key(s)}
%     -> (Short Authors1, Year1; Short Authors2, Year2; ..., optional notes)
% \shortciteA[optional notes]{key}
%     -> Short Authors (Year, optional notes)
%     Note: ONE AND ONLY ONE KEY.
%           \shortciteA[pp.~3--5]{Apt88,Lloyd87} does not make sense at all.
%           In this case, the outcome will look aweful.
% \shortciteB{keys}
%     -> Authors1 (Year1), Authors2 (Year2), ...
%     Note: if \shortciteB[Notes]{keys} is given, notes will be ingored,
%           because it does not make sense at all.
% \shortciteC[optional notes]{key} or \shortciteauthor[optional notes]{key}
%     -> Short Authors1, Short Authors2, ...
%
%%%%%
% [3] Changing Citation Punctuations
%
% \citepunct{open paren}%
%           {between authors}%
%           {between author year}%
%           {between citations}%
%           {before notes}%
%           {closing paren}%
%           {open quote for article titles}%
%           {closing quote for article titles}
%
% For example,
%   \citepunct{[}{and}{ }{, }{: }{]}{``}{,''}
%        - use square brackets
%          `and' between authors
%          space between author and year
%          comma between citations
%          comma before notes
%     e.g. [Apt and van Emden 1986, Lloyd 1985: Notes]
%        - ``article title,''  (in double quote marks and comma in them)
%
% The default is:
%   \citepunct{(}{\&}{, }{; }{, }{)}{}{.}
%
% Notice spaces around punctuations in \citepunct!!!
%
%%%%%
% [4] Changing Citation Labels
%
% \citelabels{editor label}%
%           {editors label}%
%           {volume label}%
%           {number label}%
%           {edition label}%
%           {page label}%
%           {pages label}%
%           {chapter label}%
%           {tech. rep. label}
%
% For example,
%   \citelabels{, editor}{, editors}{Volume}{Number}{edition}%
%              {page}{pages}{chapter}{Technical report}
%
% The default is:
%   \citelabels{ (Ed.)}{ (Eds.)}{Vol.}{No.}{edition}%
%              {p.}{pp.}{chap.}{Tech.\ rep.}
%
% Notice spaces around lables in \citelabels!!!
%
%%%%%
% [5] Enforcing APA Style Section Heading 
%
% \theapasectioning redefines section headings as described
%       by the APA Publication Manual
%       \section - level 1       (toc entry, pageheading)
%               Normalsize, Centered, Uppercase, Boldface
%       \subsection - level 2    (toc entry)
%               Normalsize, Centered Boldfaced
%       \subsection - level 3    (toc entry)
%               Normalsize, Centered Underlined
%       \paragraph - level 4
%               Normalsize, Underlined
%       \subparagraph - level 5
%               Normalsize, Underlined followed by texts in the same line
%
%  if * is placed after \section, \subsection, \subsubsection,
%   section headings are not listed in the table of contents
%
%%%%%
% [6] Others
%
%  A. `mastersreport', `dbathesis', `eddthesis' added.
%      Why? - Some schools also allow master's report as well as
%              master's thesis.
%           - DBA (Doctor of Business Administration) and
%             Ed.D. (Doctor of Education) are also popluar
%             doctoral degrees.
%
%  B. Underlined (not italic) book titles, etc.
%     - A few journal publication editors and schools,
%       who do not appreciate new electronic typesetting and
%       desktop publishing technologies, require underlined
%       book titles, etc.
%     - To do this, I included `ulem.sty' (C) 1989 by Donald Arseneau.
%     - `\UnderlinedBemOnly' underlines book titles, etc. in Reference.
%       `\UnderlinedEm' replaces emphasized texts by underlined texts
%                       both in the body and reference of your document.
%
%  C. Not implemented yet (!): to be implemented soon
%     - None as Nov. 15, 1991
%     - May be added as request
%
%  D. Not implemented: I don't know if I can do in the near future !!! ;-)
%     - Same last name but different people
%          (C. Lewis, 1958; D. Lewis, 1973)
%           ^               ^
%       It must be done in the BibTeX style file (theapa.bst).
%
%  E. NO GUARANTEE, absolutely (You know what I mean.)
%
%  F. Bug reports
%     - Your bug report(s) is (are) welcome(d).
%     - E-mail me to ONE of the following:
%
%             young@emx.utexas.edu (Internet)
%             ^^^^^
%             youngryu@bongo.cc.utexas.edu (Internet)
%                  ^^^
%             youngr@utxvm.cc.utexas.edu (Internet)
%                  ^
%             youngr@utxvm (Bitnet)
%                  ^
%             bgbg767@utxvms (Bitnet)
%             ^^^^^^^
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%%%%%%%%%%%%%%%%%%%
% cite punctuations %
%%%%%%%%%%%%%%%%%%%%%
\def\BBOP{(}                        % open parenthesis
\def\BBA{and}                       % between authors
\def\BBAY{, }                       % between author(s) and year
\def\BBC{; }                        % between cites
\def\BBN{, }                        % before note
\def\BBCP{)}                        % closing parenthesis
\def\BBOQ{}                         % open quote for article title
\def\BBCQ{.}                        % closing quote for article title
%
%\def\citepunct#1#2#3#4#5#6#7#8{%
%    \def\BBOP{#1}
%    \def\BBA{#2}
%    \def\BBAY{#3}
%    \def\BBC{#4}
%    \def\BBN{#5}
%    \def\BBCP{#6}
%    \def\BBOQ{#7}
%    \def\BBCQ{#8} }

%%%%%%%%%%%%%%%
% cite labels %
%%%%%%%%%%%%%%%

\def\BED{ Ed.}                % editor
\def\BEDS{ Eds.}              % editors
\def\BVOL{Vol.}                 % volume name
\def\BNUM{No.}                  % number name
\def\BEd{edition}               % edition
%\def\BPG{p.}                    % page
%\def\BPGS{pp.}                  % pages
\def\BPG{}                    % page
\def\BPGS{}                  % pages
\def\BCH{chap.}                 % chapter
\def\BTR{Tech.\ Rep.}           % (default) technical report type name

%\def\citelabels#1#2#3#4#5#6#7#8#9{%
%     \def\BED{#1}                % editor
%     \def\BEDS{#2}
%     \def\BVOL{#3}
%     \def\BNUM{#4}
%     \def\BEd{#5}                % edition
%     \def\BPG{#6}
%     \def\BPGS{#7}
%     \def\BCH{#8}
%     \def\BTR{#9} }

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Upper or Lowercase article titles %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%\def\@Ucase#1{\uppercase{#1}}
%\def\BUcase#1{\lowercase{\@Ucase #1}}
%\def\notitlecasechange{\def\BUcase##1{##1}}
%
%%%%%%%%%%%%%
% citations %
%%%%%%%%%%%%%
%
%
% \cite -> Short Author List (Year)
% \citeB -> (Short Author List, Year)
%
\def\citeB{\def\@citeseppen{-1000}%
    \def\@cite##1##2{%
        ##1\if@tempswa \BBN##2\fi}%
    \def\BCAY##1##2##3{##2}\@citedata}
\def\cite{\def\@citeseppen{-1000}%
    \def\@cite##1##2{##1\BBCP}%
    \def\BCAY##1##2##3{##2}\@citedataB}
% Author only citation
\def\citea{\def\@citeseppen{-1000}%
    \def\@cite##1##2{%
        ##1\if@tempswa \BBN##2\fi}%
    \def\BCAY##1##2##3{##2}\@citedataC}
% to keep compatibility with newapa2.0
%
% \citeyear -> (Year)
%
%\def\citeyear{\def\@citeseppen{-1000}%
%    \def\@cite##1##2{%
%        \BBOP##1\if@tempswa \BBN##2\fi\BBCP}%
%    \def\BCAY##1##2##3{}\@citedataD}

% Year is separately handled by \Y<citation key>
\def\bibcite#1#2{\global\@namedef{b@#1}{#2}%           name list
                 \global\@namedef{Y@#1}{\@year@#2}}%    year

\def\@year@\BCAY#1#2#3{#3}
%
\newif\if@F@cite\@F@citetrue    % first author of a multi-author reference?
%
\def\@citedata{\@ifnextchar [{\@tempswatrue\@citedatax}{\@tempswafalse\@citedatax[]}}
%
\def\@citedatax[#1]#2{%
    \if@filesw\immediate\write\@auxout{\string\citation{#2}}\fi%
    \edef\@citeP{}%
    \@cite{\@for\@citeb:=#2\do%
           {\@ifundefined{b@\@citeb}%
              {{\bf ?}\@warning
                 {Citation `\@citeb' on page \thepage \space undefined}%
               \edef\@citeP{}\@F@citefalse}%
              {\@ifundefined{flag@\@citeb}%
               {\global\@namedef{flag@\@citeb}{DUMMY}%
                \def\BCA##1##2{##1}}%
               {\def\BCA##1##2{##2}}%
               \edef\@my@dummy{\csname b@\@citeb\endcsname}%
               \ifx\@my@dummy\@citeP%
                   \if@F@cite\@F@citefalse\else{, }\fi%
                   \csname Y@\@citeb\endcsname%
               \else%
                   \if@F@cite\@F@citefalse\else{\BBC}\fi%
                   \csname b@\@citeb\endcsname\BBAY\csname Y@\@citeb\endcsname%
               \fi%
               \edef\@citeP{\csname b@\@citeb\endcsname}%
              }%
           }%
          }{#1}%
    \@F@citetrue}
%
%\def\@citedataA{\@ifnextchar[{\@tempswatrue\@citedataxA}{\@tempswafalse\@citedataxA[]}}
%%
%\def\@citedataxA[#1]#2{%
%    \if@filesw\immediate\write\@auxout{\string\citation{#2}}\fi%
%    \edef\@citeP{}%
%    \@cite{\@for\@citeb:=#2\do%
%           {\@ifundefined{b@\@citeb}%
%              {{\bf ?}\@warning
%                 {Citation `\@citeb' on page \thepage \space undefined}%
%                \edef\@citeP{}\@F@citefalse}%
%              {\@ifundefined{flag@\@citeb}%
%               {\global\@namedef{flag@\@citeb}{zzz}%
%                \def\BCA##1##2{##1}}%
%               {\def\BCA##1##2{##2}}%
%               \edef\@my@dummy{\csname b@\@citeb\endcsname}%
%               \ifx\@my@dummy\@citeP%
%                   \if@F@cite\@F@citefalse\else{, }\fi%
%                   \csname Y@\@citeb\endcsname%
%               \else%
%                   \if@F@cite\@F@citefalse\else{, }\fi%
%                   \csname b@\@citeb\endcsname\ \BBOP\csname Y@\@citeb\endcsname%
%               \fi%
%               \edef\@citeP{\csname b@\@citeb\endcsname}%
%              }%
%           }%
%          }{#1}%
%    \@F@citetrue}
%
%
\def\@citedataB{\@ifnextchar[{\@tempswatrue\@citedataxB}{\@tempswafalse\@citedataxB[]}}
%
\def\@citedataxB[#1]#2{%
    \if@filesw\immediate\write\@auxout{\string\citation{#2}}\fi%
    \edef\@citeP{}%
    \@cite{\@for\@citeb:=#2\do%
           {\@ifundefined{b@\@citeb}%
              {{\bf ?}\@warning
                 {Citation `\@citeb' on page \thepage \space undefined}%
                \edef\@citeP{}\@F@citefalse}%
              {\@ifundefined{flag@\@citeb}%
               {\global\@namedef{flag@\@citeb}{zzz}%
                \def\BCA##1##2{##1}}%
               {\def\BCA##1##2{##2}}%
               \edef\@my@dummy{\csname b@\@citeb\endcsname}%
               \ifx\@my@dummy\@citeP%
                   \if@F@cite\@F@citefalse\else{, }\fi%
                   \csname Y@\@citeb\endcsname%
               \else%
                   \if@F@cite\@F@citefalse\else{\BBCP, }\fi%
                   \csname b@\@citeb\endcsname\ \BBOP\csname Y@\@citeb\endcsname%
               \fi%
               \edef\@citeP{\csname b@\@citeb\endcsname}%
              }%
           }%
          }{#1}%
    \@F@citetrue}
%
\def\@citedataC{\@ifnextchar[{\@tempswatrue\@citedataxC}{\@tempswafalse\@citedataxC[]}}
%%
\def\@citedataxC[#1]#2{%
    \if@filesw\immediate\write\@auxout{\string\citation{#2}}\fi%
    \edef\@citeP{}%
    \@cite{\@for\@citeb:=#2\do%
           {\@ifundefined{b@\@citeb}%
              {{\bf ?}\@warning
                 {Citation `\@citeb' on page \thepage \space undefined}%
                \edef\@citeP{}\@F@citefalse}%
              {\@ifundefined{flag@\@citeb}%
               {\global\@namedef{flag@\@citeb}{zzz}%
                \def\BCA##1##2{##1}}%
               {\def\BCA##1##2{##2}}%
               \edef\@my@dummy{\csname b@\@citeb\endcsname}%
               \ifx\@my@dummy\@citeP%
                   \if@F@cite\@F@citefalse\else{}\fi%
               \else%
                   \if@F@cite\@F@citefalse\else{, }\fi%
                   \csname b@\@citeb\endcsname%
               \fi%
               \edef\@citeP{\csname b@\@citeb\endcsname}%
              }%
           }%
          }{#1}%
    \@F@citetrue}
%
%\def\@citedataD{\@ifnextchar[{\@tempswatrue\@citedataxD}{\@tempswafalse\@citedataxD[]}}
%
%\def\@citedataxD[#1]#2{%
%    \if@filesw\immediate\write\@auxout{\string\citation{#2}}\fi%
%    \edef\@citeP{}%
%    \@cite{\@for\@citeb:=#2\do%
%           {\@ifundefined{b@\@citeb}%
%              {{\bf ?}\@warning
%                 {Citation `\@citeb' on page \thepage \space undefined}%
%                \edef\@citeP{}\@F@citefalse}%
%              {\@ifundefined{flag@\@citeb}%
%               {\global\@namedef{flag@\@citeb}{zzz}%
%                \def\BCA##1##2{##1}}%
%               {\def\BCA##1##2{##2}}%
%               \edef\@my@dummy{\csname b@\@citeb\endcsname}%
%               \ifx\@my@dummy\@citeP%
%                   \if@F@cite\@F@citefalse\else{, }\fi%
%                   \csname Y@\@citeb\endcsname%
%               \else%
%                   \if@F@cite\@F@citefalse\else{, }\fi%
%                   \csname Y@\@citeb\endcsname%
%               \fi%
%               \edef\@citeP{\csname b@\@citeb\endcsname}%
%              }%
%           }%
%          }{#1}%
%    \@F@citetrue}
%%%%%%%

%
% (from apalike.sty)
% No labels in the bibliography.
% Set length of hanging indentation for bibliography entries.
\def\@biblabel#1{}
\newlength{\bibhang}
\setlength{\bibhang}{2em}
%
\def\bibname{References}
\def\thebibliography#1{%
     \section*{\bibname\@mkboth{\bibname}{\bibname}}
     \addcontentsline{toc}{section}{References}
     \list
     {\relax}{\setlength{\labelsep}{0em}
     \setlength{\itemindent}{-\bibhang}
     \setlength{\leftmargin}{\bibhang}}
     \def\newblock{\hskip .11em plus .33em minus .07em}
     \sloppy\clubpenalty4000\widowpenalty4000
     \sfcode`\.=1000\relax}
\let\endthebibliography=\endlist


\makeatother

\pagestyle{headings}
\oddsidemargin 2mm
\evensidemargin -8mm
\topmargin=-20mm
\textwidth=165mm
\textheight=226mm
\raggedbottom
%\flushbottom

\newcommand{\Item}[1]{
\begin{list}{$\bullet$}{
\setlength{\topsep}{0pt}
\setlength{\parskip}{0pt}
\setlength{\parsep}{0pt}
\setlength{\itemsep}{0pt}
\setlength{\leftmargin}{\parindent}
}
\item #1
\end{list}
}

\newcommand{\aItem}[2]{{\bf #1} & #2\\}

\newcommand{\oldbaselineskip}{\baselineskip}

\newenvironment{examp}[1]{
  \renewcommand{\oldbaselineskip}{\baselineskip}
  \baselineskip=#1
  \pagebreak[3]
}{
  \pagebreak[3]
  \baselineskip=\oldbaselineskip
}

% normal example environment
\newcommand{\bex}{\begin{examp}{\oldbaselineskip}\begin{verbatim}}
\newcommand{\eex}{\end{examp}}

% squashed example environment
\newcommand{\bsex}{\begin{examp}{2.0mm}\begin{verbatim}}

\newcommand{\V}{\verb}

\newcommand{\degree}{$^\circ$}

\begin{document}

\begin{titlepage}
\vspace*{50mm}
\begin{center}
\begin{Huge}
{\bf Introduction to J}\\
\end{Huge}
\vspace{10mm}
\begin{LARGE}
{\bf \copyright \ Harvey Davies}\\
\end{LARGE}
\vspace{10mm}
\begin{Large}
CSIRO Division of Atmospheric Research\\
\vspace{5mm}
Private Bag No. 1,\\
Mordialloc 3195,\\
Australia\\
\vspace{5mm}
email: hld@dar.csiro.au\\
\vspace{10mm}
\today
\end{Large}
\end{center}
\vspace*{50mm}
\end{titlepage}

%{\samepage \tableofcontents}
\tableofcontents

\vfill

\section{Introduction}

{\em J} is an exciting new programming language designed by Ken Iverson
(well-known as the creator of {\em APL}) and Roger Hui.
Iverson describes J as a dialect of APL,
but the differences from APL are more than sufficient to justify the new
name.

Why the name {\em J\/}?
I once assumed a connection with the imaginary number $\sqrt{-1}$, which
is conventionally denoted in mathematics by $j$ (or $i$).
In fact this is represented by \V.0j1. within the J language.
However Roger Hui provides the simple explanation
``{\em It is easy to type}'' in \cite{Hui92}.

The following are some important features of J:
\Item{It uses the standard ASCII character set rather than the special APL
  character set.}
\Item{It is array-oriented.  Arrays are treated in a very systematic,
  general manner.  The elements of arrays can themselves be arrays.}
\Item{It has
a rich set of {\em verbs} (functions) to manipulate {\em nouns} (arrays).}
\Item{{\em Verbs}
  can be modified, combined and defined using powerful facilities
  such as {\em adverbs} and {\em conjunctions}.
  For example, the conjunction \V!D.! gives the derivative of a verb.}
\Item{Expressions are used to define verbs, adverbs and conjunctions, as
  well as nouns.  All four types of object are assigned names in the same
  way.}
\Item{Verbs can be defined in traditional {\em explicit} manner using {\em pronouns}
  (variables representing nouns) to represent arguments.}
\Item{Verbs can also be defined using a succinct {\em tacit} (functional)
  programming style which avoids the need to mention the arguments of the
  verb.}

Although J can be used as a very sophisticated programming language, it can
also be used in a very simple way as a desk calculator.  Thus if you type
`\V/2+3/', J displays the result `\V/5/'.

\vfill
Iverson's company {\em Iverson Software Inc.} (ISI)
has implemented J for MS Windows, MS DOS, Macintosh and Unix.
The most recent release is called {\em J Release 2} and this comes with
two manuals \cite{Iverson94} and \cite{Burke94}.
The {\em J Release 2 for Windows} version includes powerful tools (like
those in {\em Visual Basic}) for developing Windows programs and is
available in personal and commercial editions.

\vfill
\begin{flushleft}
ISI products are distributed worldwide by:\\
Strand Software Systems,\\
2 Adelaide Street West, Suite 203,\\
Toronto,
Ontario,
Canada M5H 1L6\\
Tel.: (416) 369-1630\\
Fax.: (416) 369-9590\\
Email: \verb;anne.faust@rose.com;\\
\vfill
The Australian agents are:\\
Adaptable Systems,\\
49 First Street,\\
Black Rock,
Victoria 3193,
Australia\\
Tel.: (+61 3) 589 5578\\
Fax.: (+61 3) 589 3220
\end{flushleft}

\vfill
The Internet newsgroup \V!comp.lang.apl! includes a great deal of discussion
about J.
An {\em FAQ} document providing answers to {\em Frequently Asked Questions}
is available by anonymous ftp to \V!watserv1.waterloo.edu!.
The file is called \V!faq! and will be found in the directory 
\V!languages/apl/j!, which also contains other documentation and
source code for the old version 7, which (unlike J Release 2) is available as
shareware.

\pagebreak
\section{Overview}

This section is intended to provide a brief overview of the major features,
many of which are covered in more detail later.

\subsection{Getting Started}

The following annotated log demonstrates some of the basic facilities.  Note
that command lines (which you type in) are indented while result lines are
not.  Anything following ``\V/NB./'' is treated as comment.

You may like to run J while reading the following.  This will enable you to
clarify points by experimenting.  It is the best way of learning J.

I have followed Iverson in using grammatical terms in place of mathematical
terms.  Thus {\em noun} is used in place of {\em operand} and {\em verb} is used in place
of {\em function} or {\em operator}.

\bex
   3 + 2                NB. Verb '+' adds nouns '3' and '2'
5
   2-5                  NB. Negative sign is '_' not '-'
_3
   2 ^ 4                NB. Power
16
   2e1 * _1.3           NB. '2e1' means '2*10^1' i.e. 20
_26
   9 % 6                NB. Division symbol is '%' not '/'
1.5
   radius=. 7           NB. 'radius' is pronoun.  Assign is '=.' not '='.
   radius               NB. Display value (assign does not display)
7
   2p1 * radius         NB. '2p1' means '2*pi^1' (c.f. '2e1' above)
43.9823
   7 3 _2 * _1 4 _9     NB. Arguments can be vectors
_7 12 18
   radius =. 7 3 9.5    NB. Vector containing three radii
   2p1 * radius         NB. Three circumferences (scalar times vector)
43.9823 18.8496 59.6903
   1p1 * radius^2       NB. Three areas
153.938 28.2743 283.529
\end{verbatim}
\eex

\subsection{Monadic and Dyadic Verbs}

All the above examples have nouns (arguments) on both the left and right of
the verb.
The following example has only a right argument.
\bex
   -radius
_7 _3 _9.5
\end{verbatim}
\eex
Such a {\em unary minus} is familiar in ordinary mathematical notation
and computer languages.
Iverson has extended this concept to allow most verbs to take
either one or two arguments.  Such verbs are said to be {\em ambivalent}.
The two
meanings are often related, but this is not always the case.  A verb with a
single argument (e.g.  `\V/-radius/' above) is said to have valence 1 and
is called a {\em monadic verb} or {\em monad}.  A verb with two arguments (e.g.
'\V/2-5/' above) is said to have valence 2 and is called a
{\em dyadic verb} or {\em dyad}.

The primitives (in-built verbs, etc.) are denoted by one of the following:
\Item{a single graphic (e.g. `{\tt \%}')}
\Item{a single graphic followed by `{\tt .}' or `{\tt :}' (e.g. `{\tt =.}')}
\Item{a name followed by `{\tt .}' (e.g. `{\tt NB.}')}

The following demonstrates some common monads.
\bex
   % 2 3 5 2r3          NB. Monadic '%' means 'reciprocal'.  '2r3' means '2/3'
0.5 0.333333 0.2 1.5
   ^ 1 2 3              NB. Monadic '^' means 'exp'
2.71828 7.38906 20.0855
   i. 9                 NB. Monadic 'i.' generates integers
0 1 2 3 4 5 6 7 8
   y =. _8 + 2 * i. 9   NB. and thus any arithmetic progression
   y
_8 _6 _4 _2 0 2 4 6 8
   * y                  NB. Monadic '*' is sign (signum) function
_1 _1 _1 _1 0 1 1 1 1
   | y                  NB. Monadic '|' is magnitude (abs)
8 6 4 2 0 2 4 6 8
   6 | y                NB. Dyadic '|' is mod (remainder or residue)
4 0 2 4 0 2 4 0 2
\end{verbatim}
\eex

New verbs (called {\em pro-verbs}) are defined by assignment, very much as
pronouns are defined.  This can be used to assign familiar aliases, such as
\V'mod' in the following example.

\bex
   mod=. |
   3 mod y
1 0 2 1 0 2 1 0 2
   %: 4 16 9            NB. Monadic '%:' means square root
2 4 3
   %: _9                NB. '0j3' means '0 + 3*j' where j is square root of _1
0j3
   3 %: 125 8 27        NB. Dyadic 'x %: y' means x'th root of y
5 2 3
   !4 1.5 999           NB. Factorial. Monad always has argument on its right
24 1.32934 _
\end{verbatim}
\eex

\V/!y/ is generalised to non-integers by defining it as $\Gamma(y+1)$.  The
third element `\V/_/' means `$\infty$', indicating overflow in this case.

\subsection{Combining Verbs}

We next consider how verbs are combined to form more complicated expressions.
The following expression represents
$-e^{\frac{1}{2}}$
using three monads:
\bex
   -^%2
_1.64872
\end{verbatim}
\eex

Note that the order of execution has to be {\em right-to-left}.
It is treated as
\bex
-(^(% 2))
\end{verbatim}
\eex

Most computer languages have complex rules for combining verbs.  For example,
Fortran 77 has nine levels of operator precedence; most operators are
left-associative (executed left-to-right), one (\V/**/) is
right-associative and some (e.g. \V/.EQ./) are non-associative.

Iverson's notation has no such precedence rules.  All verbs have equal
rights!  There seems to be no good reason to give certain verbs precedence
over others.  Such rules would be horrendous in J which has over 70
primitive verbs and the capacity to define any number of others.  The only
precedence rule in J is that adverbs and conjunctions have higher priority
than verbs.

The order is simply right-to-left for both dyads and monads.  This may seem
strange at first, but it really is much simpler than the complex traditional
rules.  There is much less need for parentheses.

\bex
   9-5+2                NB. Treated as 9-(5+2)
2
   3*4-2                NB. Simply right-to-left again
6
   (3*4)-2              NB. Parentheses can be used
10
   _2+3*4               NB. But can often be avoided
10
   3+%4                 NB. Combination of monad & dyad
3.25
   y                    NB. Using y defined above
_8 _6 _4 _2 0 2 4 6 8
   -3**y-2              NB. -( 3 * ( sign(y-2) ) )
3 3 3 3 3 0 _3 _3 _3
\end{verbatim}
\eex

\subsection{Trigonometric Functions}

The dyadic verb `\V/o./' provides various trigonometric and hyperbolic
functions.  Note the mnemonic association between the circular letter
'\V/o/' and functions related to the circle.

\bex
   1 o. 0.5p1           NB. '1 o. x' means 'sin x' so this is 'sin pi%2'
1
   2 o. 60 % 180p_1     NB. '2 o. x' means 'cos x' so this is 'cos 60 deg'
0.5
\end{verbatim}
\eex

It is convenient to assign conventional names (as pro-verbs) to these
functions.  This can be done using the {\em bond} conjunction `\V/&/' to define
a monad in terms of a dyad with one argument bonded (i.e. fixed or constant).

\bex
   sin=. 1 & o.            NB. sin is o. with left argument bound to 1
   sin 360 30 90 % 180p_1  NB. sin of 360 30 90 degrees
0 0.5 1
\end{verbatim}
\eex

\subsection{Comparisons and Logical (Boolean) Values}

The following comparison dyads return the result 1 for {\em true} and 0 for
{\em false}.  Note that here `\V.:.' means {\em equal}.

\bex
   3 6 4 < 2 9 4        NB. less than
0 1 0
   3 6 4 <: 2 9 4       NB. less than or equal to
0 1 1
   3 6 4 = 2 9 4        NB. equal to
0 0 1
   3 6 4 ~: 2 9 4       NB. not equal to
1 1 0
   3 6 4 > 2 9 4        NB. greater than
1 0 0
   3 6 4 >: 2 9 4       NB. greater than or equal to
1 0 1
\end{verbatim}
\eex

As shown above, dyadic `\V/=/' does {\em element-by-element} comparison.  There
is also a dyadic verb {\em match} (\V/-:/) which tests whether the two entire
arguments are {\em equal in all respects} or {\em congruent},
which is conventionally represented by the symbol `$\equiv$'.
So it is mnemonic to again consider the `\V.:.' to mean `=',
giving three horizontal lines in all.

\bex
   3 6 4 -: 2 9 4
0
   3 6 4 -: 3 6 4
1
\end{verbatim}
\eex

The dyadic verbs `\V/<./' and `\V/>./' give the {\em minimum} and {\em maximum}

\bex
   3 6 4 <. 2 9 4       NB. lesser of (minimum)
2 6 4
   3 6 4 >. 2 9 4       NB. greater of (maximum)
3 9 4
   1 >. 8 <. 3 0 9 7    NB. restrict range to 1 to 8 (Again right-to-left!)
3 1 8 7
\end{verbatim}
\eex

An advantage of treating {\em true}
and {\em false} as numbers is shown by the following.

\bex
   3 0 2 # 2 8 5        NB. 'x#y' means x copies of y
2 2 2 5 5
   v =. 9 4 3 5 0
   v >: 4
1 1 0 1 0
   (v >: 4) # v         NB. Select elements greater than or equal to 4
9 4 5
\end{verbatim}
\eex

The logical operations {\em and}, {\em or} and {\em not} can be done as follows.

\bex
0 0 1 1 *. 0 1 0 1      NB. and
0 0 0 1
0 0 1 1 +. 0 1 0 1      NB. or
0 1 1 1
-. 0 1                  NB. not
1 0
\end{verbatim}
\eex

\subsection{Character Nouns}

So far all nouns have been numeric.  J automatically determines whether the
type is {\em Boolean} (i.e. 0 or 1), {\em integer}, {\em real} or {\em complex}.
J also allows
{\em character} nouns, which are arrays whose elements are ASCII characters.

\bex
   cv=. 'Sam can''t!'   NB. Define character vector 'cv'
   cv
Sam can't!
   cv = 'a'             NB. Many verbs apply also to character nouns
0 1 0 0 0 1 0 0 0 0
   cv > 'a'             NB. But some do not
|domain error
|   cv  >'a'
   cv -: 6              NB. Some even allow a mixture of both types
0
\end{verbatim}
\eex

\subsection{Adverb `Insert' ({\tt /})}

We have seen how J extends many verbs to arrays in an element by element
fashion.  We now consider some other facilities such as adverbs.  An adverb
has a single argument on its left.  In the following, a verb to sum the
elements of a vector (or the columns of a matrix, etc.) is defined by
`\V!+/!'.
The adverb `\V!/!' is called {\em insert} because it has the
effect of inserting its
verb argument between the items of the noun argument of the resulting verb.

\bex
   data=. 4 _1 5 2
   +/ data              NB. Monadic '+/' means 'sigma' i.e. sum
10
   sum=. +/             NB. So let us define it as the pro-verb 'sum'
   sum data
10
   */ data              NB. Similarly, monadic '*/' means 'product'
_40
   >./ data             NB. and monadic '>./' means 'maximum'
5
   -/ data              NB. and monadic '-/' means 'alternating sum'
8
   4 - _1 - 5 - 2       NB. In other words this (Remember right-to-left!)
8
   # data               NB. Monadic '#' means 'tally' or 'number of elements'
4
   (sum data) % # data  NB. So arithmetic mean is sum divided by tally
2.5
\end{verbatim}
\eex

\subsection{Tacit Definition, Forks and Hooks}

You may be surprised to learn that the above calculation of an arithmetic mean
can be written more succinctly as

\bex
   (sum % #) data
2.5
   sum % # data         NB. which is quite different to this
0.25
   sum ( % ( # data ) ) NB. which means this
0.25
   % ( # data )         NB. or this (sum of a scalar is simply itself)
0.25
\end{verbatim}
\eex

The original expression `\V!(sum % #)!' is evaluated first (because it is
parenthesised) to define a verb meaning {\em arithmetic mean}.  How can a sequence
(or {\em train}) of verbs define another verb?  Here we have a train of three
verbs called a {\em fork} and the resultant verb is used monadically.  In this
case\\
$(verb_{1}\; verb_{2}\; verb_{3})\; noun$ \\
is defined to mean \\
$(verb_{1}\; noun)\; verb_{2}\; verb_{3}\; noun$.

Forks and other trains provide a powerful way of defining verbs.  The following
definition of \verb;am; is a classic example of {\em tacit definition}.

\bex
   am=. sum % #         NB. Define pro-verb 'am' as arithmetic mean
   am data
2.5
   max=. >./            NB. Similarly 'range' can be defined as 'max-min'
   min=. <./
   range=. max - min
   range data
6
\end{verbatim}
\eex

The following illustrates the dyadic meaning of a fork:
\bex
   5(+*-)3              NB. This dyadic fork means 'product of sum and difference'
16
   (5+3)*(5-3)          NB. i.e. this
16
\end{verbatim}
\eex

A train of two verbs is called a {\em hook}.
The monadic and dyadic meanings of hooks are illustrated by the following:
\bex
   (+%)4                NB. This monadic hook means 'add reciprocal'
4.25
   4+%4                 NB. i.e. this
4.25
   7(+%)4               NB. Dyadic use of hook
7.25
   7+%4                 NB. means simply this
7.25
\end{verbatim}
\eex

\subsection{Explicit Definition}

Note that such {\em tacit} verb definitions do not involve noun arguments.  We
could have used the conjunction `\V.:.'
to define \verb;am; using a more traditional {\em explicit definition} such as:

\bex
   am=. '(sum y.) % # y.' : ''
   am data
2.5
\end{verbatim}
\eex

Note that in any explicit definition, \V/y./ represents the right
argument of the resultant verb.
The left (character) argument of `\V.:.' defines the monad and the right
argument defines the dyad.
In the above example the right argument is \V/''/ which means {\em undefined}.
We could define dyadic `\V/am/' to give a weighted mean as follows:

\bex
   am=. '(sum y.) % # y.' : '(sum x. * y.) % sum x.' NB. 'x.' is left argument
   1 2 0 3 am data      NB. Weighted mean
1.33333
   am 1 2 0 3 # data    NB. Equivalent to this (using monadic 'am')
1.33333
\end{verbatim}
\eex

\section{Array Manipulation}

\subsection{Extracting Elements from Vectors}

Elements can be extracted from arrays using the verb `\V/{/' called
{\em from}.  The left argument is the subscript, with 0 corresponding to the first
item.

\bex
   data                 NB. Display vector 'data' again
4 _1 5 2
   0 { data             NB. Extract first element from 'data'
4
   2 1 { data           NB. Extract third (2) and second (1) elements
5 _1
   _1 _1 _3 { data      NB. -ve subscripts are relative to end (_1 is last)
2 2 _1
\end{verbatim}
\eex

The verb {\em from} (\V/{/) can be used to write conditional expressions like
the C ternary operator `\V/?:/'
\bex
   (3 < i. 6) { 2 9     NB. If element > 3 then result is 9, otherwise 2
2 2 2 2 9 9
   2 + 7 * 3 < i. 6     NB. Another way of expressing this step function
2 2 2 2 9 9
   data i. _1 2         NB. Dyadic 'i.'  Find index of values _1 & 2 in 'data'
1 3
   {. data              NB. Monadic '{.' is 'head' i.e. 1st element
4
   {: data              NB. Monadic '{:' is 'tail' i.e. final element
2
   }. data              NB. Monadic '}.' is 'behead' i.e. all except head
_1 5 2
   }: data              NB. Monadic '}:' is 'curtail' i.e. all except tail
4 _1 5
   2 {. data            NB. Dyadic '{.' is 'take' i.e. take first 2 elements
4 _1
   _3 {. data           NB. If left argument -ve then take from end
_1 5 2
   2 }. data            NB. Dyadic '}.' is 'drop' i.e. drop first 2 elements
5 2
   |. data              NB. Monadic '|.' means 'reverse' (Mnemonic: '|' is axis)
2 5 _1 4
   1 |. data            NB. Dyadic '|.' means 'rotate'
_1 5 2 4
\end{verbatim}
\eex

\subsection{Changing Elements of Vector}

Specific array elements can be changed by using the adverb `\V/}/'
({\em amend}) to define a dyadic verb to change these elements.  Say we want to
change element 1 to 0 and element 2 to 9.

\bex
   v=. 1 2 }            NB. Define verb 'v' to change elements 1 & 2
   0 9 v data           NB. Use it
4 0 9 2
   0 9 (1 2 }) data     NB. All in single expression
4 0 9 2
\end{verbatim}
\eex

Note that this amendment process has three arguments.  One is the argument of
the adverb and two are arguments of the resultant verb.

\subsection{Matrices}

A {\em matrix} (or {\em table}) is a 2-dimensional rectangular array.
The following illustrates the construction and manipulation of matrices.
\bex
   mat=. 2 3$4 _1 5 2 _7 0  NB. Dyadic '$' forms array with specified shape & elements
   mat                  NB. Display matrix 'mat'
4 _1 5
2 _7 0
   $mat                 NB. Monadic '$' gives shape (Mnemonic: $ like S = Shape)
2 3
   $$mat                NB. Shape of shape is 'rank' i.e. number of dimensions
2
   +/mat                NB. Column sums
6 _8 5
   sum mat              NB. since we defined 'sum=. +/' above
6 _8 5
   sum"1 mat            NB. Row sums.  '"1' means over row vectors (i.e. rank 1)
8 _5
   # mat                NB. Number of rows
2
   (+/ mat) % # mat     NB. Column means
3 _4 2.5
   am mat               NB. Using above definition of 'am'
3 _4 2.5
   am"1 mat             NB. Row means
2.66667 _1.66667
   0 { mat              NB. Row 0
4 _1 5
   2 { 0 { mat          NB. Element 2 of row 0
5
   |: mat               NB. Transpose
 4  2
_1 _7
 5  0
\end{verbatim}
\eex

\subsection{Concatenating Arrays}

Vectors and scalars
can be concatenated as follows using the dyad {\em append items} (\V.,.).
\bex
   data                 NB. As defined above
4 _1 5 2
   data , 13            NB. Concatenate vector and scalar
4 _1 5 2 13
   13 _9,data           NB. Concatenate two vectors
13 _9 4 _1 5 2
   9,0                  NB. Concatenate two scalars
9 0
\end{verbatim}
\eex

The following shows how this verb handles matrices:
\bex
   mat                  NB. As defined above
4 _1 5
2 _7 0
   mat2x3=. i. 2 3      NB. Vector argument of i. specifies shape
   mat2x3
0 1 2
3 4 5
   mat , mat2x3         NB. Concatenate columns of two matrices
4 _1 5
2 _7 0
0  1 2
3  4 5
   mat , 3              NB. Concatenate matrix & scalar to add row
4 _1 5
2 _7 0
3  3 3
   mat , 7 8 9          NB. Concatenate matrix & vector to add row
4 _1 5
2 _7 0
7  8 9
   mat2x2=. i. 2 2      NB. Define another matrix
   mat2x2
0 1
2 3
   mat2x2 ,"1 mat       NB. Concatenate rows of two matrices
0 1 4 _1 5
2 3 2 _7 0
\end{verbatim}
\eex

Note how the conjunction {\em rank} (\V.".) was again used to specify the
rank of the arguments. In this case \V.,"1. means concatenation of
vectors i.e. rows.
Dyadic {\em append} has the same effect, as shown in the first of the following
examples:
\bex
   mat2x2 ,. mat        NB. Append matrix to matrix
0 1 4 _1 5
2 3 2 _7 0
   mat ,. 3             NB. Append scalar to matrix
4 _1 5 3
2 _7 0 3
   1 2 ,. 3 5           NB. Append vector to vector
1 3
2 5
\end{verbatim}
\eex

Dyadic \V!,:! is called {\em laminate}.
It concatenates the arguments over a new first dimension
after reshaping them to have the same shape.
\bex
   mat ,: 3             NB. Laminate matrix with scalar
4 _1 5
2 _7 0

3  3 3
3  3 3
   $ mat ,: 3           NB. Shape
2 2 3
   mat ,: 6 7 8 9       NB. Laminate matrix with vector
4 _1 5 0
2 _7 0 0

6  7 8 9
0  0 0 0
   $ mat ,: 6 7 8 9     NB. Shape
2 2 4
   mat ,: mat2x2        NB. Laminate matrix with matrix
4 _1 5
2 _7 0

0  1 0
2  3 0
   $ mat ,: mat2x2      NB. Shape
2 2 3
\end{verbatim}
\eex

\subsection{Monads which Reshape Arrays}

Monadic \V.,. is called {\em ravel} and produces a vector containing the
elements of the argument.
\bex
   , mat                NB. Ravel of matrix
4 _1 5 2 _7 0
   $ , mat              NB. Shape
6
   , 3                  NB. Ravel of scalar
3
   $ , 3                NB. Shape
1
\end{verbatim}
\eex

Monadic \V!,.! is called {\em ravel items} and produces a matrix.
\bex
   ,. 3                 NB. Ravel-items of scalar
3
   $ ,. 3               NB. Shape
1 1
   ,. 2 3               NB. Ravel-items of vector gives 1-column matrix
2
3
   $ ,. 2 3             NB. Shape
2 1
\end{verbatim}
\eex

Monadic \V!,:! is called {\em itemize} and adds a dimension of 1.
\bex
   ,: 5 7               NB. Itemize of vector gives 1-row matrix
5 7
   $ ,: 5 7
1 2
   ,: mat               NB. Itemize of matrix gives 3D array
4 _1 5
2 _7 0
   $ ,: mat
1 2 3
\end{verbatim}
\eex

\subsection{Function Table}

We have seen above how the adverb {\em insert} (\V./.)
defines monadic verbs such
as sum above.
Such verbs also have a dyadic meaning called {\em function table} or
{\em outer product}.

\bex
   2 3 4 */ 0 1 2 3 4   NB. Dyadic product (multiplication table)
0 2 4  6  8
0 3 6  9 12
0 4 8 12 16
\end{verbatim}
\eex

Let $v$ be the verb argument of `/'.\\
Let $X$ be the vector left argument of `$v$/'.\\
Let $Y$ be the vector right argument of `$v$/'.\\
Let $Z$ be the matrix result.\\
$Z_{ij}$ is defined as $X_{i}\: v \: Y_{j}$.

In the above example $v$ is `\V/*/', $X$ is `2 3 4' and $Y$ is `0 1 2 3 4'.
So $Z$ is defined by:\\
$Z_{ij} = X_{i}\: *  \: Y_{j}$

This is a convenient way of defining many matrices.  For example:
\bex
   i=. i. 5
   i
0 1 2 3 4
   i =/ i               NB. Identity matrix
1 0 0 0 0
0 1 0 0 0
0 0 1 0 0
0 0 0 1 0
0 0 0 0 1
\end{verbatim}
\eex

Dyadic `$x!y$' gives the number of combinations of $y$ things, $x$ at a time.

\bex
   |: i !/ i            NB. Pascal's triangle (|: is 'transpose')
1 0 0 0 0
1 1 0 0 0
1 2 1 0 0
1 3 3 1 0
1 4 6 4 1
\end{verbatim}
\eex
\subsection{Linear Algebra}

Simultaneous linear equations can be solved using `\V/%./', which is
{\em matrix divide} as explained below.  For example let us solve the system:\\
\begin{tabular}{rrrrr}
$3x$ & $-$  & $6y$ & $=$  & $10$\\
$9x$ & $+$ & $15y$ & $=$ & $-14$
\end{tabular}
\bex
   A=. 2 2 $ 3 _6 9 15  NB. Define 2 by 2 matrix
   A
3 _6
9 15
   10 _14 %. A          NB. Matrix-divide right-hand-side by this matrix
0.666667 _1.33333
\end{verbatim}
\eex

Thus the solution is $x = \frac{2}{3}$ and $y = -\frac{4}{3}$.  This can be
checked using matrix multiplication.  Matrix multiplication is not a
primitive, but it can easily be defined using the conjunction `.' meaning {\em dot
product}.

\bex
   matmul =. sum . *    NB. Matrix product is dyadic sum of products
   A matmul 2r3 _4r3    NB. Check result
10 _14
   %. A                 NB. Matrix inverse
  0.151515 0.0606061
_0.0909091  0.030303
   (%. A) matmul 10 _14 NB. Matrix divide 'x %. y' is defined as (%. y) matmul x
0.666667 _1.33333
   det =. -/ . *        NB. Determinant is monadic alternating sum of products
   det A
99
   (3 * 15) - (_6 * 9)  NB. In other words, this.
99
\end{verbatim}
\eex

\subsection{Boxed Arrays}

The {\em array} is the only data structure in J.
A {\em scalar} is treated as an array with rank 0.
All the elements of an array must be of the same data type.
This is the reason for the failure of
the following attempt to mix characters with numbers:
\bex
   3 , 'A'
|domain error
|   3  ,'A'
\end{verbatim}
\eex

Besides data types {\em numeric} and {\em character}, there is another
called {\em boxed array} or simply {\em boxed}.
Boxed arrays can be elements of higher level arrays.
One can think of putting arrays into boxes and then forming an array of
these boxes.

Internally, the C code represents a box as a pointer to (i.e. address of)
the array inside.
The ability to nest arrays to any depth provides an elegant means of
representing data structures such as {\em trees}.

Any array can be boxed using the monadic verb {\em box} (\V!<!).
A useful mnemonic is to imagine a `\V!>!' on the right
(e.g. \V!<3>!) to complete the box.
The following example illustrates the use of \V!<!
\bsex
   b =. < 2 _6                  NB. b is box containing vector
   b                            NB. Display b.  Note the surrounding box
+----+
|2 _6|
+----+
   $ b                          NB. Shape of b

   # $ b                        NB. Rank of b
0
\end{verbatim}
\eex

Thus \V!b! is a scalar (rank 0 array) even though it contains a vector.
Since boxed arrays are scalars they
can be used as the elements of a higher level array.
\bsex
   a =. b , < 3                 NB. Append boxed scalar to boxed vector
   a
+----+-+
|2 _6|3|
+----+-+
   $ a                          NB. Shape of a
2
   0 { a                        NB. 1st (0) element of a
+----+
|2 _6|
+----+
   1 } a                        NB. 2nd (1) element of a
+-+
|3|
+-+
\end{verbatim}
\eex
The effect of {\em box} (\V!<!)
is reversed by the monadic verb {\em open} (\V!>!).
\bex
   > b                          NB. Open b
2 _6
   > > b                        NB. Open has no effect if already open
2 _6
   > 0 { a                      NB. Open 1st element
2 _6
   $ > 0 { a                    NB. Check shape
2
   > 1 } a                      NB. Open 2nd element
3
   $ > 1 } a                    NB. Shape is empty i.e. scalar

   # $ > 1 } a                  NB. i.e. rank = 0
0
\end{verbatim}
\eex

The following shows how
\Item{dyad {\em link} (\V!;!)
   combines the action of `\V!<!' and `\V!,!'}
\Item{several arrays can be combined into a single (array) entity}
\bsex
   (< 2 _6) , < 3               NB. Instead of this
+----+-+
|2 _6|3|
+----+-+
   2 _6 ; 3                     NB. we can use ';' (link)
+----+-+
|2 _6|3|
+----+-+
   'hello' ; 3 9                NB. Can link character & numeric arrays
+-----+---+
|hello|3 9|
+-----+---+
   c =. 8 5 ; 'x' ; a ; 9       NB. And even boxed arrays
   c
+---+-+--------+-+
|8 5|x|+----+-+|9|
|   | ||2 _6|3|| |
|   | |+----+-+| |
+---+-+--------+-+
   1 { > 0 { > 2 { c            NB. Extract element from inner box
_6
\end{verbatim}
\eex
The following phone list example begins by showing how boxed arrays can be
used to store text containing lines of different lengths.
\bsex
   names =. 'Ed' ; 'Mary' ; 'Tom'
   names
+--+----+---+
|Ed|Mary|Tom|
+--+----+---+
   $ names
3
   matrix =. > names            NB. Open whole array, not just single element
   matrix
Ed
Mary
Tom
   $ matrix                     NB. Shape of matrix
3 4
   matrix = ' '                 NB. Show position of spaces
0 0 1 1
0 0 0 0
0 0 0 1
   list =. 2 3 $ names , 123 ; 432 ; 987
   list
+---+----+---+
|Ed |Mary|Tom|
+---+----+---+
|123|432 |987|
+---+----+---+
   |: list                      NB. Transpose
+----+---+
|Ed  |123|
+----+---+
|Mary|432|
+----+---+
|Tom |987|
+----+---+
\end{verbatim}
\eex

The following examples show how the
conjunction {\em under} (\V!&.!) can be used to apply some verb to
each of the enclosed arrays.
\bsex
   d =. 3 0 4 ; a
   d
+-----+----+-+
|3 0 4|2 _6|3|
+-----+----+-+
   +/ &. > d                    NB. Sum of each boxed array element
+-+--+-+
|7|_4|3|
+-+--+-+
   |. &. > d                    NB. Reverse each boxed array element
+-----+----+-+
|4 0 3|_6 2|3|
+-----+----+-+
\end{verbatim}
\eex

Verbs are displayed in boxes.
In fact verbs are represented internally as boxed arrays.
The following example shows how one can display a verb.
Note how the boxes show the order of execution.
\bsex
   range =. >./ - <./           NB. Define verb using fork
   range                        NB. Display verb
+------+-+------+
|+--+-+|-|+--+-+|
||>.|/|| ||<.|/||
|+--+-+| |+--+-+|
+------+-+------+
\end{verbatim}
\eex

\subsubsection{Boxed Subscripts}

One important use of boxed arrays is as subscripts.
\bsex
   table=. 'cat','dog',:'emu' NB. Create 3x3 matrix
   $table
3 3
   table
cat
dog
emu
   ]s=. <2 1                  NB. Define scalar single-level boxed subscript
+---+
|2 1|
+---+
   s{table                    NB. which specifies individual elements
m
   1{2{table                  NB. i.e. same as this
m
   ]s=. 2 1;0 0;1 0           NB. Vector single-level boxed subscript
+---+---+---+
|2 1|0 0|1 0|
+---+---+---+
   s{table                    NB. gives several individual specifications
mcd
   ]s=. <2 1;0 2              NB. 2-level boxed subscript
+---------+
|+---+---+|
||2 1|0 2||
|+---+---+|
+---------+
   s{table                    NB. means rows 2 & 1, columns 0 & 2
eu
dg
   ]s=. <(<2 1),<<1           NB. 3rd level means 'all except'
+---------+
|+---+---+|
||2 1|+-+||
||   ||1|||
||   |+-+||
|+---+---+|
+---------+
   s{table                    NB. i.e. same (rows 2 & 1, all columns except 1)
eu
dg
\end{verbatim}
\eex

\section{J Programming}

So far we have been mainly concerned with using J as a powerful calculator
using the primitive (inbuilt) verbs.
We now consider how to
\Item{define new verbs and thus use J as a programming language.}
\Item{store J code (including definitions of verbs) in script files}

\subsection{Defining Verbs with Explicit Definition ({\tt :}) Conjunction}

We first consider the case where both the left and right arguments are
character vectors.
The following example shows how the left argument of `{\tt :}'
defines the monadic meaning and the right argument defines the dyadic meaning.
The pronouns {\tt x.} and {\tt y.} respectively
represent the left and right arguments of the defined verb.
\bsex
   max=. '>. / y.' : 'x. >. y.'         NB. Define ambivalent verb 'max'
   max                                  NB. Display definition
+-------+-+--------+
|>. / y.|:|x. >. y.|
+-------+-+--------+
   max 1 8 _3 0                         NB. Use monad
8
   _2 0 1 max 1 _9 3                    NB. Use dyad
1 0 3
\end{verbatim}
\eex

The arguments of `{\tt :}' can be any character expressions.
So the above definition of `{\tt max}' is equivalent to:
\bex
   max=. '>.'
   max=. (max , '/ y.') : ('x.' , max , 'y.')
   max 1 8 _3 0
8
   _2 0 1 max 1 _9 3
1 0 3
\end{verbatim}
\eex

Note that {\tt max} was first defined as a noun, then redefined as a verb.
It was necessary to parenthesise the character expressions
because conjunctions (like '\V!:!')
and adverbs have higher precedence than verbs.

An expression defining a verb can be used directly without
assigning it to a pro-verb (and thus giving it a name).
The above example could be done directly as:
\bex
   m=. '>. / y.'                        NB. Monad
   d=. 'x. >. y.'                       NB. Dyad
   m : d 1 8 _3 0
8
   _2 0 1 m : d 1 _9 3
1 0 3
\end{verbatim}
\eex

The following shows
that the space preceding `{\tt :}' is needed to prevent `{\tt m:}'
being treated as a single primitive object.
(Two-character primitives have either `{\tt :}' or `{\tt .}' as
the second character.)
\bex
   m:d 1 8 _3 0
|value error
|     m: d 1 8 _3 0
\end{verbatim}
\eex

The left and right arguments of `{\tt :}' can be verbs, as in the
following:
\bex
   max=. >. / : >.
   max 1 8 _3 0
8
   _2 0 1 max 1 _9 3
1 0 3
   m : >. 1 8 _3 0                      NB. Can also have 'string : verb'
8
   >. / : d 1 8 _3 0                    NB. or 'verb : string'
8
\end{verbatim}
\eex

There was no need to parenthesise the left argument of `{\tt :}'
because adverbs (like `{\tt /}') and conjunctions are executed left to right.

\subsection{Examples: Verbs for Statistics}

I must acknowledge \cite{Smillie} who provided some of the following
examples.
His document is available by \V!ftp! to \V!ftp.cs.ualberta.ca! in
file \V!pub/smillie/intj.ps!.

\subsubsection{Arithmetic Mean}

The following shows various ways of defining our old friend the arithmetic mean.
\bex
   data=. 1.5 8.1 _1.2 4
   am=. '(+ / y.) % # y.' : ''
   am data
3.1
   '(+/ y.) % # y.' : '' data
3.1
   (+/ % #) data                        NB. Tacit definition
3.1
\end{verbatim}
\eex

The monad {\em same} (\V!]!) simply gives the value of its argument.
It can be used as follows to assign and display in a single sentence.
The value of a sentence (expression) is displayed only if the final
(left-most) operation is not assignment.
For example:
\bex
   ] mean=. am data
3.1
   mean
3.1
\end{verbatim}
\eex

Let us now generalise verb \V.am. to optionally take a
left argument providing weights (e.g. frequencies).
\bex
   f=. 1 2 0 1                          NB. frequencies
   am=. '(+ / y.) % # y.' : '(+/ x. * y.) % +/ x.'
   am data
3.1
   f am data
5.425
   ] all=. f # data                     NB. Check
1.5 8.1 8.1 4
   am all
5.425
\end{verbatim}
\eex

\subsubsection{Frequency Table}

What about the reverse process of defining frequencies from raw data?
This can be done using {\em self-classify}, which is monadic `{\tt =}'.
But first let us consider the related monad {\em nub} (\V!~.!) which
provides a list of unique items.
\bex
   raw=. 1.4 _3 1.4 0 1.4 _3
   ] nub=. ~. raw                       NB. Define nub
1.4 _3 0
   nub =/ raw                           NB. Relate raw to nub
1 0 1 0 1 0
0 1 0 0 0 1
0 0 0 1 0 0
   = raw                                NB. Which is equivalent to monadic =
1 0 1 0 1 0
0 1 0 0 0 1
0 0 0 1 0 0
   ] f=. +/"1 = raw                     NB. Row sums are required frequencies
3 2 1
   ] i=. /: nub                         NB. Ascending sort permutation vector
1 2 0
   nub=. i { nub                        NB. Use to sort nub
   nub
_3 0 1.4
   ] f=. i { f                          NB. & f
2 1 3
   ] cf=. +/\ f                         NB. Cumulative frequencies
2 3 6
   nub ,. f ,. cf
 _3 2 2
  0 1 3
1.4 3 6
\end{verbatim}
\eex

Several of the verbs and adverbs used here are new and require some explanation.
Verb {\em grade up} ({\tt /:})
gives a permuted (re-ordered) subscript vector corresponding to
ascending sorted values.
In other words
\bex
(/: x) { x
\end{verbatim}
\eex
gives {\tt x} in ascending order.

Adverb {\em prefix} (\V!\!) defines successive items of the result by
repeatedly applying its left verb argument
to the first $i$ items of its noun right argument, with $i$ varying
from 1 to the number of items in the noun argument.
In the above case the left argument was `{\tt +/}', so the resultant verb gave
partial sums.
The following is another example of the use of {\em prefix}:
\bsex
   <\ 2 4 6 8
+-+---+-----+-------+
|2|2 4|2 4 6|2 4 6 8|
+-+---+-----+-------+
\end{verbatim}
\eex

Let us now define a monadic
verb to produce such a frequency table from raw data.
We use the conjunction `{\tt :}' with both arguments of 0.
This causes the definition to be read from the following lines,
terminating with a line containing just `{\tt )}'.

The result of the verb is the result of the final sentence.
This result (like all within verbs) is not displayed.
\bex
freqTable=. 0 : 0
nub=. ~. y.                             NB. nub
f=. +/"1 = y.
i=. /: nub
nub=. i { nub
f=. i { f
cf=. +/\ f
N=. {: cf                               NB. tail of cf is total number cases
nub ,. f ,. cf ,. (f%N) ,. cf%N
)
   freqTable raw
 _3 2 2 0.333333 0.333333
  0 1 3 0.166667      0.5
1.4 3 6      0.5        1
   N
|value error
\end{verbatim}
\eex

Columns were added for the {\em relative frequency} and
{\em relative cumulative frequency}.
Note that \V!N! is undefined at the J command level
because it is local to verb \V!freqTable!.
A verb can define {\em global} objects by assigning with `\V!=:!'
rather than `\V!=.!'.

\subsubsection{Simulation of Dice}

The expression `\V!?6!' gives a random number from 0 to 5.
Let us define a verb \V!dice! to simulate $y$ trials,
each involving $x$ (default 1) dice.
The dyad gives the sum of $x$ dice in each of the $y$ trials.
\bex
   dice=. '1 dice y.' : '+/ 1 + ? (x. , y.) $ 6'
   dice
+---------+-+----------------------+
|1 dice y.|:|+/ 1 + ? (x. , y.) $ 6|
+---------+-+----------------------+
   freqTable dice 10000                 NB. single die
1 1650  1650  0.165  0.165
2 1631  3281 0.1631 0.3281
3 1637  4918 0.1637 0.4918
4 1751  6669 0.1751 0.6669
5 1670  8339  0.167 0.8339
6 1661 10000 0.1661      1
   freqTable 2 dice 10000               NB. 2 dice
 2  276   276 0.0276 0.0276
 3  547   823 0.0547 0.0823
 4  841  1664 0.0841 0.1664
 5 1085  2749 0.1085 0.2749
 6 1380  4129  0.138 0.4129
 7 1657  5786 0.1657 0.5786
 8 1413  7199 0.1413 0.7199
 9 1116  8315 0.1116 0.8315
10  858  9173 0.0858 0.9173
11  549  9722 0.0549 0.9722
12  278 10000 0.0278      1
\end{verbatim}
\eex

Let us now make the number of sides on each die a variable \V.nsides..
This time we use the \V!0 : 0! facility:
\bex
   dice=. 0 : 0
1 dice y.
:
+/ 1 + ? (x. , y.) $ nsides
)
   dice
+---------+-+---------------------------+
|1 dice y.|:|+/ 1 + ? (x. , y.) $ nsides|
+---------+-+---------------------------+
   nsides=. 2
   freqTable dice 10000
1 4956  4956 0.4956 0.4956
2 5044 10000 0.5044      1
\end{verbatim}
\eex

Note how the line containing just `\V!:!' separates the definition of
the monad from that of the dyad.
This was not needed in the definition of \V!freqTable!
because there was no dyad.
Also note that the pronoun \V.nsides. was visible from within the verb
even though it was defined using {\em local assign} (\V!=.!).

\subsection{J-Scripts}

A file containing J sentences is called a {\em J-script} and conventionally
has a filename with extension \V!.js!.
The effect of executing a script is the same as if you typed in its contents.
Under {\em J Release 2 for Windows} you can execute a script by selecting
the menu item {\em Run/File}.

It is also possible to execute J-scripts using verbs defined using {\em foreign conjunction} (\V.!:.), which is discussed further in Section~\ref{sec-foreign}.
The following examples use such a verb called \V;script;, which requires the
following different definitions under Version 7 and Release 2.
\bex
   script=: 0!:2        NB. Version 7
   script=: 0!:1        NB. Release 2
\end{verbatim}
\eex

Say the above definition of verb \V!dice! is stored in a file \V!dice.js!.
The following shows how to
use \V;script; to execute this J-script file and thus define \V!dice!:
Note that the filename argument has to be boxed using \V.<..
\bex
   script < 'dice.js'     NB. Execute file 'dice.js'
   dice
+---------+-+---------------------------+
|1 dice y.|:|+/ 1 + ? (x. , y.) $ nsides|
+---------+-+---------------------------+
\end{verbatim}
\eex

It is usually convenient to define standard verbs and other objects
in a J-script (often named \V!profile.js!) which is automatically executed
when J is started.
See \cite{Burke94} (p52) for further details.

\subsection{Explicit and Tacit Definitions of Standard Deviation, etc.}

The first step is to define a verb \V.dev. which gives {\em deviations from the
mean}.
We will use upper case for {\em explicitly} defined verbs and lower case for
those defined using {\em tacit definition}.
\bex
   obs=. 2.3 5 3.5 6                    NB. observations
   AM=. '(+/ y. % # y.)' : ''           NB. explicit definition of AM
   AM obs
4.2
   am=. +/ % #                          NB. tacit definition of am
   am obs
4.2
   DEV=. 'y. - am y.' : ''              NB. explicit definition of DEV
   DEV obs
_1.9 0.8 _0.7 1.8
   dev=. - am                           NB. tacit definition of dev using hook
   dev obs
_1.9 0.8 _0.7 1.8
\end{verbatim}
\eex

This tacit definition of \V.dev. consists of a train of two verbs `\V.-.' and
`\V.am.'.
A train of two verbs `$v_1 v_2$' is called a {\em hook}.
The monadic meaning of any hook
`$(v_1 v_2) n$'
(where $n$ is the noun argument) is defined as
`$n v_1 v_2 n$'.
Thus `\V!- am!' means {\em subtract mean}.

We now want to
define verbs giving the {\em sum of squares of deviations from the mean}.

One might be tempted to
try `\V!ss=. +/ *: dev!', but this definition is a train of
three verbs (i.e. a {\em fork}), which has a quite different meaning.
We can specify that we simply want one verb executed after another
by specifying them as arguments of the conjunction {\em atop} (\V!@!).
\bex
   SS=. '+/ *: dev y.' : ''             NB. *: is square
   SS obs
7.98
   ss=. +/ @ *: @ dev
   ss obs
7.98
\end{verbatim}
\eex
Next we define verbs giving the {\em variance} and {\em standard deviation}:
\bex
   VAR=. '(ss y.) % # y.' : ''
   VAR obs
1.995
   var=. ss % #                         NB. fork
   var obs
1.995
   SD=. '%: var y.' : ''                NB. %: is square root
   SD obs
1.41244
   sd=. %: @ var
   sd obs
1.41244
\end{verbatim}
\eex

Finally, let us modify these (by subtracting 1 from the sample size)
to give an {\em unbiased estimate}
of the population variance and its square root.
\bex
   VAR1=. '(ss y.) % _1 + # y.' : ''
   VAR1 obs
2.66
   var1=. ss % <: @ #                   NB. <: is decrement (subtract 1)
   var1 obs
2.66
   SD1=. %: @ var1
   SD1 obs
1.63095
   sd1=. %: @ var1
   sd1 obs
1.63095
\end{verbatim}
\eex
This definition of \V.var. is treated as `\V.ss % (<: @ #).' because
the conjunction \V!@! has higher priority than the verbs.
The verb \V.<: @ #. means
{\em one less than the number of items}
and, together with verbs \V.ss. and \V.%., forms a fork.

\section{Adverbs and Conjunctions}

Much of the power of J comes from its ability to
define new verbs, adverbs and conjunctions using expressions
whose operators are {\em adverbs} and {\em conjunctions} and whose arguments are
verbs and nouns.
Computer scientists would describe verbs, adverbs and conjunctions as
{\em first class objects} because J provides facilities to
define them at run time.

An {\em adverb} has a single argument on its left.
A {\em conjunction} is positioned between its two arguments.
Adverbs and conjunctions have higher precedence than verbs and are
executed {\em left-to-right}.

Note how adverbs and conjunctions are identified in the
{\em Vocabulary Table} on the back cover of both \cite{Iverson93} and
\cite{Iverson94}.
Adverbs are in {\em italics} and conjunctions are in {\bf bold}.

\subsection{Adverbs}

Adverbs {\em insert/table} (\V!/!) and {\em amend} (\V!}!) were discussed
previously and will not be considered here.

We also discussed how the adverb {\em prefix/infix} (\V!\!) was used to
define monadic verbs such as {\em partial sum}.
The term {\em infix} refers to its use to define a dyad which applies some
verb to the elements in each position of a moving window.
Thus we can define a {\em moving average} as follows:

\bex
   data =. 8 2 9 3 0 2
   # data                       NB. number of items
6
   am =. +/ % #                 NB. arithmetic mean
   ] ma =. 2 am\ data           NB. moving average with window of length 2
5 5.5 6 1.5 1
   # ma                         NB. number of items
5
   ] ma =. 3 am\ data           NB. moving average with window of length 3
6.33333 4.66667 4 1.66667
   # ma                         NB. number of items
4
\end{verbatim}
\eex
The adverb {\em reflex/commute} (\V!~!) acts on a dyad $u$ to produce
\Item {the {\em reflex} monad defined by $y \ u \ y$}
\Item {the {\em commuted or crossed} dyad defined by $y \ u \ x$}
where $x$ is the left noun argument of the new dyad and $y$ is the right
noun argument of the new monad or dyad.
For example:

\bex
   +~ 4                         NB. Reflex puts argument on left & right
8
   4 + 4                        NB. In other words, this
8
   */~i.4                       NB. Use reflex to produce multiplication table
0 0 0 0
0 1 2 3
0 2 4 6
0 3 6 9
   4 -~ 3                       NB. Commute swaps arguments
_1
   'abcd' {~ 2 , 0              NB. Commute puts subscript on right
ca
\end{verbatim}
\eex

\subsection{Conjunctions}

\subsubsection{Fit or Customize ({\tt !.})}

Conjunction {\em fit (customize)} (\V/!./)
modifies various verbs in various ways.
Often it essentially provides a third argument to a dyad.
The following example shows how
it changes the relative tolerance allowed when deciding whether
two values should be considered equal.

\bex
   9 = 9 + 1e_13                NB. Default (relative) tolerance is 2^_44 (5.7e_14)
1
   9 * 2^_44                    NB. Thus absolute tolerance is this
5.11591e_13
   9 = 9 + 1e_12
0
   9 (= !. 1e_11) 9 + 1e_12     NB. Increase tolerance
1
   9 (= !. 0) 9 + 1e_13         NB. Decrease tolerance to 0 (exact comparison)
0
\end{verbatim}
\eex

\subsubsection{Rank ({\tt "})}

The {\em rank} conjunction ({\tt "})
modifies the verb left argument by changing its rank
to that of the numeric noun right argument.
The rank of a verb is a vector containing three elements corresponding to
the ranks of the monad argument, dyad left argument and dyad right argument.
If the right argument has one element, it specifies all ranks; if two, these
specify the dyadic ranks.
A rank of infinity means that the argument is processed as a whole.
The following illustrates the effect of monadic rank
\bsex
   ] m=. i. 2 3         NB. Define 2x3 matrix
0 1 2
3 4 5
   <"0 m                NB. Box scalars
+-+-+-+
|0|1|2|
+-+-+-+
|3|4|5|
+-+-+-+
   +/"0 m               NB. Sum scalars
0 1 2
3 4 5
   <"1 m                NB. Box vectors
+-----+-----+
|0 1 2|3 4 5|
+-----+-----+
   +/"1 m               NB. Sum vectors
3 12
\end{verbatim}
\eex
\bsex
   <"_ m                NB. Box whole array
+-----+
|0 1 2|
|3 4 5|
+-----+
   +/"_ m               NB. Sum whole array
3 5 7
\end{verbatim}
\eex
The following example
defines an adverb \V.ranks. which provides the rank vector of a verb.
This definition uses
the {\em explicit definition} conjunction (\V.:.) with a
right argument of 1, which specifies that the object being defined is an adverb.
It also uses the {\em base characteristics} (\V!b.!) conjunction which
provides various information about its verb left argument.
This new adverb  \V.ranks.
is used to display the standard ranks of \V.<. (used above) and
some other verbs.
\bex
   ranks=. 'x. b. 0' : 1        NB. Define adverb 'ranks'
   < ranks                      NB. Ranks of 'box/lessThan'
_ 0 0
   * ranks                      NB. Ranks of 'sign/times'
_ 0 0
   %. ranks                     NB. Ranks of 'matrixInv/MatDivide'
2 _ 2
   +/ ranks                     NB. Ranks of 'sum'
_ _ _
   +"1 ranks                    NB. Note how scalar value is extended
1 1 1
   +"1 2 ranks                  NB. Note how dual values are extended
2 1 2
\end{verbatim}
\eex
Note that the traditional arithmetic dyads (\V!+ - * % ^!)
act on scalar arguments, but their corresponding monads act on entire arrays.

The following shows the effect of rank on {\em equal} (\verb;=;) and
{\em match} (\verb;-:;):
\bex
   = ranks                      NB. Like traditional arithmetic dyads
_ 0 0
   -: ranks                     NB. Rank _ means whole arrays 
_ _ _
   m                            NB. As above
0 1 2
3 4 5
   m=4
0 0 0
0 1 0
   m = 2 4
0 0 1
0 1 0
   m (="1 1) 3 4 5
0 0 0
1 1 1
   m -: 4
0
   m (-:"0 0) 4                 NB. (-:"0 0) is equivalent to =
0 0 0
0 1 0
   m (-:"0 0) 2 4
0 0 1
0 1 0
   m (-:"1 1) 3 4 5
0 1
\end{verbatim}
\eex

One often has to specify \V."0. or \V."_. in the definition of a verb
which is to be applied to arrays of any rank.

Verb rank is part of the essence of J.
\cite{Iverson94} (p89) explains how
ranks are described at the top of each dictionary definition.
The concept of verb rank is somewhat subtle and 
beginners often find it difficult to grasp.
However it is essential to the full utilisation of the language.

\subsubsection{Bond Conjunction ({\tt \&})}

The bond conjunction can be used to define a {\em monad} in terms of a
{\em dyad} with one argument a constant.
This is done using \V.&. with either argument a verb and the other a noun.
Some examples are
\bex
   log10=. 10 & ^.              NB. Define logarithm to base 10
   log10 100 0.1                NB. Try it
2 _1
   pos=. > & 0                  NB. Define 'pos' which tests whether positive
   pos _2 _1 0 1 2              NB. Try it
0 0 0 1 1
   base8=. 8 & #.               NB. Convert to base 8
   base8 3 5
29
   5 + 8 * 3                    NB. Check
29
   dhm2m=. 1 24 60 & #.         NB. Convert days, hours & minutes to minutes
   dhm2m 2 23 45                NB. Try it with 2 days, 23 hours, 45 minutes
4305
   45 + 60 * 23 + 24 * 2        NB. Check
4305
   quad=. #. & 4 7 _3           NB. Quadratic 4 x^2 + 7x - 3
   quad 2                       NB. Try it with scalar
27
   _3 + 2 * 7 + 2 * 4           NB. Check
27
   ] x=. _3 + i. 7              NB. Define vector
_3 _2 _1 0 1 2 3
   quad x                       NB. Try 'quad' with vector
|length error
|     quad x
   quad ranks                   NB. Check ranks of quad
_ _ _
   quad=. #. & 4 7 _3 "0        NB. Set monadic rank to 0
   x ,: quad x                  NB. Print quadratic table
_3 _2 _1  0 1  2  3
12 _1 _6 _3 8 27 54
\end{verbatim}
\eex
Note how the verb {\em base} (\V!#.!) can be used to define polynomials,
but the monadic rank must be set to 0 in order to process non-scalars.

\subsubsection{Atop Conjunction ({\tt @})}

Both arguments of the {\em atop } conjunction (\V/@/) are verbs.
The resultant verb combines both these by
first applying the right argument, then the left.
Here are some examples
\bex
   ] y=. _2 _1 0 1 2               NB. Define a data vector
_2 _1 0 1 2
   v=. %: @ %                      NB. Define verb 'v' as 'sqrt atop %'
   v y                             NB. Use 'v' monadically
0j0.707107 0j1 _ 1 0.707107
   %: % y                          NB. Same as this
0j0.707107 0j1 _ 1 0.707107
   2 v y                           NB. Use 'v' dyadically
0j1 0j1.41421 _ 1.41421 1
   %: 2 % y                        NB. Same as this
0j1 0j1.41421 _ 1.41421 1
\end{verbatim}
\eex
Thus \V.%:@%. represents the monad $\sqrt{1/y}$ and the dyad $\sqrt{x/y}$.

\subsubsection{Foreign ({\tt !:})}
\label{sec-foreign}

The conjunction {\em foreign} (\V/!:/) provides facilities for housekeeping 
and access to the world outside J, including input/output.

These facilities are often used via automatically-defined
utility-verbs, so that the
beginner (especially with J Release 2 for Windows)
may not need to use {\em foreign} directly.
As described in \cite{Burke94} (chapters 2 and 3),
J Release 2 for Windows provides a {\em Session Manager} which
includes menus to set options, access files, etc.
\cite{Burke94} (p6) explains how to automatically execute the J-script
\verb;profile.js; to define the standard utilities
described in chapters 5 and 6.

The foreign conjunction
takes two integer arguments and in most cases produces a verb.
The remainder of this section is intended merely to introduce the
foreign conjunction and give an idea of the types of facilities it provides.

Detailed documentation for Release 2 
is provided in the Appendix of \cite{Iverson94}.
For J7 it is provided in Appendix E of \cite{Iverson93} and
file \V!xenos.txt!, which is one of the
{\em Distribution Files} included in the ISI diskette (or ftp source tar file).

One can execute system commands from J using the verb
{\em host system command}.
For example, we might want to display a directory listing of all
files with extension \V!.js! i.e. J-scripts.
Under \V!MS-DOS! (but not Windows where one would use a menu item) one could do:
\bex
   2!:0 'dir *.js'
\end{verbatim}
\eex
Under unix one could do:
\bex
   0!:0 'ls -l *.js'
\end{verbatim}
\eex

The fundamental input verb is {\em file read} (\V.1!:1.).
This defines a character vector containing all the characters in the file,
including control characters separating lines.
The corresponding output verb is {\em file write} (\V.1!:2.).
The following example writes a simple character vector (without any
control characters) and then reads it back in:
\bex
   $ msg =. 'Hello world'
11
   filename =. < 'hello.txt'    NB. Boxed filename
   msg 1!:2 filename            NB. File Write
   in =. 1!:1 filename          NB. File Read
   in                           NB. Display 'in'
Hello world
   $ in                         NB. Shape of 'in'
11
\end{verbatim}
\eex

The verb {\em erase} (\V.4!:55.)
undefines an object previously defined using {\em assign} (\V!=.! or \V!=:!).
This frees the associated memory.
Note that the name of the object must be boxed.
For example:
\bex
   x =. 7
   x
7
   4!:55 < 'x'                NB. Erase object from memory (1 indicates success)
1
   x
|value error
\end{verbatim}
\eex

Another useful housekeeping verb is {\em time required} (\V.6!:2.) which
gives the CPU seconds used while executing the sentence argument.
For example the following shows that it took 0.12 CPU seconds to execute
the sentence `\V!i. 10000!':
\bex
   6!:2 'i. 10000'
0.12
\end{verbatim}
\eex

The verb {\em name class} (\V.4!:0.) returns an integer
code indicating the class
(2 = noun, 3 = verb, 4 = adverb, 5 = conjunction)
corresponding to a name.
For example:
\bex
   mod =. |
   4!:0 < 'mod'
3
\end{verbatim}
\eex

The following example uses the verb {\em set prompt} (\V.9!:5.)
to change the prompt string 
to `\V.: .' 
from the default `\V.   .':
\bex
   9!:5 ': '

: 3+4
7
:
\end{verbatim}
\eex

\subsubsection{Derivative ({\tt D.})}

This conjunction provides the $n$th derivative of a verb (function).
J can analytically differentiate many verbs and others are
differentiated numerically.
\cite{Iverson93c} explains how to define partial derivatives,
grad, div, curl, etc. in terms of \V!D.! \ .
The following shows how to obtain the derivatives of $x^3$
\bex
   cube=. ^&3"0         NB. Define scalar (rank 0) cube function
   ] x=. i.5
0 1 2 3 4
   cube x
0 1 8 27 64
   cube D. 1 x          NB. 1st derivative
0 3 12 27 48
   cube D. 2 x          NB. 2nd derivative
0 6 12 18 24
   cube D. 3 x          NB. 3rd derivative
6 6 6 6 6
\end{verbatim}
\eex
The following shows how to
define an adverb \V!D! which provides the scalar first derivative of a
function.
It then uses \V!D! to differentiate the function $x^3$.
\bex
   D=. ("0) (D. 1)      NB. Define derivative adverb
   Dcube=. ^&3 D        NB. Use to define verb Dcube as derivative of cube
   Dcube x              NB. Use Dcube
0 3 12 27 48
\end{verbatim}
\eex
\bsex
   Dcube                NB. Display Dcube using boxed representation
+-------------------+-+-+
|+-------+-+-------+|"|0|
||+-+-+-+|@|+-+-+-+|| | |
|||3|&|*|| ||^|&|2||| | |
||+-+-+-+| |+-+-+-+|| | |
|+-------+-+-------+| | |
+-------------------+-+-+
   5!:5 <'Dcube'        NB. Display Dcube using linear representation
3&*@(^&2)"0
\end{verbatim}
\eex
These two displays of the verb \V.Dcube. each have three parts.
Firstly \V.3&*. represents the verb {\em triple}.
Next \V.^&2. represents the verb {\em square}.
Finally \V."0. sets the rank of the resultant verb to 0 i.e. makes it a
scalar function.
Thus the whole verb means {\em triple the square} i.e. $3x^2$.

\section{Gerunds, Recursion and Iteration}

One of the new features in Release 2 is that explicit definitions can
contain {\em control words} such as \verb;if;, \verb;case; and \verb;while;,
which define {\em control structures}.
Details are provided by
\cite{Iverson94} (pp19, 130--131) and \cite{Burke94} (pp46--49).

These control structures will be familiar to those who have programmed in
other languages and are appropriate in some situations.
However J has alternative facilities which are usually more elegant
and efficient.

{\em Gerunds} are essentially arrays of verbs.
The ability to select a verb (as an array element) provides an alternative
to control structures such as {\em if} and {\em case}.

There are several alternatives to 
looping control structures such as {\em while}.
The powerful array manipulation facilities in J obviate much of the need for
explicit looping.
In some cases recursion (verb calling itself) is a natural way of avoiding
looping in J.
In most other cases iteration (looping) can be
done conveniently using the {\em power} (\V!^:!) conjunction.

\subsection{Gerunds and Agenda}

{\em The Penguin Macquarie Dictionary} defines {\em gerund} as
``a noun formed from a verb as {\em running, writing, loving,} etc.''.
In J a gerund is a noun formed from two or more verbs using the
conjunction {\em tie} (\V.`.).
An important use of gerunds is to provide the functionality of {\em if}
and {\em case} statements by allowing the definition of verbs which
select from other verbs.

Let us define a verb corresponding to the following function
\[ y = \left\{ \begin{array}{ll}
                x^2 & \mbox{if $x>0$} \\
                -x  & \mbox{otherwise}
                \end{array}
        \right. \]
\bex
   g =. - ` *:          NB. Form gerund from 'negate' and 'square'
   type 'g'
noun
   g
\end{verbatim}
\eex
\bsex
+-+--+
|-|*:|
+-+--+
\end{verbatim}
\eex
\bex
   1{g
\end{verbatim}
\eex
\bsex
+--+
|*:|
+--+
\end{verbatim}
\eex
Now we use the
{\em agenda} (\V!@.!) conjunction to define a verb which selects an element
from a gerund.
We use the verb \V.pos. defined above to provide the index of the
element in the gerund from the argument of the required verb.
\bex
   y=. g @. pos " 0     NB. Use agenda to define required scalar verb 'y'
   ] x=. _5 + i. 11     NB. Test with these values
_5 _4 _3 _2 _1 0 1 2 3 4 5
   y x
5 4 3 2 1 0 1 4 9 16 25
   x ,: y x             NB. Use ',:' to combine into matrix
_5 _4 _3 _2 _1 0 1 2 3  4  5
 5  4  3  2  1 0 1 4 9 16 25
\end{verbatim}
\eex

Sometimes we want to use a variable other than an argument to select
an element from a gerund (as an alternative to a {\em case} control structure).
This can be done using {\em evoke gerund (append)} (\verb;`:0;) as shown in the
following:
\bex
   g=. !`|`%            NB. Define gerund from three verbs
   case=. 2             NB. Case 2 is reciprocal
   ((case{g)`:0) 4
0.25
   case=. 0             NB. Case 0 is factorial
   ((case{g)`:0) 4
24
\end{verbatim}
\eex

\subsection{Recursion}

J allows verbs to call themselves.
Such verbs are said to be {\em recursive}.
Recursive algorithms are heavily used in applications such as translators
and combinatorics.

We have already come across examples of explicit
definitions of ambivalent verbs
where the {\em monad} is defined in terms of the {\em dyad} or vice versa.
This is a kind of {\em quasi-recursion}.

It is hard to find simple realistic examples of proper recursion.
An artificial example used in countless textbooks is our old friend
{\em factorial}, which can be defined recursively as follows
\[ f = \left\{ \begin{array}{ll}
                1        & \mbox{if $x=0$} \\
                x f(x-1) & \mbox{otherwise}
                \end{array}
        \right. \]
The following shows how this is done in J:
\bex
   1: _5                           NB. '1:' is verb giving result 1 for any argument
1
   1: 'abc'
1
   f=. 1: ` (* f@<:) @. pos " 0    NB. Define factorial verb 'f'
   x ,: f x                        NB. Test
_5 _4 _3 _2 _1 0 1 2 3  4   5
 1  1  1  1  1 1 1 2 6 24 120
\end{verbatim}
\eex
Note that the parenthesised expression \V.(* f@<:). is a {\em hook} which
multiplies the argument by the result of applying \V.f.
to the decrement (\V.<:.) of the argument.
Remember that \V.f@<:. is evaluated first because \V.@. is a conjunction
and therefore has higher precedence than verbs.
Again we need to specify \V."0. to indicate that the function is scalar.

Another slightly less artificial example is that of {\em Fibonacci Numbers}
1 1 2 3 5 8 13 21 \ldots
where each value is the sum of the two preceding it.
\bex
   fib234=. '+/ fib y. - 2 1' : ''      NB. Verb giving elements 2, 3, 4, ...
   fib=. (1: ` fib234 @. (1&<)) " 0     NB. All cases
   fib 0
1
   fib 1
1
   fib 2
2
   fib 3
3
   fib 4
5
   fib i. 9
1 1 2 3 5 8 13 21 34
\end{verbatim}
\eex
Here the verbs \V.fib234. and \V.fib. are mutually recursive i.e. each
calls the other.

\subsection{Power and Iteration}

\subsubsection{Power Conjunction}

We sometimes want to apply a verb several times.
For example:
\bex
   ]a=. i. 2 3 4        NB. Define 3D array
 0  1  2  3
 4  5  6  7
 8  9 10 11

12 13 14 15
16 17 18 19
20 21 22 23
   sum=. +/             NB. Define sum
   sum a                NB. Apply sum once
12 14 16 18
20 22 24 26
28 30 32 34
   sum sum a            NB. Apply sum twice
60 66 72 78
   sum sum sum a        NB. Apply sum 3 times
276
   sum sum sum sum a    NB. Apply sum 4 times (same result)
276
\end{verbatim}
\eex

In such a situation we can use the {\em power} conjunction (\V.^:.) which
defines a verb which repeatedly applies the verb left argument.
If the right argument is a noun, it defines the number of repetitions
(iterations).
Instead of the above we could do:
\bex
   sum ^: 0 a           NB. Apply sum 0 times - gives 'a' itself
 0  1  2  3
 4  5  6  7
 8  9 10 11

12 13 14 15
16 17 18 19
20 21 22 23
   sum ^: 1 a           NB. Apply sum once
12 14 16 18
20 22 24 26
28 30 32 34
   sum ^: 2 a           NB. Apply sum twice
60 66 72 78
   sum ^: 3 a           NB. Apply sum 3 times
276
   sum ^: 4 a           NB. Apply sum 4 times (same result)
276
   sum ^: _ a           NB. Same result with any larger number (even infinity!)
276
\end{verbatim}
\eex
Since the sum of a scalar is itself,
any further applications keep producing the same value.
And once a value produces itself, there is no need to continue.
Thus an infinite number of iterations (as at the end of the above example)
can be interpreted to mean \\
{\em Continue until two successive values are equal}.

\subsubsection{Obverse Verbs (Inverse Functions)}

The power conjunction can have a negative right argument.
In this case its magnitude specifies the number of applications of
the {\em obverse} verb, which is normally the {\em inverse} function.
Note the connection with the notation $\cos^{-1} x$ for the inverse of
$\cos x$.

Users can use the {\em obverse} (\V!:.!) conjunction to specify an obverse
as part of the definition of a verb.
J is able to determine an analytic inverse for many verbs (but
there seem to be problems with forks, etc.).
Other cases are handled by a numerical approximation.
The following example is based on the function $x^2$ whose
inverse is $\sqrt{x}$.
\bex
   *: ^: _1             NB. Inverse of square (*:) is sqrt (%:)
\end{verbatim}
\eex
\bsex
+--+
|%:|
+--+
\end{verbatim}
\eex
\bex
   (*: ^: _1) 2         NB. Inverse square (i.e. sqrt) of 2
1.41421
   ] n=. _2 + i. 5      NB. n is number of iterations
_2 _1 0 1 2
   n ,: *: ^: n 2       NB. Produce table
     _2      _1 0 1  2
1.18921 1.41421 2 4 16
   2 ^ 0.25 0.5 1 2 4   NB. Check
1.18921 1.41421 2 4 16
\end{verbatim}
\eex

\subsubsection{Solution of Non-linear Equations}

An important application of iteration is the solution of non-linear equations.
One of the simplest techniques is to rewrite the equation in the form
$ x = F(x) $
We choose some initial approximation $x_0$ and then calculate a better
estimate using
$ x_1 = F(x_0) $.
The process is repeated until a sufficiently accurate result is obtained.
The following example can be found in both \cite{Iverson93} (section 24) 
and \cite{Iverson94} (p12).
The equation to be solved is
$ x - \cos x = 0 $
which can be rewritten as
$ x = \cos x $
\bex
   x=. x0=. 1           NB. Initial estimate is 1
   ] x=. cos x          NB. Improve estimate
0.540302
   ] x=. cos x          NB. Improve estimate
0.857553
   ] x=. cos ^: _ x     NB. Continue until convergence
0.739085
   cos x                NB. Check result
0.739085
\end{verbatim}
\eex
This technique has severe limitations.
It is not always possible to rewrite equations in the required form.
Its rate of convergence is usually poor and it often fails to converge at all.

The Newton-Raphson Method is much faster and more reliable.
It uses the iterative formula
\[ x_n = x_{n-1} - \frac{f(x_{n-1})}{f'(x_{n-1})} \]
Let us use this method to solve the same equation solved above.
We have
\[ f(x) = x - \cos x \]
\[ f'(x) = 1 + \sin x \]
\bex
   f=. 'y. - cos y.' : ''               NB. Define f
   Df=. '1 + sin y.' : ''               NB. and its derivative
   nrf=. 'y. - (f y.) % Df y.' : ''     NB. Newton-Raphson formula
   nrf ^: _ x0                          NB. Apply this until it converges
0.739085
\end{verbatim}
\eex
This can be simplified using tacit definitions as follows
\bex
   f=. - cos                    NB. Define 'f' using hook
   Df=. >: @ sin                NB. Define 'Df'
   nrf=. - (f % Df)             NB. Newton-Raphson formula using hook & fork
   limit=. ^: _                 NB. Define adverb 'limit'
   nrf limit x0                 NB. Apply 'nrf' until it converges
0.739085
\end{verbatim}
\eex
But we have already seen that the conjunction \V!D.! can be used to
differentiate functions automatically.
Let us incorporate this facility into a generic Newton-Raphson adverb \V!nr!.
\bex
   D=. ("0) (D. 1)              NB. Define derivative adverb 'D' (as above)
   nr=. '-(x.%x.D)' : 1 limit   NB. Define adverb 'nr'
   fnr=. f nr                   NB. Apply this to f to define verb 'fnr'
   fnr x0                       NB. Apply 'fnr' to initial estimate
0.739085
   (-cos) nr x0                 NB. Repeat using hook to define function
0.739085
\end{verbatim}
\eex

\subsubsection{Iteration with Non-scalars}

So far we have only considered iterative processes involving scalar
nouns and verbs.
Some problems require the transmission of several values from one iteration to
the next.
This can always be done using arrays, boxed if necessary.
The following example again uses {\em Fibonacci Numbers}, but
this time instead of using recursion to generate scalars,
we use iteration to generate vectors.
\bex
   tail2=. _2&{.                NB. Define verb 'tail2' giving final 2 elements
   next=. +/ @ tail2            NB. Define verb 'next' giving sum of final 2 elements
   Fib=. , next                 NB. Define verb 'Fib' using hook to append next
   fib01=. 1 1                  NB. Initial sequence
   Fib ^: 9 fib01               NB. 9 iterations of 'Fib'
1 1 2 3 5 8 13 21 34 55 89
\end{verbatim}
\eex

\subsubsection{Alternative to While Loop}

But what if we want to stop when say an element exceeds 1000?
The power conjunction with a {\em verb} right argument provides an
alternative to a {\em while} loop.
The number of iterations comes from applying this verb to the right
hand argument of the resultant verb.
The following shows how this can be used to stop the generation of Fibonacci
numbers once 1000 is exceeded.
\bex
   while=. 1000&> @ {:          NB. Define verb 'while' so 1=continue, 0=stop
   Fib ^: while limit fib01
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
\end{verbatim}
\eex
The adverb 'limit' is defined as \V.^:_1. so we have two levels of iteration.
The inner level is controlled by the verb \V.while. which normally gives the
value 1, which means {\em Do a single iteration}.
At the end \V.while.
gives the value 0 which means that the argument is simply copied to
the result, giving two successive identical values.
This causes the outer iteration to terminate.

\nocite{Iverson92}

% \bibliography{hld}
% \bibliographystyle{ams}

\begin{thebibliography}{}

\bibitem[\protect\BCAY{}{Burke}{1994}]{Burke94}
Burke,~C., 1994: {\em J User Manual}.
\newblock Iverson Software Inc., Toronto.

\bibitem[\protect\BCAY{}{Hui}{1992}]{Hui92}
Hui,~R.~K., 1992: {\em {An Implementation of J}}.
\newblock Iverson Software Inc., Toronto.

\bibitem[\protect\BCAY{}{Iverson}{1993a}]{Iverson93c}
Iverson,~K.~E., 1993a: {\em Calculus}.
\newblock Iverson Software Inc., Toronto.

\bibitem[\protect\BCAY{}{Iverson}{1993b}]{Iverson93}
Iverson,~K.~E., 1993b: {\em J Introduction \& Dictionary}.
\newblock Iverson Software Inc., Toronto.

\bibitem[\protect\BCAY{}{Iverson}{1994}]{Iverson94}
Iverson,~K.~E., 1994: {\em J Introduction and Dictionary}.
\newblock Iverson Software Inc., Toronto.

\bibitem[\protect\BCAY{}{Smillie}{1993}]{Smillie}
Smillie,~K.
\newblock {\em Some Notes on Introducing J with Statistical Examples}.
\newblock Dept. Computing Science, University of Alberta, Edmonton, Alberta T6G
  2H1, Canada, June 1993.

\end{thebibliography}

\end{document}
