help=
  ( streep,verwerk,lusmenu,whatIsBracmat,filosofie,colofon
  . syntax,atotxt,evaltxt,gettxt,contxt,binovztxt,patternm
  . savtxt,dumtxt,binprotxt,prostutxt1,prostutxt2,funmactxt
  . unops,naamloos,algtxt,unpattxt,binmenu,pattxttxt,maptxt
  . pattxt,asstxt,unopsmenu,unstuurtxt,varsmenu,funcmenu,vaptxt
  . varmattxt,varprotxt,progsmenu,debugtxt,debugtxt2,debugtxt3
  . inbltmenu,alctxt,aligntxt,asctxt,utftxt,chrtxt,charsettxt
  . chutxt,dbgtxt,dentxt,escappattxt,lambda,morexmlps,jsntxt
  . divtxt,fretxt,funtxt1,funtxt3,beztxt,moptxt,lettxt,ugctxt
  . lsttxt1,difftxt,pattxt2,methodtxt,predvartxt,calctxt
  . lsttxt2,lsttxt3,memtxt,modtxt,peetxt,poktxt,Bracmat-name
  . puttxt1,puttxt2,puttxt3,rentxt,revtxt,seltxt,simtxt,strtxt
  . switxt,systxt,tbltxt,filtxt,flgtxt,glftxt,predefmenu,flttxt
  . sgntxt,cattxt,gontxt,factxt,subtxt1,show,rmvtxt,macrotxt
  . outtxt,taytxt,newtxt,newobjecttxt,humtxt,objecttxt,hashtxt
  . paragraphs,fname,findtxt,inserttxt,removetxt,Dietxt
  . ISOtxt,casesensitivetxt,foralltxt,doHTML,clktxt,limitations
  . lowtxt,upptxt,whltxt,argtxt,d2xtxt,x2dtxt,toMLtxt,errtxt
  . rewriting,jsntranstxt,transformtxt,MLencodingtxt,nestMLtxt
  . gentlepat recurpat closetxt filesettxt interaction usecases
  . fixdtxt modetxt positiontxt readtxt varitxt writetxt nonlinpat
  . CalcFunctxt,Calculatetxt,CalcTrctxt,CalcPrinttxt,CalcExporttxt
  . CalcParmtxt,CalcVartxt,CalcArraytxt,CaltItertxt,CalcMethodtxt
  . CalcConsttxt,tmetxt
  )
.   ( lusmenu
    =   M
      , "                       BRACMAT                       "
      , "0  introduction
1  pattern matching
2  grammar
3  binary operators
4  prefixes/unary operators
5  strings or atoms
6  symbols
7  the four evaluation contexts
8  programming in Bracmat
9  functions
10 data structures
11 objects
12 hash tables
13 floating point calculations
14 character set
15 predefined variables
html      transform this file to HTML
htmltable transform this file to HTML, put excercises in tables, not blockquotes
latex     transform existing HTML version to LaTeX format
htmllatex transform this file to HTML and then to LaTeX format
save      reformat and save this file as help.bra
lex       lexical analysis of help file"
      ,   (0,intro)
          (1,patternm)
          (2,syntax)
          (3,binmenu)
          (4,unopsmenu)
          (5,atotxt)
          (6,varsmenu)
          (7,evaltxt)
          (8,progsmenu)
          (9,funcmenu)
          (10,contxt jsntranstxt)
          (11,objecttxt methodtxt)
          (12,hashtxt)
          (13,calctxt)
          (14,charsettxt)
          (15,predvartxt)
          (html,)
          (htmltable,)
          (latex,)
          (htmllatex,)
          (lex,)
          (save,)
    )
  & ( funcmenu
    =   M
      , Functions
      , "1  function evaluation
2  defining functions
3  nameless functions
4  lambda abstractions
5  currying
6  built-in functions
7  predefined, changeable functions"
      ,   (1,funmactxt naamloos macrotxt transformtxt)
          (2,funtxt1 funtxt3)
          (3,naamloos macrotxt transformtxt escappattxt)
          (4,lambda)
          (5,lambda)
          (6,inbltmenu)
          (7,predefmenu)
    )
  & ( binmenu
    =   M
      , "Binary operators"
      , "0  binary operators - overview
1  algebraic operations
2  program flow
3  pattern matching
4  data structures
5  assignment
6  differentiation
7  functions and macros
8  the dummy operator"
      ,   (0,binovztxt)
          (1,algtxt)
          (2,binprotxt prostutxt2)
          (3,pattxt pattxttxt pattxt2 escappattxt)
          (4,contxt)
          (5,savtxt asstxt)
          (6,difftxt)
          (7,funmactxt naamloos macrotxt transformtxt)
          (8,dumtxt funtxt3)
    )
  & ( unopsmenu
    =   M
      , Prefixes
      , "1  program flow
2  pattern matching
3  prefixes combined with expressions
4  unary operators"
      , (1,unstuurtxt) (2,unpattxt) (3,unpattxt) (4,unops)
    )
  & ( varsmenu
    = M,Symbols,"1  literals
2  variables",(1,varmattxt) (2,varprotxt)
    )
  & ( progsmenu
    =   M
      , "Programming advice"
      , "1  program flow
2  pattern matching
3  data structures
4  debugging"
      ,   (1,prostutxt1 prostutxt2)
          (2,pattxt unpattxt escappattxt)
          (3,contxt objecttxt)
          (4,debugtxt debugtxt2 debugtxt3)
    )
  & ( inbltmenu
    =   M
      , "Built-in functions"
      , "1 <N>
    access array element: !(12$a):?(11$a)
2 |_alc_|
    allocate memory (low level): alc$100
3 |_arg_|
    return program (command line) argument:
    (arg$0:?programName) ((arg$:?o1)&(arg$:?o2))
4 |_asc_|
    convert character to internal representation: asc$y:121
5 |_bez_|
    show number of allocations and max. number of allocations
6 |_chr_|
    convert internal representation to character: chr$121:y
7 |_chu_|
    convert Unicode codepoint to UTF-8 character: chu$2000
8 |_clk_|
    CPU seconds since start of session: clk$:?t0
9 |_d2x_|
    convert decimal number to hexadecimal number: d2x$73083734:45B2B56
10 |_dbg_|
    debugging aid: |_dbg'(a b c:? b ?)_|
11 |_den_|
    denominator: den$22/7:7
12 |_div_|
    quotient: div$(22.7):1
13 |_err_|
    redirect or silence error messages
14 |_fil_|
     file I/O (low-level)
15 |_flg_|
    splits expression in prefixes and expression without prefixes
16 |_glf_|
    opposite of flg: combines prefixes and expression
17 |_fre_|
    return allocated memory (low level)
18 |_get_|
    get input (from file,keyboard or memory)
19 |_low_|
    convert to lower case
20 |_lst_|
    list un-evaluated expression(s) or value(s) of variable(s)
21 |_map_|
    apply function to each member of a list
22 |_mem_|
    list existing variable names
23 |_mod_|
    remainder
24 |_mop_|
    map expression to space separated list (option: another separator operator)
25 |_new_|
    create new object as a copy of another object
26 |_pee_|
    get value from address (peek) (low level)
27 |_pok_|
    put value at address (poke) (low level)
28 |_put_|
    write output
29 |_ren_|
    rename file or directory or move file
30 |_rev_|
    string reverse
31 |_rmv_|
    remove file
32 |_sim_|
    similarity between two atoms
33 |_str_|
    stringize expression into atom
34 |_swi_|
    software interrupt (low level)
35 |_sys_|
    command line shell
36 |_tbl_|
    create array, remove array/variable
37 |_tme_|
    return current time
38 |_ugc_|
    determine the Unicode General Category of a character
39 |_upp_|
    convert to upper case
40 |_utf_|
    convert UTF-8 character to Unicode codepoint
41 |_vap_|
    deconstruct a string character-wise or according to specified separator
42 |_whl_|
   while loop
43 |_x2d_|
    convert hexadecimal number to decimal number x2d$BABEFACE:3133078222
"
      ,   (1,seltxt)
          (2,alctxt)
          (3,argtxt)
          (4,asctxt)
          (5,beztxt)
          (6,chrtxt)
          (7,chutxt)
          (8,clktxt)
          (9,d2xtxt)
          (10,dbgtxt)
          (11,dentxt)
          (12,divtxt)
          (13,errtxt)
          (14,filtxt)
          (15,flgtxt)
          (16,glftxt)
          (17,fretxt)
          (18,gettxt)
          (19,lowtxt)
          (20,lsttxt1 humtxt lsttxt2 lsttxt3 newtxt)
          (21,maptxt)
          (22,memtxt)
          (23,modtxt)
          (24,moptxt)
          (25,newobjecttxt)
          (26,peetxt)
          (27,poktxt)
          (28,puttxt1 humtxt puttxt2 puttxt3 newtxt)
          (29,rentxt)
          (30,rmvtxt)
          (31,revtxt)
          (32,simtxt)
          (33,strtxt)
          (34,switxt)
          (35,systxt)
          (36,tbltxt)
          (37,tmetxt)
          (38,ugctxt)
          (39,upptxt)
          (40,utftxt)
          (41,vaptxt)
          (42,whltxt)
          (43,x2dtxt)
    )
  & ( intro
    =   M
      , Introduction
      , "
Bracmat makes it a joy to find your way in oddly shaped data and manipulate it
at your will. Bracmat occupies a niche where you find few, if any, other
computer programming languages.

This chapter may give you an impression of what Bracmat can do for you.

0 What is Bracmat?
1 Why use Bracmat?
2 How does Bracmat work?
3 What are Bracmat's limitations?
4 How did Bracmat evolve?
5 Why the name `Bracmat'?
6 How to obtain Bracmat
7 Where to find example code on the internet"
      ,   (0,whatIsBracmat)
          (1,usecases)
          (2,interaction)
          (3,limitations)
          (4,filosofie)
          (5,Bracmat-name)
          (6,colofon)
          (7,morexmlps)
    )
  & ( whatIsBracmat
    =   T
      , "What is Bracmat?"
      , "Bracmat is a computer programming language designed for the analysis and
manipulation of complex data, including the evaluation of algebraic
expressions, parsing natural language, validation of HTML, and the
automatic chaining of multifaceted web services into a workflow. In
several projects, Bracmat has been combined with other programming
languages to take care of high level activities that otherwise would
be time-consuming to implement.

Bracmat was originally developed as a calculator for symbolic
algebra. Like a table calculator, Bracmat ran a Read-Eval-Print-Loop
(REPL). It added, multiplied, took powers and logarithms, and
differentiated algebraic expressions.

Later additions transformed the calculator into a programming
language. The subject matter, algebraic expressions, had often to be
dismantled and recombined differently, e.g., to find terms
with like factors and recombining these into a group of new terms with
a common factor. What was needed was advanced pattern matching with a
notation that requires little more than your intuition to understand,
because the algebraic transformations to be implemented were already
hard enough to grasp. Envisioning that pattern matching would also be
useful in natural language related problems, the subject domain
was extended to cover almost any kind of data.

True to its roots, Bracmat has still an important feature in common
with calculators: as long as the input data are simple enough, the
user does (and can) not specify how these data have to be
processed. Calculators handle basic calculations in a predictable,
unchangeable way, e.g. 4+7 will always result in |_11_|,
and not in, say, |_10_| or |_23-12_|. That is because the
manufacturer had good reasons to think that |_11_| is what the user
expects and nothing else.

In the same way, Bracmat handles basic calculations with a much
wider variety of data: rational numbers, symbols, words, and
collections thereof. For example, a+b+a becomes 2*a+b
and not, say, |_x.a_| or |_b+2*a_|. Again, Bracmat takes
decisions that you can't easily circumvent. However, the more complex
the data are, the better are the chances that not all results,
although defensible, have an appearance that suits you. It is here
that programming comes in: Bracmat leaves certain kinds of data
unchanged, but opens the possibility to dissect data, to perform
calculations on the parts, and to assemble an answer from the
resulting subanswers.

Bracmat makes no distinction between data and instructions. There
are only expressions. Some expressions stay the same upon evaluation,
other expressions change radically, and then there are expressions
that contain some parts that are stable upon evaluation and other
parts that change. The advantage of having the same syntax for data
and instructions is not that you could deconstruct
and recombine program code (generally not a good idea), but that you
can embed code in a data structure that adds more data upon
evaluation. Such code can function as growing tips in list or tree
structures, as variable fields in a standard letter, or as places of
particular interest inside a pattern, to name some examples.

Another advantage of not having to distinguish between code and data
is that reading a program and reading data from a file are no
different. And saving a program is the same as saving data to a
file. Which brings us to yet another enormous advantage: a Bracmat
expression is virtually undecipherable if it doesn't obey the
canonical layout rules, which are ... canonical. Whereas layout
doesn't matter to Bracmat, it does to you, and therefore Bracmat, when
asked to save an expression to file, imposes the canonical layout
rules on the output, unless you insist on wanting to have it all in
one line, no superfluous spaces allowed.

Bracmat expressions have a simple syntax: a mix of parentheses, binary
operators, and operands along with prefixes preceding those operands
or parentheses. When programmability was added to Bracmat, no new syntax was invented. To the
operators for addition, multiplication, etc. were added only a few prefixes and binary
operators dedicated to assignment, function calling, pattern matching and program flow."
    )
  & ( limitations
    =   T
      , Limitations
      ,   "Oddly enough, Bracmat has no operators for subtraction and division. The reason
is that these operations lack a very desirable property: associativity.
Addition and multiplication are associative, because

    a+(b+c)

is equivalent to

    (a+b)+c

and can be written as

    a+b+c

On the other hand, subtraction and division are not associative, as can be seen
in this example

    a-(b-c)

which is not equivalent to

    (a-b)-c

because

    a-(b-c) = a-b+c

while

    (a-b)-c = a-b-c

So we see that an expression with binary minus operations and written without
parentheses is a left descending tree: the topmost binary operator is the
operator to the far right. And indeed, the first incarnation of Bracmat
internally represented sums and products as left descending trees. However,
we are used to seeing numerical factors to the left of non-numerical symbols.
If sums and products are left-descending, adding 3*a*b*c+4*a*b*c becomes
unnecessary expensive

    3*a*b*c+4*a*b*c = ((3*a)*b)*c+((4*a)*b)*c

The first expensive step is finding the numerical factors |_3_| and |_4_|,
because they are several levels deep. The second expensive step is that
in the result

    ((7*a)*b)*c

all multiplication operators necessarily have to be new nodes, so to do this
simple addition, 4 new nodes (one for the |_7_| and three for the
multiplication operators) had to be created. Compare this with a right
descending tree as the default internal representation for sums and products:

    3*a*b*c+4*a*b*c = 3*(a*(b*c))+4*(a*(b*c))

The numerical factors are very close to the root of the tree and therefore
easy to find. Moreover, for the result

    7*(a*(b*c))

Bracmat only needs to create one node for the numerical factor |_7_| and
one node for a single multiplication operator, because the subexpression

    (a*(b*c))

can be shared with the original expression.

Fortunately, subtraction and division are unnecessary operations if you have
negative numbers and the operations of multiplication and exponentiation,
because

    a - b

can be written as

    a + -1 * b

and

    a / b

can be written as

    a * b ^ -1

A completely unrelated limitation is that in Bracmat, calculations always have
to be exact. Number expressions for which no rational representation exists
are not further evaluated. Bracmat knows how to handle the special symbols
|_i_|, |_e_| and |_pi_|, but it offers no numerical representation for |_e_|
and |_pi_|. Examples:

{?} a+b+-1*a                 { this is how you subtract in Bracmat }
{!} b

{?} 1+(1+i)*(1+-1*i)+-1     { the leading and trailing terms force
                               Bracmat to expand the product }
{!} 2

{?} 12345/54321 ^ 1/2        { the square root of 12345/54321 }
{!} 5^1/2*19^-1/2*823^1/2*953^-1/2

{?} x^(a+x\\L2*100)
{!} 1267650600228229401496703205376*x^a

{?} 5/2 \\L 987654
{!} 15+5/2\\L32363446272/30517578125

{?} y\\D(x\\D((x+y)^-2))
{!} 6*(x+y)^-4"
          "Whereas Bracmat can do floating point arithmetic, it is more at home with 
bignum arithmetic, performimg arithmetic operations with integer and rational
numbers. Bracmat happily adds and multiplies numbers with thousands of digits.
Only available computer memory and address size impose a limit to the size of
numerical operands, but before you decide to multiply two ten-million digit
numbers you should realize that Bracmat is not time optimised for number
crunching on that scale.

Bracmat handles non-integer powers of positive rational numbers (square root,
for example) provided that the number (if it is an integer) or the numerator
and the denominator (if the number is a fraction) are less than 2^32 (or 2^64,
if Bracmat is compiled for a 64-bit platform).

A predefined function, flt$, represents rational numbers in a
scientific floating point notation.

Bracmat has a module for floating point arithmetic. When you write an algorithm
to be executed by this module - an UFP object - you write code that looks like
all other Bracmat code. Below the surface, however, the code is treated very
differently: it is compiled to efficient byte code before being executed. Many
things that you can do outside the UFP module, such as pattern matching,
symbolic computations, recursion and string operations are not available in the
floating point module, but because the surface language is the same,
communication between the two worlds is easy and elegant."
    )
  & ( usecases
    =   T
      , "Why use Bracmat?"
      , "Bracmat is not a general purpose programming language, but a programming
language that was conceived in the 1980s with a single aim: to make tedious
algebraic manipulations easy and, most importantly, not prone to human errors.
Now hang on.

Many problems can be solved by following steps similar to those taken when solving
an algebraic problem:

* Find stuff
* Find the context of stuff
* Sort stuff
* Merge stuff
* Combine stuff
* Replace stuff
* Cope with labyrinthine problems with many cul-de-sacs"
    )
  & ( interaction
    =   T
      , "User Interaction with Bracmat"
      ,   "Bracmat offers a simple environment for input of both data and code. After the
prompt {?} you can write your input. When you hit the <return> key, Bracmat
evaluates your input and writes the result to the screen following a {!}
sequence (unless there was no visible result). Under the result follows a line
that tells whether the evaluation was successful (S) or not (F) (in rare cases
you may see an |_I_|, which, for the time being, you may interpret as failure).
In the same line the machine shows how much processor time it needed.
Intermediary results may also appear on the screen.

When instructions are entered from the keyboard, the program waits until all
the conditions below are fulfilled:

* <return> (or <enter>) is the last key that has been pressed
* every opening parenthesis has a closing counterpart
* every opening brace (start of comment) has a closing counterpart
* every string has either two enclosing double quotes, or none.

You can freely have parentheses and double quotes in a comment, and you can
freely have parentheses and braces in a string, provided the string is enclosed
in double quotes.

You can write a multiple-line instruction by putting the instruction inside
an extra pair of parentheses. After each non-terminating <return>, Bracmat
shows in the next line how many closing parentheses are needed for the
completion of the instruction. If you are in the middle of a string or a
comment when pressing <return>, the next line starts with {str} or {com},
respectively.

If you want to enter several instructions on the same line, you should write
a semicolon ; between the instructions. These instructions are executed
in the same order. If you do not want to see the result of a calculation, you
may write a semicolon after the last instruction. Instructions in a text file
must be separated by semicolons.

You may freely surround binary operators with whitespace characters (e.g.,
space, tab, line feed). Take care not to put spaces between the characters
that make up a fraction or negative number, |_- 1234 / 5678_| is different
from |_-1234/5678_|."
          "Bracmat can open and read a text file and execute the instructions as they are
read. After the last instruction has been executed, the file is closed. For
example, the program that produces the text you are reading just now, is read
from a file named |_help_| and immediately executed.

The instruction for reading a file |_myprog_| and executing its instructions
is |_get$myprog_|. The $ is a binary operator that initiates
function evaluation. |_get_| is the function name of one of the few built-in
functions.

The result of the last executed instruction in a file is written to the screen.
For better control over screen output one may use the built-in function |_put_|,
which writes from the current cursor position to the right, or the predefined
(but changeable) function |_out_|, which writes an extra line feed after its
argument has been written to the screen.

{?} put$(x*x);put$(y+y)
x^22*y{!} 2*y"
          "Often you will need the result of the last evaluated instruction in the next
instruction. You can use the exclamation mark ! instead of re-entering the
result. Example:
{?} 1+1
{!} 2
{?} !^!^!^!
{!} 65536"
          "When you write programs in the Bracmat language you will normally use an
external text editor. You can enter small programs directly at the Bracmat
prompt {?}, but a small change in an instruction can only be done by re-
entering the entire instruction. You may save instructions that are still
held in memory, by the built-in |_lst_| function. This function takes several
optional parameters that tell the system whether the instruction has to be
written in a compact and barely readable form, or in a more pretty form, with
lots of indentations. Comments are never written, as they are ignored at input
time. As an example, you can write the definition of the predefined
factorisation function |_fct_| to a file |_factorise_| by entering the following
instruction:

{?} lst$(fct,factorise,NEW) {NEW: replace old file with same name}
{!} fct"
          "At first sight, a Bracmat program doesn't look like programs written in other
languages. This may even become a permanent impression. So here are some
recommendations about programming habits:
* Experiment with the examples in this document.
* Use a modular and incremental style of programming: test every function
  before going on to the next one.
* Keep functions small, to begin with. Error messages point to functions, not
  to line numbers.
* Use meaningful names. There is no limit to their length, and you may use the
  minus-sign as separator in multiple-word-names.
* Let Bracmat indent your code: regularly save your code, read it in Bracmat,
  save it from Bracmat using the |_lst_| function to the file you are editing
  and reread the file in your editor.
* Try to avoid the `not' prefix |_~_| and the use of arrays."
    )
  & ( patternm
    =   M
      , "Pattern matching"
      , "The single most outstanding feature of Bracmat is how it can recognise patterns
in data. The data can be an algebraic expression, a directory listing in table
form, a thesaurus structured like a tree, a text or whatever data that can be
expressed as a string of characters or as a tree of such strings. Bracmat's
patterns are much more advanced than regular expressions. Regular expressions
are fixed patterns once the matching operation is started. Bracmat implements
not only propositional rules comparable to regular expressions, but also first
order predicate rules, backtracking to search the space of combinations of data
that make its predicates come true. In this way it is easy to implement a
relational database. But it doesn't stop here, because Bracmat supports
recursive invocations of pattern matching and other operations.

1 Gentle introduction
2 Rewriting data using pattern matching
3 Non-linear patterns
4 Recursive patterns
5 Pattern matching in character strings
6 Pattern matching in tree structures"
      ,   (1,gentlepat)
          (2,rewriting)
          (3,nonlinpat)
          (4,recurpat)
          (5,pattxttxt pattxt2)
          (6,pattxt escappattxt)
    )
  & ( gentlepat
    =   T
      , "Gentle introduction to pattern matching"
      , "The following is an expression that tests whether a specific detail is present
in a list of nodes, a sum in this case:

{?} 20+a+b+c:?+b+?  { Is there a term \"b\" in the sum \"(20+a+b+c)\" ?}
{!} 20+a+b+c
    S   0,00 sec

This is what happened. The left-hand side of the match operator |_:_| is the subject,
and the right-hand side of the match operator is the pattern.
If the match operation is to succeed, the pattern must be like the
subject. This is the case here, because the question marks behave like
a wild card (like the Joker in some card plays) and the |_b_| is similar to
itself. By the way, when a pattern match operation succeeds, the resulting
expression is the subject. The second example shows a pattern match operation
that fails:

{?} 20+a+b+c:?+q+?  { Is there a term \"q\" in the sum \"(20+a+b+c)\" ?}
    F

The |_q_| in the pattern is not like anything in the subject 20+a+b+c
and thus the pattern match operation must fail.

The following examples are the same as the introductory example, merely
replacing the |_+_| operator by the |_*_| and the whitespace operators:

{?} 20*a*b*c:?*b*?  { Is there a factor \"b\" in the product \"(20*a*b*c)\" ?}
{!} 20*a*b*c
    S   0,00 sec

{?} 20 a b c:? b ?  { Is there a word \"b\" in the sentence \"(20 a b c)\" ?}
{!} 20 a b c
    S   0,00 sec

In the following example, the pattern applies to the characters in the string,
rather than to nodes in a list of terms, factors or words. The |_@_| that is
prefixed to the match expression indicates to the match operator that this is
not the normal match operation, but a string match operation.

{?} @(20abc:? b ?)  { Is there a character \"b\" in the string \"20abc\" ?}
{!} 20abc
    S   0,00 sec

The patterns in string match operations are like patterns in normal match
operations that have sentences (words separated by whitespace operators) as the
subject."
    )
  & ( rewriting
    =   T
      , "Rewriting data using pattern matching"
      , "
An important application of pattern matching is rewriting data by using
several rules. Each rule consists of a pattern and a replacement expression.
Often, the pattern explicitly specifies only parts of the subject, so that the
same rule will fire for a broad class of subjects, all having the specified
parts of the rule in common. The remaining, unspecified, parts normally have
to reappear unscathed in the output of the transformation rule. To catch these
parts, patterns can contain several variables that bind to the parts of
the rule that are not completely fixed.

Suppose we have the sentence |_My name is Ivan the terrible_| and we want to
change |_Ivan_| to |_Wanja_|.
The following instructions can do that:

{?} My name is Ivan the terrible:?begin Ivan ?end
{!} My name is Ivan the terrible
{?} !begin Wanja !end
{!} My name is Wanja the terrible

A question mark indicates that the symbol that it precedes is a variable that
accepts (part of) the subject as value. An exclamation mark indicates that the
following symbol is supposed to be a variable and that the value of that
variable must replace the variable.

The pattern |_?begin Ivan ?end_| and the replacement |_!begin Wanja !end_|
are not sensitive to what the rest of the sentence looks like, so we can
use the same pattern and replacement expression to transform another sentence:

{?} Ivan goes to school:?begin Ivan ?end
{!} Ivan goes to school
{?} !begin Wanja !end
{!} Wanja goes to school

To make a rewrite rule out of these two components, we can put them in a
function that we can feed any sentence and that returns a transformed sentence,
if the pattern matched the input. Further, if the pattern doesn't match, as in the
function below, it simply returns the input.

{?} ( ivanRule
    =   begin end
      .     !arg:?begin Ivan ?end
          & !begin Wanja !end
        | !arg
    )
{!} ivanRule
{?} ivanRule$(She bought a bicycle for Ivan)
{!} She bought a bicycle for Wanja
"
    )
  & ( nonlinpat
    =   T
      , "Non-linear patterns"
      , "Bracmat patterns not only can contain receiving variables (those that are
preceded by a question mark), but also giving variables (those that are
preceded by an exclamation mark). The same variable symbol can even occur
in both roles: as receiving and as giving, in any order. If an occurrence of a
variable is receiving and a later in the pattern giving, than the pattern is
said to be non-linear. Such patterns can for example be used to find things
that occur more than once in the subject. For example, find two inventions of the
same age in a list of name/year pairs:

{?} (   (teabag.1903) (sonar.1906) (computer.1941)
        (triode.1906) (zeppelin.1900) (\"coffee filter\".1782)
      : ? (?invention1.?year) ? (?invention2.!year) ?
    & !invention1 !invention2
    )
{!} sonar triode
"
    )
  & ( recurpat
    =   T
      , "Pattern matching with recursive patterns"
      , "Many life problems can be solved by first solving a less complex problem.
If needed, this process can be done again and again, until we end with a
problem that we know how to solve. In such cases, Bracmat's ability to handle
recursive patterns can be of much help.

Here is a rather academic example that defines a grammar with recursive
patterns and that checks whether an input is valid, according to this grammar.

{?} S=(|0 !S|1 !T);T=(0 !T|1 !S); { Regular grammar }
{?} 0 1 0 1 0:!S { Check whether subject contains an even number of 1's. }
{!} 0 1 0 1 0

{?} P=(|0 ?x 1 & !x:!P); { context free grammar }
{?} 0 0 0 1 1 1:!P { Check whether subject consist of a row of 0's
                     followed by a row of 1's of the same length. }
{!} 0 0 0 1 1 1

The following example could be the basis for a journey planner. We use a
recursive pattern to find out whether two continents are connected over land.

{?} connected=((\"South America\".\"North America\") (Africa.Asia)
               (Asia.Europe));
{?} (reachable = a b f
    .     !arg:(?a.?b.?f)
        & !f:? ((!a.!b)|(!b.!a)) ?
      |   !f:?A ((!a.?c)|(?c.!a)) ?Z
        & reachable$(!c.!b.!A !Z)
    ); {Remove used fact from fact base.}
{?} (   Antarctic Europe Australia Africa Asia \"North America\"
        \"South America\"
    :   ?
        %@?x  {Pick a continent.}
        ?
        ( %@?y {Pick another continent}
        & reachable$(!x.!y.!connected) {Are they reachable?}
        & out$(!x \"is reachable from\" !y)
        & ~  {Force backtracking to collect all answers.}
        )
        ?
    );    { pattern using second order logic }

    Europe is reachable from Africa
    Europe is reachable from Asia
    Africa is reachable from Asia
    North America is reachable from South America"
    )
  & ( filosofie
    =   T
      , "How Bracmat evolved"
      ,   "Bracmat originated from a Basic program that was meant (and able) to do some
algebraic calculations in General Relativity. This program could do the
mathematical operations that Bracmat can: add, multiply, take powers and
logarithms and differentiate. This calculator was not programmable, all
program flow had to be done in Basic. It became clear that the program could
only solve the simplest algebraic problems. The reason for this was its
inability to recognise complex patterns in the subject expressions. All
pattern recognition had to be done in Basic and this was a fault prone
business. It would be nice to have an interpreter at hand that could interpret
human-readable production rules. That is exactly what Bracmat embodies.
This program is written in ANSI-C and developed on the fastest home computer
that existed at that time (Acorn Archimedes). Although Bracmat is much faster
than its predecessor, its main virtue lies in its programmability and the
advanced pattern matching. The speed at which it processed formulae was not
impressive, so Bracmat always needed a fast machine. Fortunately computers
have become faster and faster, and nowadays Bracmat performs at a speed
that is acceptable, even in real time systems with users expecting
immediate responses."
          "Compared with other algebra systems, Bracmat has few built-in functions and
even its set of mathematical operators is small. There are no operators for
subtraction and division, for example. Nevertheless, Bracmat is general and
flexible enough to even solve problems elegantly outside the field of computer algebra.
This flexibility on the programming level is traded off against
the inability to change the behaviour of the interpreter itself.
There are no switches (toggles) that could influence, for example, the order of
terms within a polynomial, or whether complex products are expanded, or
the way backtracking is done. This choice was, of course, easier to implement,
but it also has benefits for the user: the working of Bracmat programs is not
obscured by deep side effects of switch settings. Bracmat's only side effects
are expression binding and change of focus in a multiple valued
variable (array indexing, stacking). A later addition is support of objects,
i.e. data structures that allow for partial updates. This introduced another
kind of side effect."
          "One peculiar thing about the original, object-less Bracmat is
the way it manages data:
1)  Processes are not periodically interrupted for garbage collection.
2)  Each piece of data has a reference counter. If the reference counter equals
    zero, the occupied memory is returned to the memory pool at once. If the
    reference counter is about to overflow, a fresh copy of this piece of data
    is made with a reference counter set to one.
3)  Data is only created and destroyed. It is never changed.
4)  To the user, there is no difference between two expressions being equal,
    but stored in different parts of memory, and two expressions being two
    representations of the same parts of memory.
5)  There is no facility for named fields within a data structure.
Leaving one of these features out would have severe consequences for the other
features. (2) explains why (1) is true. (3) ensures that (2) is workable: if two
pieces of data are created equal they will remain so. This, in turn, explains
why (4) is true. (5) almost follows from (3) : in any full-fledged programming
language, named fields allow all types of actions on the named parts of a
data structure that are allowed on whole data structures, that is: creation
and destruction. But the possibility to destroy only part of a data structure
means that the entire data structure is changeable, which violates (3)."
          "In the current version of Bracmat, with objects, the last restriction (5)
no longer exists. As a consequence, restrictions (3) and (4) are not true for
objects. (2) needs the additional remark that the reference counter for objects
is made so big (counting to more than 1000000000000 before overflowing), that
overflow is practically ruled out. Restriction (1) is still true, which means
that the Bracmat programmer must take care of the deletion of some pathological
structures. (To be precise: circular structures, which were non-existent in the
object-less Bracmat.)"
          "How can a programming language that is created for handling data structures
do without named fields? If I only can create and destroy data, how can I let
data evolve gradually, piecemeal? The answer lies in the well-developed
pattern matching mechanism. Change of data is a two-step process. In the first
step you retrieve, by pattern matching, all those parts of the data
that you want to keep. The second step is building the new data from the
retrieved parts, together with new pieces. Creation of complex data structures
from parts is straightforward in Bracmat. For example, the variable Row is a
list of three words. We want to change the second word into the word |_cat_|:
{?} the dog runs:?Row       {initial creation}
{?} !Row:%?one % %?three    {step 1: retrieval of 1st and 3rd word}
{?} !one cat !three:?Row    {step 2: reconstruction}
{!} the cat runs
This may seem complicated and cumbersome, but look at this:
{?} 123:?a                  {create three variables a, b and c}
{?} a sentence:?b
{?} (a.silly,data*structure):?c
{?} (!a.!b.!c):(?b.?c.?a)   {permutation of 3 values in just 1 `statement'}"
          "Bracmat has no clear genealogy, but it has borrowed features from several
programming languages. It is not declarative, like Prolog, nor deeply object-oriented,
like Smalltalk, but it is procedural, like most
languages. Below, I have tried to make the origin of some details more
explicit:

C
    * conditional execution of right operands of `and' and `or'
    * parameter passing (only `by value')
Pascal
    locally defined functions and routines
Lisp
    * implementation of expressions in binary trees
    * weak type checking
    * late binding
Logo
    different notations for the same variable, depending on whether it produces or receives a value
Snobol, Icon
    * a well-developed pattern matching apparatus including backtracking
    * dual results of evaluations : both value and success/failure

Every similarity to other computer algebra systems is a matter of evolutionary
convergence."
    )
  & ( Bracmat-name
    =   T
      , "Why the name `Bracmat'?"
      ,   "The name Bracmat stems from Ludvig Holbergs novel `Nicolai Klimii iter
subterraneum', the history of Niels Klim who visits the planet Nazar and
comments the habits of its inhabitants. For example, the people of the country
Bracmat are clumsy juniper trees and Niels Klim initially thinks they must be
blind. But he discovers that their sight is so sharp that they
can see the smallest details in the far distance and therefore don't see
what is right in front of them. They are mostly occupied with astronomy and
transcendental philosophy, but the state also uses them to do prospection
for minerals in the mines."
          "It so happens that the Latin word `brachiatus', meaning `with arms' or
`with branches', in literature of botany often is shortened to `brachiat.'.
I like to think that Ludvig Holberg, who wrote the story in 1741, knew about
the works of Carl Linnaeus (1707 - 1778) and was inspired by him to populate
his planet with smart trees. The word `bracmat' is easily morphed into the
word `brachiat.', and at least one case can be found on the
internet where the Optical Character Reader has misinterpreted `brachiat.' as
`bracmat', caused by a black speck that almost connects the `h' and the `i'
in the word `brachiat.'! Whether true or not, this derivation highlights one
of the most prominent characteristics of the programming language Bracmat:
it is all about tree branches."
    )
  & ( colofon
    =   T
      , "How to obtain Bracmat"
      , "There are a few download options. Get the last revision from
https://github.com/BartJongejan/Bracmat.

At https://cst.dk/download/bracmat/ you can follow the history of Bracmat from
its inception somewhere in the eighties up to the last version. At this site
you can also find compiled versions for some platforms."
    )
  & ( morexmlps
    =   T
      , "Where to find example code on the internet"
      , "At https://rosettacode.org/wiki/Category:Bracmat over 300 tasks are solved
using Bracmat. The site is an excellent way to compare how the same task is
solved in numerous programming languages."
    )
  & ( syntax
    =   T
      , "The grammar of Bracmat"
      ,   "Note: in long lists the vertical bar | is left out.
<input>           ::= [<expression>] [;<input>]
<expression>      ::=   <whitespace> <expression> <whitespace>
                      | [<prefixes>] ( <expression> )
                      | <leaf>
                      | <expression> <binop> <expression>
<leaf>            ::= [<prefixes>] <atom-or-nil>
<atom-or-nil>     ::= <atom> | <nil>
<atom>            ::= \"<string>\" | <string>
<string>          ::= <character> [<string>]
<character>       ::= any printable character except \\ and \" | <spec>
<spec>            ::= \\a \\b \\t \\n \\v \\f \\r \\\" \\\\
<nil>             ::= \"\"   (or nothing at all, such as in \"()\")
<binop>           ::= = . , | & : <whitespace> + * ^ \\L \\D ' $ _
<prefixes>        ::= <prefix> [<prefixes>]
<prefix>          ::= [ ~ / # < > % @ ` ? ! !!
<whitespace>     ::= spaces, tabs, new line and form feed characters"
          "Whitespace (operator/cosmetic measure) almost never leads to confusion. It
does in (some) cases where a <nil> leaf without prefixes is adjacent to the whitespace
operator. For example : |_get' out$now_|. Bracmat interprets this as :
|_get'(out$now)_|. |_\"\"_| or |_()_| fixes the problem : |_get'() out$now_|.
Quotation marks are not part of the string they surround. They should be used
if necessary, e.g., |_\"in this case\"_| or |_\"he{this is not a comment}re\"_|.
Comments can be written everywhere, except in the middle of a string in
quotation marks. Comments are enclosed in {} and may be nested."
    )
  & ( charsettxt
    =   T
      , "Character set"
      , "Bracmat supports UTF-8 as well as ISO 8859-1 encoded source code. Usually
it does not matter how characters are encoded, because Bracmat merely sees
sequences of non-zero bytes. Only a few functions explicitly handle UTF-8
encoded characters. When lower- or uppercasing text, Bracmat assumes that the
argument is UTF-8 encoded, but graciously falls back to regarding the argument
as ISO 8859-1 encoded if parsing the argument as UTF-8 fails. UTF-16 and UTF-32
is not supported, because those encodings use zero-bytes.

As of July 2009 Codepage 850 is not supported, unless Bracmat is compiled with
#define CODEPAGE850 1."
    )
  & ( atotxt
    =   T
      , "Strings or atoms"
      ,   "A string in Bracmat is the same as an `atom'. If you envisage a Bracmat
expression as a tree like structure, atoms or strings are to be found in the
leafs. In Bracmat terminology, an empty leaf is syntactically represented
by <nil>. <nil> is not an <atom> proper, but an <atom-or-nil>. So not every
leaf contains an atom. However, leafs may contain other things
besides <atoms>, such as prefixes.

In Bracmat, atoms are less accessible than trees. There are, therefore,
ways to convert atoms to trees and back.
1) Conversion between an atom and its constituent characters:
  - get$(<atom>,MEM,VAP) puts every character in the literal <atom> in its own
    leaf in a tree, which has space operators in every node.
  - str$<tree> does more or less the inverse.
2) Conversion between an atom and executable Bracmat code:
  - get$(<atom>,MEM) literally `reads' an atom as though it is a file with
    Bracmat expressions.
  - lst$(<variable>,MEM) `writes' the expression that is bound to <variable>
    to an atom.
Atoms can be used as names for variables, functions, files, etc.. Often they
are used as literals, such as mathematical symbols or text."
          "Atoms consist of any number of non-zero bytes, up to the limits set by the
operating system and hardware. Atoms can be surrounded by quotation marks,
but are often optional. You do need them if you want parentheses,
braces, semicolons, operators or prefixes to be part of an atom. All UTF-8
encoded Unicode characters can be used in strings. Some special characters
have to be preceded by a backslash:

\\a
    attention (bell)
\\b
    backspace
\\t
    tab
\\n
    new line
\\v
    vertical tab
\\f
    form feed
\\r
    carriage return
\\\\
    backslash
\\\"
    double quote

If you precede a string with the prefix @, then backslashes are treated as
normal characters. E.g. sys$@\"C:\\gitprojects\\Bracmat\\Windows\\bracmat.exe\".
Instead of the tab and new line characters above, you may enter tabs and
new lines by pressing the tab and the return key, respectively."
          "Examples:

{?} this is a \"tree\" with\\nsix leafs
{?} (this is a \"tree\" with
      seven leafs)
{?} \"this\" has 4 characters and \"\" (nil) none
{?} \"this is an \\\"atom\\\" with 36 characters\"
{?} \"this string\\nno verb\"
{?} \"this string
    no verb either\"
{?} \"This string has a value\" = \"a value\"
{?} get$(!\"This string has a value\",MEM)
{!} a value"
    )
  & ( evaltxt
    =   T
      , "The four evaluators"
      ,   "In Bracmat, a binary operator may have four different effects, depending on
the context of the operator. For each of these contexts there is one evaluator.
Of these four evaluators, the macro evaluator is relatively unimportant.
The four evaluators are :
1) the expression evaluator, which takes care for the transformations of
   expressions.
2) the match evaluator, which handles the unification of pattern expressions
   with subject expressions.
3) the macro evaluator, which merely substitutes certain parts of an
   expression.
4) the archivist, which doesn't do anything but keeping expressions alive."
          "The expression evaluator is the first evaluator that a newly input expression
is confronted with. If necessary, it delegates tasks to one of the other three
evaluators.
The match evaluator can only delegate tasks to the expression evaluator and to
the archivist.
The macro evaluator can only delegate tasks to the expression evaluator.
The archivist doesn't delegate any tasks to other evaluators.

The cross link is in most cases a binary operator. The exceptions to this rule
are in the context of the match evaluator: some (combinations of) prefixes
involve the expansion of a chain of variable bindings and all but the last
subexpansion demand the expression evaluator.
In the scheme below, you'll find the current evaluator in the left column
and the successor evaluators in the top row. A cross link is represented by the
relevant operator or prefixes. If the change of evaluator only applies to the
left (right) operand of the cross link operator, the symbol `l' (`r') is used.
If the transition depends on the left operand being <nil>, the symbol `n' is
used."
          "             expression     match          macro          archivist
 expression                 :r             n'r            =r 'r
 match       &r $ 'l ?! !!                 n'r            =r 'r
 macro       $r
 archivist
"
    )
  & ( gettxt
    =   T
      , "get$(<atom-or-nil> [MEM][ECH][VAP][STR][TXT|BIN][JSN]|[[X]|[HT]ML[TRM]])"
      ,   "get$ reads and interprets characters in a string (internal memory) or file
(external memory or keyboard).

options :

|_MEM_|
    <present>
    The name of the first parameter is the source of the characters. (MEMory)
    <not present>
    A file with the name of the first parameter is the source.
|_ECH_|
    <present>
    The characters are echoed to the screen as they are read.
    <not present>
    No echo.
|_VAP_|
    <present>
    The (8-bit) characters are read as is. Extra spaces
    are inserted between the characters. (VAPorised)
    <not present>
    No extra spaces are added.
|_STR_|
    <present>
    The characters are read into one string.
    <not present>
    The characters are interpreted as parts of a Bracmat expression and
    evaluated after the whole expression has been read.
|_TXT_|
    <present>
    File is read in `text' mode (file mode |_r_|). When in combination with |_STR_|,
    any zero byte in the input will cause failure.
    <not present>
    File is read in binary mode (file mode |_rb_|). However, reading stops at the
    first zero byte! (Only |_fil$_| can read binary files.)
|_BIN_|
    <present>
    File is read in binary mode.
    <not present>
    File is still read in binary mode.
|_JSN_|
    <present>
    The input is parsed as JSON.
|_ML_|
    <present>
    The input is parsed as markup (SGML,XML or HTML). Any unrecognised entity
    reference is preceded by a DEL character (ASCII code 127 (decimal)). Any
    DEL character in the input is also preceded by a DEL character, similar to
    how the traditional escape character '\\' is itself represented by doubling
    it: '\\\\'.
|_HT_| (together with ML)
    <present>
    HTML entities are translated to UTF-8 characters.
    <not present>
    Only XML entities are translated to UTF-8 characters.
|_X_| (together with ML)
    <present>
    Only XML entities are translated to UTF-8 characters. Processing
    instructions are assumed to have the syntax |_<?...?>_|.
    <not present>
    Processing instructions are assumed to have the syntax |_<?...>_|.
|_TRM_| (together with ML)
    <present>
    Heading and trailing whitespace is cut down to a single space in character data.
    <not present>
    All whitespace is kept. Input can be exactly reproduced when writing, except HTML-entities.

The |_VAP_| option is evaluated before the |_STR_| option."
          "Applications :

  get'(matrix,ECH)

Read file |_matrix_| and evaluate the expressions (delimited by semicolons)
therein. If the system finds a syntax error in a multiple expression file,
the |_ECH_| option makes it easier to locate the error."
          "  get'(matrix,STR):?intern

Read file |_matrix_| into a string called |_intern_|. If this file contains
Bracmat instructions, they hereafter exist in a sleeping state in memory."
          "  get$(!intern,MEM)

!intern is, in this example, expanded to an atom with a very long name, namely
all of the text of file |_matrix_|. The sleeping expressions are evaluated one
after the other, just as if |_get'matrix_| was evaluated."
          "  get'(,VAP):?space-STRing

Read characters from standard input (normally keyboard) until next line feed
character. Put each character into an atom. Put all atoms into a linear list
with space operators. Bind this list to the name |_space-list_|."
          "  get'(\")y\",MEM)

Read the sleeping expression |_)y_| from memory. The lexical scanner
will find an unbalanced right parenthesis, which could mean that this Bracmat
session should stop. The |_y_| confirms this assumption and the program will
come to an end immediately. If the |_y_| hadn't been present, Bracmat would
ask |_end Bracmat session ? (y/n)_| after which the user has to choose. This
trick is useful in batch processing."
          "If the first parameter is <nil> or |_stdin_| and the |_MEM_| option is not used,
input is coming from standard input.
Take care that you put filenames in double quotes if they contain any
characters that can be misunderstood, such as dots, (back)slashes or dollars."
    )
  & ( lettxt
    =   T
      , "let$(<atom-or-nil>)"
      , "let$ checks whether a single character is a letter.
This function uses the Unicode definitions of letters as found in Unicode.txt.
On success, the single character is returned. The function fails if the
argument is not a single character that is a letter."
    )
  & ( lowtxt
    =   T
      , "low$(<atom-or-nil>)"
      , "low$ converts a string to all-lowercase.
The characters 'A'-'Z' are converted to 'a'-'z'. Other characters are handled
as UTF-8 encoded Unicode characters, but default to ISO 8859 (Latin 1) if
the argument is not valid UTF-8."
    )
  & ( tmetxt
    =   T
      , "tme$ or tme$GMT"
      , "The first form returns local time, the second UTC (Coordinated Universal Time).
The output has the same structure as C's tm struct and the ranges are the same,
except for month, year (western calendar year), day of the week and day of the
year.
                       range
    seconds           0 to 59
    minutes           0 to 59
    hours             0 to 23
    day of the month  1 to 31
    month             1 to 12
    the current year
    day of the week   1 to 7
    day in the year   1 to 366
    daylight saving time 0:no 1:yes

{?} tme$:(#:~<1:~>59.#:~<1:~>59.#:~<0:~>23.#:~<1:~>31.
          #:~<1:~>12.#:~<2024.#:~<1:~>7.#:~<1:~>366.(0|1))
{?} tme$GMT
"
    )
  & ( ugctxt
    =   T
      , "ugc$(<atom-or-nil>)"
      , "ugc$ determines the Unicode General Category of a character.
 Lu   Uppercase_Letter        an uppercase letter
 Ll   Lowercase_Letter        a lowercase letter
 Lt   Titlecase_Letter        a digraphic character, with first part
                              uppercase
 LC   Cased_Letter            Lu | Ll | Lt
 Lm   Modifier_Letter         a modifier letter
 Lo   Other_Letter            other letters, including syllables and
                              ideographs
 L    Letter                  Lu | Ll | Lt | Lm | Lo
 Mn   Nonspacing_Mark         a nonspacing combining mark (zero
                              advance width)
 Mc   Spacing_Mark            a spacing combining mark (positive
                              advance width)
 Me   Enclosing_Mark          an enclosing combining mark
 M    Mark                    Mn | Mc | Me
 Nd   Decimal_Number          a decimal digit
 Nl   Letter_Number           a letterlike numeric character
 No   Other_Number            a numeric character of other type
 N    Number                  Nd | Nl | No
 Pc   Connector_Punctuation   a connecting punctuation mark, like a
                              tie
 Pd   Dash_Punctuation        a dash or hyphen punctuation mark
 Ps   Open_Punctuation        an opening punctuation mark (of a pair)
 Pe   Close_Punctuation       a closing punctuation mark (of a pair)
 Pi   Initial_Punctuation     an initial quotation mark
 Pf   Final_Punctuation       a final quotation mark
 Po   Other_Punctuation       a punctuation mark of other type
 P    Punctuation             Pc | Pd | Ps | Pe | Pi | Pf | Po
 Sm   Math_Symbol             a symbol of mathematical use
 Sc   Currency_Symbol         a currency sign
 Sk   Modifier_Symbol         a non-letterlike modifier symbol
 So   Other_Symbol            a symbol of other type
 S    Symbol                  Sm | Sc | Sk | So
 Zs   Space_Separator         a space character (of various non-zero
                              widths)
 Zl   Line_Separator          U+2028 LINE SEPARATOR only
 Zp   Paragraph_Separator     U+2029 PARAGRAPH SEPARATOR only
 Z    Separator               Zs | Zl | Zp
 Cc   Control                 a C0 or C1 control code
 Cf   Format                  a format control character
 Cs   Surrogate               a surrogate code point
 Co   Private_Use             a private-use character
 Cn   Unassigned              a reserved unassigned code point or a
                              noncharacter
 C    Other                   Cc | Cf | Cs | Co | Cn
"
    )
  & ( upptxt
    =   T
      , "upp$(<atom-or-nil>)"
      , "upp$ converts a string to all-uppercase.
The characters 'a'-'z' are converted to 'A'-'Z'. Other characters are handled
as UTF-8 encoded Unicode characters, but default to ISO 8859 (Latin 1) if
the argument is not valid UTF-8."
    )
  & ( whltxt
    =   T
      , "|_whl'(<expression>)_|"
      , "|_whl'_| implements a |_while <expression>_| loop. The expression is repeatedly evaluated
until it fails. |_whl'_| always succeeds. Notice that |_whl'_| is faster than loops using tail recursion."
    )
  & ( contxt
    =   T
      , "Data structures"
      ,   "In Bracmat, linear lists can be made by separating the elements with comma,
plus sign, asterisk, space and dot. The first four operators create linear
structures (right descending lists), moving nodes as necessary, whereas the
dot operator creates any tree structure. In addition, the plus sign and the
asterisk (times) do not preserve the order of the elements if they are not
canonical order. Which operator one should use in a given situation depends on
the following considerations:
* Space, comma, plus and asterisk offer automatic concatenation of lists, but
  are slower than the dot.
* Space, plus and asterisk are useful if there is a need to search in a list,
  because these operator support backtracking, but they are slower than the
  comma.
* The comma can be used in linear lists that are accessed recursively and in
  record-like structures, where the elements must have absolute positions.
  The dot can be used for the same purpose.
* If a function has a fixed number of parameters, you should use dots to
  separate them.
* If there is a need to sort elements alphabetically, use the plus operator.
* Lists constructed with plus or asterisk behave like sets. Adding an element
  that already is present does not make the list any longer, but will instead
  increase a factor (plus) or exponent (astererisk)."
          "Examples :
{?} x=a.b.c
{?} y=p.q
{?} !x.!y
{!} (a.b.c).p.q

{?} x=a b c
{?} y=p q
{?} !x !y
{!} a b c p q

{?} set=jan+piet+klaas
{?} !set
{!} jan+klaas+piet

{?} !set+klaas
{!} jan+2*klaas+piet

{?} rotate=car,cdr.!arg:(?car,?cdr) & (!cdr,!car)
{?} rotate$(one,two,three,four)
{!} two,three,four,one

{?} rotate$((one,two),(three,four))
{!} two,three,four,one"
          "By combining dots, commas and spaces, one may build any tree-like data structure
that, thanks to the backtracking mechanism on space-separated lists, make
the formulation of queries (goals) almost as easy as in Prolog. This is an
example of a simple database, in which each row starts with a descriptor
field, followed by a varying number of similar fields.

{?} M=( (odd  ,1 3 5 7 9)
        (even ,0 2 4 6 8)
        (prime,2 3 5 7)
      )
We choose the space operator to form the backbone of the lists of numbers,
because we want to access these numbers associatively, by using the back-
tracking mechanism."
          "Let us formulate a query that searches for all numbers that occur in
two or more categories (odd, even, prime). The findings are to be
printed to the screen.

{?} ( !M
    :   ?                           { skip 0 or more rows --- }
        (?c1,?row)                  { ---fetch (number type, number row)--- }
        ?                           { ---skip 0 or more rows --- }
        ( ?c2                       { ---fetch another number type, }
        ,   ?                       {    skip 0 or more numbers, }
            ( %?`el                 {    fetch a number }
            & !row:? !el ?          { does number occur in earlier row ? }
            & out$(!el is both !c1 and !c2) { yes?  show result }
            & ~                     { not satisfied yet: fail and backtrack }
            )
            ?                       {    skip rest of numbers--- }
        )
        ?                           { ---skip rest of rows }
    )

This prints

    3 is both odd and prime
    5 is both odd and prime
    7 is both odd and prime
    2 is both even and prime

and finally fails when backtracking (induced by the |_~_|) has found all answers
to the query."
          "Experimentation with the implementation of matrices in Bracmat has revealed
that lists (of lists (of lists..)) lead to smaller and faster programs than
arrays, artificially made multidimensional by playing with the index.
A drawback of the list approach is its unconventionality. Much time has to
be spend in reformulating existing algorithms based on indices. On the other
hand, the list approach is essentially insensitive to the dimensionality
of the matrix at hand, and may even be indifferent to the number of indices."
    )
  & ( binovztxt
    =   M
      , "= . , | & : whitespace + * ^ \\L \\D ' $ _"
      , "These are the 15 binary Bracmat operators. The higher in the list, the lower
in the order of operations. Use parentheses to overrule the ordering of
precedence and force an operator to a higher position in the order of
operations, as in:

{?} (a+b)*(a+c)+a^(-1*d^2+(d+1)*(d+-1))
{!} a^-1+a^2+a*b+a*c+b*c

1 =
    assignment: (x=7) (square=.!arg^2)
    object member definition:
    (myobject=(place=Copenhagen) (setPlace=.!arg:?(its.place)))
2 .
    fixed data structure: |_(Palme.Olof.Sweden)_|
    object member referencing: (myhash..insert)$(xxx.998743)
3 ,
    automatically flattens sublists:
    |_(ham,(bread,butter),jam):(ham,bread,butter,jam)_|
4 |
    or else: |_get$myfile | out$\"Cannot read myfile\"_|
5 &
    and then: |_out$\"almost done\" & Done_|
6 :
    match subject with pattern:
    |_Meeting at 4 in room 24:? ?#hour ? ?#room ?_|
7 [whitespace]
    sentence, neutral element:
    |_Oh well this can go on and on:?a Oh ?z & !a:_|
8 +
    add, neutral term 0:|_(a+6+b+a+10)_|,|_(a+b:?x+a+?y & !x:0)_|
9 *
    multiply, neutral factor 1: |_(46546*647547564)_|,|_(a*b:?x*a*?y & !x:1)_|
10 ^
    raise to a power, neutral exponent 1: |_(9975^332)_|,|_(45:?n^?exp & !exp:1)_|
11 \\L
    take logarithm: 10\\L1050
12 \\D
    differentiate: x\\D(x^10)
13 '
    function evaluation (does not evaluate RHS): |_str'(b+a):\"b+a\"_|
    macro: |_()'(my name is ()$name)_|
14 $
    function evaluation (evaluates RHS): |_str$(b+a):\"a+b\"_|
    variable in macro: |_()'(my name is ()$name)_|
15 _
    dummy:   |_!expr:?lhs_?rhs & (do$!lhs)_(do$!rhs)_|  "
      ,   (1,savtxt objecttxt asstxt)
          (2,contxt objecttxt)
          (3,contxt)
          (4,binprotxt prostutxt1 pattxt)
          (5,binprotxt prostutxt1 pattxt)
          (6,asstxt pattxt pattxttxt pattxt2)
          (7,contxt)
          (8,algtxt)
          (9,algtxt)
          (10,algtxt)
          (11,algtxt)
          (12,difftxt)
          (13,funmactxt macrotxt transformtxt)
          (14,funmactxt escappattxt)
          (15,dumtxt funtxt3)
    )
  & ( savtxt
    =   T
      , "The = operator"
      ,   "This operator ensures that the right hand operator stays unevaluated. It is
mainly used in the definition of pieces of code (e.g., functions). The code
on the right is bound to the name on the left.

<atom>=<expression>

Each time when the value of <atom> is asked for, a fresh copy of <expression>
is made available. <expression> itself is unchangeable and can only be wiped
out by removing the binding between <expression> and its name, <atom>. This
has, in turn, no influence on the copies made earlier.

{?} a=2    { create binding }
{!} a
    S
{?} !a:?b  { bind copy to b }
{!} 2
    S
{?} !b     { show b's value }
{!} 2
    S
{?} a=3    { remove a's binding to 2}
{!} a
    S
{?} !b     { show b's value }
{!} 2
    S
"
          "There is a second way of using the = operator, with a slightly different
syntax :

<nil>=<expression>

The = operator serves as a shock proof container for <expression>.
The effect of evaluating this type of expression is almost the same as that
of the macro instruction |_()'<expression>_|. Indeed, after evaluating a macro
instruction we have an expression with the <nil>=<expression> syntax.

{?} (b+a)
{!} a+b
{?} (=b+a)
{!} =b+a
{?} ('(b+a))
{!} =b+a
{?} c=3
{?} (=b+a+$c)
{!} =b+a+$c
{?} ('(b+a+$c))
{!} =b+a+3"
    )
  & ( objecttxt
    =   T
      , Objects
      ,   "With the = and . operators you can construct and dereference conventional data
structures and even objects with methods. In an expression, each subexpression
with a = operator in the top node and an atom in the LHS of the top node
indicates a field or object method that can be accessed and changed
independently of other fields and methods, i.e. without the need to dissect and
reassemble the whole expression. Such expressions are objects. An object member
(a field or method) is addressed by using the LHS of the = operator as the
member's name, preceded by the object's name. The name of the object and the
name of the member must be separated by a dot operator.

In the example below an object named |_John_| is created with the members
|_length_|, |_age_| and |_name_|. The |_name_| member has two submembers
|_first_| and |_family_|:

{?} John = (length=180),(age=30),(name=(first=John) (family=Bull))

There is no prescribed way in which the members should be glued together to
form an object. Here, the comma operator and whitespace operator are used, but any
operator except the = operator can be used to separate field names.

John's length can be changed to 185 in the following ways:

{?} John.length = 185

or

{?} 185 : ?(John.length)
"
          "The same object can be assigned to another variable, creating an alias, but
we have to take care not to evaluate |_John_|, because that would create or
overwrite the variables |_length_|, |_age_| and |_name_|):

{?} !John:?alias       {wrong, (alias=length,age,name);}

{?} '$John : (=?alias) {right, (alias=
                                (length=185)
                               , (age=30)
                               , (name=(first=John) (family=Bull)));}

Bracmat replaces the expression '$John by the value of John, protected
against evaluation by a = operator. For that reason, the pattern on the RHS
of the match operator : contains a = operator as well. Now we can change John's
age by operating on the variable |_alias_|:

{?} alias.age = 31

To see that the above expression indeed has the wanted (side-)effect, we can
inspect |_John_|:

{?} lst$John

 (John=
   (length=180)
 , (age=31)
 , (name=(first=John) (family=Bull))
 );

Alternatively, we can also just show the field |_age_| in |_John_|:

{?} !(John.age)
{!} 31
"
          "It is also possible to create an alias for a subobject. Taking the previous
example, we could create an alias for the name member:

{?} '$(John.name):(=?nm)

Now assign a new family name:
{?} Flinter:?(nm.family)
{?} lst$John

 (John=
   (length=180)
 , (age=30)
 , (name=(first=John) (family=Flinter)));

Using an alias for a subobject can save some code and processing time if the
subobject is accessed many times. Without the alias for John's name, we can
change his family name in this way:

{?} Flinter:?(John.name.family)
"
          "It is valid to have an empty name for a member:

{?} x=(header=blabla) (=(a=1) (b=2))

Here, |_a_| and |_b_| are fields in a nameless subobject of |_x_|. We can ask for the
value of |_b_|:

{?} !(x..b)
{!} 2

To retrieve the whole subobject:

{?} '$(x.):(=?subobject)
{?} lst$subobject

 (subobject=
 (a=1) (b=2));
"
          "An alias can also be created for part of an object:

{?} x=(a=) (b=) (c=) (d=)
{?} '$x:(=(a=) ?alias (d=))

Now |_alias_| only shares the members |_x.b_| and |_x.c_| with |_x_|. The same result follows
from

{?} '$x:(=? ((b=) (c=):?alias) ?)
"
          "Objects can be composed to form new objects containing the union of the members
of the contributing objects:

{?} x=(a=) (b=)
{?} '((p=) ($x) (q=)):(=?r)
"
          "Evaluation of an expression that contains = operators can have
unexpected side effects, as the following example shows.

First suppose that |_x_| (containing one record with one anonymous field) is
unevaluated (case A) and assigned to two other variables:

{?} x=(=)
{?} !x:?y
{?} !x:?z

In this case, |_x_|, |_y_| and |_z_| are different objects. For example does

{?} 2:?(y.)

not affect |_x_| and |_z_|. Do the assignment again, but this time evaluating |_x_| only
once:

{?} !x:?y:?z

Now |_y_| and |_z_| are the same object, but still different from |_x_|.
A change made to |_y_| affects |_z_| but does not affect |_x_|."
          "Suppose that |_x_| IS evaluated (case B):

{?} (=):?x
{?} !x:?y
{?} !x:?z

Now |_x_|, |_y_| and |_z_| are the same object.

Explanation: in (A) the value of |_x_| is not evaluated, especially the LHS of
the = operator. Therefore, a new = node is created each time |_x_| is
evaluated. In (B), the value of |_x_| IS evaluated, so no new copies of the
= node are made."
    )
  & ( methodtxt
    =   T
      , Methods
      , "A method is function that is a member of an object. A method definition is not
different from a function definition, but the ways in which methods and a
functions are called are. While a function call only requires the name of the
function, a method call requires the name or definition of an object and the
name of the method, separated by a dot operator. In the body of a method it is
usually necessary to refer to other members of the same object - that is one of
the primary objectives of using objects. Such self-references start with |_its_|,
which is analogous to |_this_| in C++. Here is an example of an object that
represents a rectangle with an x-size and a y-size for the lengths of two
orthogonal sides. Apart from these two data members, the object also has a
member function |_area$_| that returns the product of the x-size and the
y-size, and another member function that computes the length of the diagonal.

{?} (rect=
      (x-size=5)
      (y-size=12)
      (area=.!(its.x-size)*!(its.y-size))
      (diagonal=.(!(its.x-size)^2+!(its.y-size)^2)^1/2)
    );
{?} (rect.area)$
{!} 60
{?} (rect.diagonal)$
{!} 13
"
    )
  & ( dumtxt
    =   T
      , "The dummy operator _"
      ,   "Bracmat has only one variable that binds to a binary operator, the _
operator. Worse even, this variable is global. Nevertheless this variable is
most useful in definitions of certain types of recursive functions
(tree walkers).

The assignment of a new value to the _ variable can only take place
in a match operation. A _ in a pattern is always receiving, whereas a _
outside a pattern is either giving or left unchanged. Try this :

{?} a_b             { This has unpredictable results. }
{?} x^y:?_? & a_b   { _ gets bound to ^. Thus a_b evaluates to a^b }
{!} a^b"
          "A _ is evaluated by the expression evaluator, but also by the macro
evaluator. The latter is useful if the _ has matched an operator that is
very volatile, such as & and |_|_|.
{?} (=!a:!b&!c):(=?left_?right) {match the &}
{?} '$_
{!} =&              { It worked, the _ is replaced by a &. }
{?} get$(str$('$_),MEM,VAP):\"=\" ?op & !op { freeze and slice }
{!} &               { The operator is immobilised in a string. }"
          "The _ variable is always expanded BEFORE the left and right hand side
operands are evaluated. That explains why new assignments in the operands do
not result in unwanted side effects in the upper node with the _."
    )
  & ( binprotxt
    =   T
      , "Binary operators in program flow"
      , "<exprA> & <exprB>
    (<exprA> and then <exprB>)
    <exprB> is only evaluated if <exprA> succeeds,
<exprA> | <exprB>
    (<exprA> or else <exprB>)
    <exprB> is only evaluated if <exprA> does not succeed.

In both cases <exprA> is always evaluated and <exprB> conditionally.
If <exprB> is to be evaluated, <exprA> and the & or | operator have served
their purpose. Therefore, they are eliminated before <exprB> is evaluated.
In this way, the program stack doesn't grow indefinitely when recursive
calls are made from the right hand side of any & or | operator occurring
in an expression . Even a conventional sequence of instructions (where the
success or failure of the evaluations of each instruction do not matter) can
make use of this tail recursion optimisation. In that case one uses the
pacifier (short cut prefix) |_`_| .

(`!a & !b)     !b is always evaluated. (sequence)
(`!a | !b)     !b is not evaluated. (useless in this form)

The pacifier or shortcut prefix is inherited by higher levels, it percolates
towards operators that are closer to the root of the tree, until it is
subsumed in situations like the above ones."
    )
  & ( hashtxt
    =   M
      , "Hash tables"
      , "If you need to manage a large data set it may be a good idea to use a hash
table instead of a list. Storing, retrieving and deleting are costly processes
in lists, but cheap in hash tables. Handling hash tables in Bracmat is very
simple. You create a hash table as follows

{?} new$hash:?myhash

Hereafter, |_myhash_| refers to a hash table and is treated in the same way as
a user defined object. Bracmat keeps the load factor between 50 and 100,
rehashing as necessary.

If you know the hash table is going to be much bigger than about 100 bins, you
can suggest the size of the table to Bracmat, but this is not necessary:

{?} new$(hash,1000000):?mybiggerhash

This tells Bracmat to start off with a million bins.

You can add user defined methods and member variables to a built-in Bracmat
object, but first you have to create the object. In the following example we
add a method called |_Insert_| to an hash table. This |_Insert_| method is to
give a warning when you add a value for a key that is already present in the
hash table.

{?} ( new$hash:?myhash               { Create a hash table myhash. }
    &   (
        = Insert                    { Add a method \"Insert\" to myhash   }
        =   K,V                     { that only allows one value per key. }
          .     !arg:(?K.?V)
              & (Its..find)$!K:(?.?v)
              &   out
                $ ( Key
                    !K
                    already
                    present
                    with
                    ( !V:!v&same
                    | different
                    )
                    value
                    !v
                  )
            | (Its..insert)$!arg
        )
      : (=?(myhash.))
    )

{?} (myhash..Insert)$(X.12);         { Insert the value 12 for key X. }
{?} (myhash..Insert)$(X.12);         { Try to do it one more time. }
|_Key X already present with same value 12_|

{?} (myhash..Insert)$(X.10);        { Try to insert another
                                     value for the same key.}
|_Key X already present with different value 12_|

{?} (myhash..insert)$(Z.1);          { Use the built-in insert method.}
{?} (myhash..insert)$(Z.1);          { Insert same value again. }
{?} (myhash..insert)$(Z.2);          { Also insert a different value. }
{?} (myhash..find)$X                 { Show all key-value pairs of X. }
{!} X.12

{?} (myhash..find)$Z                 { Show all key-value pairs of Z. }
{!} (Z.2) (Z.1) (Z.1)

{?} (myhash..remove)$Z:?values;

If you need to `finalize' an object just before it dies, you can add a user
method called |_die_| that takes no arguments. If the object is a hash table,
you could serialize and save the contents of the hash table to a file, or
you could write a message to the screen, as in this example, where we add
another member function, |_die_| to the already existing member functions in
the object |_myhash_|:

{?} !myhash:(=?mymyhashmethods)
{?} '( (die=.out$\"Who ordered th\")
       ()$mymyhashmethods
     ) : (=?(myhash.))

Let us check that we now have two user defined member functions in
the |_myhash_| object, namely |_die_| and |_Insert_|:

{?} lst$myhash

    (myhash=

    =   (die=.out$\"Who ordered th\")
        ( Insert
        =   K,V
          .     !arg:(?K.?V)
              & (Its..find)$!K:(?.?v)
              &   out
                $ ( Key
                    !K
                    already
                    present
                    with
                    ( !V:!v&same
                    | different
                    )
                    value
                    !v
                  )
            | (Its..insert)$!arg
        )
    )

And here is what happens when we delete the hash object:

{?} :?myhash

    Who ordered th

In the examples above we have already seen some built-in hash
methods in use. Here is the complete list:

1 |_find_|
    find all values for a given key
2 |_insert_|
    insert a value for a key
3 |_remove_|
    remove a key and all its values
4 |_ISO_|
    make all key access case-insensitive
5 |_casesensitive_|
    make all key access case sensitive. (Default)
6 |_forall_|
    apply a function to all key-value pairs"
      ,   (1,findtxt)
          (2,inserttxt)
          (3,removetxt)
          (4,ISOtxt)
          (5,casesensitivetxt)
          (6,foralltxt)
    )
  & ( findtxt
    =   T
      , "(myhash..find)$key:(?Key.?Value) ?OtherKeyValuePairs"
      , "Returns a whitespace-separated list of key-value pairs, all with the same key."
    )
  & ( inserttxt
    =   T
      , "(myhash..insert)$(Key.Value)"
      , "Inserts the key |_Key_| with the value |_Value_|. Multiple values for the same key are
possible and the same value can be inserted more than once for the same key."
    )
  & ( removetxt
    =   T
      , "(myhash..remove)$key:?KeyValuePairs"
      , "Removes the key with all its values and returns a whitespace-separated list of
key-value pairs."
    )
  & ( ISOtxt
    =   T
      , "(myhash..ISO)$"
      , "
Make all key access case-insensitive. This applies to the full Unicode table,
but defaults to ASCII and the upper 128 characters in the ISO8859-1 (Latin 1)
character set if the characters are not UTF-8 encoded."
    )
  & ( casesensitivetxt
    = T,"(myhash..casesensitive)$","Make all key access case sensitive. This the default."
    )
  & ( foralltxt
    =   T
      , "(myhash..forall)$<Function>"
      , "Apply the function to all key-value pairs. The function can be specified
by its name or by its function body. The forall method finishes when all
elements are traversed or before that if the function fails. The behaviour of
forall is undefined if the hash table is changed or deleted during the
traversal, although this can be done safely. For example, some members may be
missed and others may be processed more than once.

Example:

{?} new$hash:?myhash;           { create a hash table myhash }
{?} (myhash..insert)$(X.12);    { Insert the value 12 for key X. }
{?} (myhash..insert)$(Z.1);     { Use the built-in insert method.}
{?} ( (myhash..forall)          { Output all key-value pairs. }
    $ (
      =   Key,Value,loop
        .   ( loop
            =   !arg:(?Key.?Value) ?arg
              & out$(str$(\"Key=\" !Key  \" Value=\" !Value))
              & !loop
            )
          & ~!loop
      )
    )

  Key=X Value=12
  Key=Z Value=1
"
    )
  & ( calctxt
    =   M
      , "Floating point calculations"
      , "Bracmat is best at symbolic processing. However, sometimes you may want to do
floating point calculations, for example to a create a graphic illustration of
the result of some symbolic processing, such as a complex graph. Whereas the
graph is purely symbolic in nature, the drawing requires coordinates. For the
computation of those coordinates you may want to model the vertices as charged
particles and the edges as elastic strings connecting the particles. To let
this physical model evolve under the influence of elastic and Coulomb forces,
the computer must iterate many times over the same set of arithmetic
instructions. For purposes like these, Bracmat has an object type called `UFP'.

A UFP object houses UFP programming code that is syntactically the same as
Bracmat code, but semantically different:

* When a UFP object is created with |_new$_|, the passed Bracmat code is parsed
  and compiled to a bytecode. Bytecode can be listed using the |_print_|
  method. Compilation is fast, as is executing the resulting bytecode.
* There is no pattern matching. The |_:_| operator is only for assignment and
  for simple comparisons of two numbers.
* There are two data types: floating point numbers (scalars) and arrays of
  floating point numbers. An array can have a rank higher than 1 -
  multidimensional arrays.
* You need to declare the parameters that your home-brewn function needs.
* But you should not declare the variables that are not parameters.
* All values are C-doubles. There are no strings and no rational or integer
  numbers.
* The semantics of the |_|_| operator is very similar to that of |_if_|
  in imperative languages in that it does not return a value.
* Variables have function scope and are not visible in nested functions.

You create a UFP object by passing the definition of the floating point code
as the second argument, either by name or verbatim: 

    new$(UFP,<name of Bracmat code>):?<name>

or

    new$(UFP,(=<Bracmat code>)):?<name>

e.g.,

{?} (onePlusTwo=.1+2)
{?} new$(UFP,onePlusTwo):?myCalculation

or

{?} new$(UFP,(=.1+2)):?myCalculation

Hereafter, |_myCalculation_| refers to a UFP object and is treated in the same
way as a user defined object.

To start the calculation, you call the |_go_| method of the UFP object,

{?} (myCalculation..go)$
{!} 3.0000000000000000E+00

You can also pass parameters to a UFP object. Suppose that you want to
calculate the sum of two numbers, you can do it like this:

{?} (sumTwoNumbers=(s.a) (s.b).!a+!b)
{?} new$(UFP,sumTwoNumbers):?mySum
{?} (mySum..go)$(\"3.5\",5/3)
{!} 5.1666666666666670E+00

As a one-liner:

{?} (new$(UFP,(=(s.a) (s.b).!a+!b)).go)$(\"3.5\",5/3)
{!} 5.1666666666666670E+00  

Before you can get started with UFP objects you need to learn about the UFP
object API, parameters, variables, constants, arrays, loops, built-in functions
and user defined functions.

1 Member functions of UFP objects
    Member functions are the API: they constitute the communication channels
    between the Bracmat code outside and the Bracmat code inside the UFP
    object.
2 Built-in UFP functions
    These functions can be used in the code that runs inside a UFP object.
3 Parameters
    How are parameters passed from outside to inside UFP objects?
    And how are they passed to built-in and user defined functions?
4 Variables
    When to declare variables and how.
5 Constants
    There are two ways to write constant values into UFP source code.
6 Arrays
    Declaring rank and extents of arrays, indexing and accessing arrays.
7 Iterations
    How to escape a loop.
"
      ,   (1,CalcMethodtxt)
          (2,CalcFunctxt)
          (3,CalcParmtxt)
          (4,CalcVartxt)
          (5,CalcConsttxt)
          (6,CalcArraytxt)
          (7,CaltItertxt)
    )
  & ( CalcMethodtxt
    =   M
      , "Listing of UFP object methods"
      , "
The following methods are defined for UFP objects:
1 |_go_|
    Perform a floating point calculation.
2 |_trc_|
    Perform a floating point calculation, showing the details of each step.
3 |_print_|
    Show a listing of the instructions contained in the UFP object.
4 |_export_|
    Export the value of a variable contained in a UFP object.
"
      ,   (1,Calculatetxt)
          (2,CalcTrctxt)
          (3,CalcPrinttxt)
          (4,CalcExporttxt)
    )
  & ( CalcFunctxt
    =   T
      , "Listing of built-in functions and function-like constructs in UFP objects"
      , "Bracmat maps all floating point functions that are available as standard C
functions to Bracmat functions. For a description, see the documentation of the
math.h C header file.

In addition:

|_sign$<number>_| returns -1, 0 or 1, depending on whether the number is
negative, zero or positive.

|_cube$<number>_| returns the third power of the number.

|_sqr$<number>_| returns the second power of the number.

|_subtract$(<number1>,<number2>)_| returns number1-number2. (Remember that
Bracmat has no operator for subtraction!)

|_divide$(<number1>,<number2>)_| returns number1/number2. (Remember that
Bracmat has no operator for division!)

|_out$<number>_| writes a number to the console.

|_outln$<number>_| writes a number, followed by a new line to the console.

|_tbl$(<name>,<whole number>, ...)_| creates an array with the first argument
as name. Each whole number adds an extent. The number of whole numbers
defines the rank of the array. The array is destroyed when the UFP object is
destroyed or when another array by the same name is created.

|_rank$<name>_| returns the rank of the array named <name>.

|_extent$(<name>,<whole number>)_| returns an extent of the array named <name>.
The number must be non-negative and smaller than the rank of the array.

|_idx$(<name>,<whole number>, ...)_| Sets the pointer of array <name> to the
indicated index (or indices, if the rank is > 1).

|_whl'(<code>)_| Implements a loop.
"
    )
  & ( CalcParmtxt
    =   T
      , "UFP parameters"
      , "Since UFP objects only handle numbers and arrays of numbers, all
parameters passed to a UFP object must be numbers or arrays of numbers.
Numbers can be represented in Bracmat's native format or in any of the formats
recognized by the C |_strtod()_| function.

In the source code of the UFP, each parameter must be explicitly and completely
declared. Single values (scalars) are declared as |_(s.<parameterName>)_|,
while arrays must be declared as |_(a.<parameterName>.<extent>)_| (1-dimensional
arrays) or

|_(a.<parameterName>.<extent>.<extent>. ...)_| (multidimensional arrays).

In the UFP source code the same rules apply on the calling side, but in user
defined functions declarations are slightly simpler: you cannot specify the
extents on arrays. (These are inferred during compilation.) So scalars are
declared as |_(s.<parameterName>)_|, while arrays must be declared as
|_(a.<parameterName>)_|.

Here is an example of a UFP object that takes a two-dimensional array of
weighted numbers as parameter and returns the average and standard
deviation of the numbers.

{?} ( sd
    =   len SD compiledSD
      .   !arg:(,? [?len) { The value of len is used in 
                            the macro expansion below. }
        &     
            ' ( (a.nums,$len,2) { Before compilation, $len is replaced
                                  by the actual number of
                                     (,<number> <weight>) pairs.}
              .   0:?sum
                & 0:?i
                & 0:?totweight
                &   whl
                  ' ( !i:<($len)
                    & !(idx$(nums,!i,1)):?weight
                    & !(idx$(nums,!i,0))*!weight+!sum:?sum
                    & !weight+!totweight:?totweight
                    & 1+!i:?i
                    )
                & divide$(!sum,!totweight):?avg
                & -1*!avg:?offset
                & 0:?i
                & 0:?sumOfSquares
                &   whl
                  ' ( !i:<($len)
                    & !(idx$(nums,!i,0))+!offset:?X
                    & !(idx$(nums,!i,1))*!X*!X+!sumOfSquares:?sumOfSquares
                    & 1+!i:?i
                    )
                & sqrt$(divide$(!sumOfSquares,!totweight)):?result
                & !result
              ) 
          : ?SD     { SD contains the UFP code, before compilation. }
        & new$(UFP,!SD):?compiledSD { Create the UFP object. }
        & (compiledSD..go)$!arg
        & ((compiledSD..export)$(F,avg),(compiledSD..export)$(F,result))
    { The UFP object is deleted when compiledSD goes out of scope. }
    )

The input data is a list of pairs of numbers, where the first number is the
value and the second number is the weight of that value, for example:

{?} (,(,1 1) (,2 1) (,3 3) (,7 100) (,11 10)) : ?data

Now we can call the |_sd_| function to compute the average and standard
deviation of the values in |_data_|:

{?} sd$!data:(?average,?stddev)
{?} average !average stddev !stddev
{!} average 7.147826 stddev 1.522261

The representation of the input data is the same as the internal representation
of the equivalent JSON array:

{?} sd$get$(\"[[1,1],[2,1],[3,3],[7,100],[11,10]]\",MEM,JSN)
{!} 7.147826,1.522261

Scalar parameters are passed by value, while arrays are passed by reference.
That means that a function, as a side effect, can change an array that is
passed as a parameter. This is especially practical, because return values
of functions are always scalar values."
    )
  & ( CalcVartxt
    =   T
      , "UFP variables"
      , "Scalar UFP variables are not explicitly declared. Arrays are declared when they
are created.

Variables have a restricted scope. The main code and each user defined function
has its own scope. Variables in functions are not visible outside that
function and variables outside a function are not visible inside that function."
    )
  & ( CalcConsttxt
    =   T
      , "UFP constants"
      , "There are two ways to introduce constant values in UFP source code.
The most obvious one is writing a numerical value. Such values can be written
by using the native Bracmat format (rational numbers that can contain a |_/_|)
or by using one of the formats recognized by |_strtod()_|.
The other way to write constants into UFP source code is by means of macro
expressions, similar to how one uses |_#define_| in C."
    )
  & ( CalcArraytxt
    =   T
      , "UFP arrays"
      , "Arrays are allocated by the built-in |_tbl$_| function. This function takes a
number of parameters. The first parameter is the name of the array. The next
parameter is the extent of the array. Each following parameter adds another
extent and increments the rank by one. To create an array for the coordinates of
all nine planets of the solar system, one would as follows:

{?} ( 8:?nrOfPlanets
    & 3:?spaceDimensions
    &     new
        $ ( UFP
          ,
            ' (
              .   \"The array `planets' is allocated at compile time,
                   because the sizes are already known at that time.\"
                & tbl$(planets,$nrOfPlanets,$spaceDimensions)
                & rank$planets:?nrOfIndices
                & \"The array `dynamic' is allocated at run time.\"
                & tbl$(dynamic,!nrOfIndices)
                & 0:?index
                &   whl
                  ' ( !index:<!nrOfIndices
                    &   extent$(planets,!index)
                      : ?(idx$(dynamic,!index))
                    & 1+!index:?index
                    )
                & 1:?cells
                & 0:?index
                &   whl
                  ' ( !index:<!nrOfIndices
                    & !(idx$(dynamic,!index))*!cells:?cells
                    & 1+!index:?index
                    )
                & \"You can comment source code this way.
                   The value !cells is returned 
                   as the result of this function\"
                & !cells
              )
          )
      : ?UFPobject
    & (UFPobject..go)$:\"2.4000000000000000E+01\"
    & (UFPobject..export)$(N,dynamic)
    )
{!} ,8 3

The |_idx_| function selects an array element. This function has the same
signature as the |_tbl_| function. The first parameter is the name of the array
while the following parameters are index values, one for each array dimension.

For each dimension, the lowest index value is |_0_| and the highest value is
the the value of the extent of that dimension, minus one.

Each array has a position variable. The position variable is set by the |_idx_|
function and keeps its value until it is changed by another call to |_idx_|.
As long as there is no need to change the position variable, the `current' array
element can be accessed by treating the array as a scalar variable.

      idx$(planets,3,2)
    & \"200.3\":?planets

The above could also be written as
     
    \"200.3\":?(idx$(planets,3,2))

To change an array element by adding some amount, one can write

    1+!(idx$(planets,7,1)):?planets

To copy a value from one element to another, one can write

    !(idx$(planets,8,5)):?(idx$(planets,1,6))

Arrays are allocated as a contiguous C array of |_double_|. The size of this
array is the product of all the extents with which the array is created. The
position variable is just an index pointing into this C array."
    )
  & ( CaltItertxt
    =   T
      , "UFP iterations"
      , "There is just one way to implement a loop in a UFP object: using
|_whl'(<body of loop>)_|. In order to exit from the loop, the body of the
loop must have at least one comparison expression."
    )
  & ( Calculatetxt
    =   T
      , "(myCalculation..go)$<Parameters>"
      , "Once a UFP object is created, it can be executed using the |_go_| method. This
method expects zero or more parameters, as specified by the parameter
declarations in the UFP object's source code."
    )
  & ( CalcTrctxt
    =   T
      , "(myCalculation..trc)$<Parameters>"
      , "The |_trc_| method is equivalent to the |_go_| method, except that it
prints the details of each step it takes during execution of the source code.
The only use for |_trc_| is while debugging and optimizing the C-source code
`calculation.c'."
    )
  & ( CalcPrinttxt
    =   T
      , "(myCalculation..print)$"
      , "The |_print_| method writes a listing of the result of the compilation of
the UFP source code. The only use for |_print_| is while debugging and
optimizing the C-source code `calculation.c'."
    )
  & ( CalcExporttxt
    =   T
      , "(myCalculation..export)$(<format>,<name of variable of UFP object>)"
      , "After executing a UFP object, the results of the calculations are still hidden
in the UFP object. To make further use of the results, they must be exported as
native Bracmat expressions. The |_export_| method can export one variable at a
time. Only variables in the main source code can be exported, variables in user
defined functions cannot be exported. The variables that are declared as the
parameters of the UFP object can also be exported.
{?} (      new
        $ ( UFP
          , (
            =   (s.a) (s.b)
              .   divide$(!a,!b):?c
                & acos$-1:?pi
            )
          )
      : ?calc
    & out$(output (calc..go)$(22,7))
    & out$(\"b \" (calc..export)$(N,b))
    & out$(\"%f\" (calc..export)$(F,c))
    & out$(\"%a\" (calc..export)$(H,c))
    & out$(\"N \" (calc..export)$(N,c))
    & out$(\"Q \" (calc..export)$(Q,c))
    & out$(\"%e\" (calc..export)$(R,c))
    & out$(pi (calc..export)$(R,pi))
    & out$(pi (calc..export)$(\"%a\",pi))
    & out$(pi (calc..export)$(Q,pi))
    )

    output 3.1415926535897931E+00
    b  7
    %f 3.142857
    %a 0x1.9249249249249p+1
    N  3
    Q  884635641090633/281474976710656
    %e 3.142857e+00
    pi 3.141593e+00
    pi 0x1.921fb54442d18p+1
    pi 884279719003555/281474976710656

The first argument to the |_export_| method tells wich notation is expected in the output:

F or \"%f\"
    A signed value that has the form <[-]dddd.dddddd> is expected. The number of
    digits before the decimal point depends on the magnitude of the number.
    There are six digits after the decimal point.
H or \"%a\"
    A hexadecimal notation. This notation preserves all bits of a |_double_|.
N
    An integer is expected. Only digits are allowed, the first digit not being
    a |_0_|. The digits can be preceded by a |_-_| to indicate that the number
    is negative.
R or \"%e\"
    A floating point expression is expected: a signed value that has the form
    <[-]d.dddddde[+|-]dd[d]>, where <d> is one decimal digit, <dddddd> is six
    decimal digits, and <dd[d]> is two or three decimal digits.
Q
    A rational number is expected. Similar to |_N_|, but a single slash |_/_|
    is allowed between to digits, the digit following the |_/_| not being a |_0_|.
"
    )
  & ( prostutxt1
    =   T
      , "Program flow"
      ,   "Most binary operators are used in expressions that flow on their own or
flow not at all. In the first group are the arithmetic operators, in
the second is the dot operator. In between are the two other structuring
operators, comma and whitespace.

Branching to a function is done with the $ and ' operators :

a$b (or |_a'b_|)       evaluate function |_a_| with argument |_b_|

Branching without argument passing and local variables is done with the unary
operator (prefix) ! but often this prefix and its cousin !! are used for the
purpose of variable expansion, it just depends on whether a variable is bound
to an unevaluated or to an evaluated expression :

!X
    do subroutine X
!X
    expand X
!!Y
    expand expansion of Y (two |_!_|s is the maximum)
"
          "Conditional evaluation is decided by the success or failure of subexpressions.
Every (sub)expression has two kinds of value: a visible value and a
success(S)/failure(F)/ignore(I) value. Success and failure are primarily
decided by the low level functions in the interpreter. The ignore value
is generated if a failing expression is back-quoted. The & and | operators
are sensitive to the S/F/I value of the left operand (where I counts as S).
Often this left operand is a matching expression.

!a & !b
    if !a succeeds do !b
!a | !b
    if !a fails do !b
!subject : !pattern
    try to prove that !pattern describes !subject

The back quote |_`_| can be used to overrule the failure of a subexpression.
The tilde |_~_| negates failure and success.

`!p & !q
    do !p and then do !q
!a:!p & `!b | !c
    if !a matches !p do !b else do !c
~!a
    succeeds if !a fails and fails if !a succeeds
"
    )
  & ( prostutxt2
    =   T
      , "Some often used control structures"
      , "Here are the nearest equivalents of some traditional control structures.

Sequence:

a; b;
    `!a&!b
    !a !b
    !a,!b
    !a.!b

Repetition:

WHILE a DO b;
    whl'(!a&`!b)
DO b WHILE a;
    whl'(`!b&!a)
DO b UNTIL a;
    whl'(`!b&~!a)
FOR i := m TO n DO b;
    !m+-1:?i&whl'(1+!i:~>!n:?i&`!b);

Selection:

IF a THEN b ELSE c;
    !a&`!b|!c;
v := IF a THEN b ELSE c;
    (!a&`!b|`!c):?v
    (works even if !c fails)
SELECT  a WHEN  c1 : b1 WHEN  c2 : b2 OTHERWISE  bx;
    !a:(!c1&`!b1|!c2&`!b2|?&!bx);

Branching:

CALL a;
    !a;
CALL b(x,y,z);
    b$(x,y,z);
v := b(x,y,z);
    b$(x,y,z):?v;
"
    )
  & ( funmactxt
    =   T
      , "Function evaluation"
      , "The binary operators $ and ' are similar in most respects. In general, the
left operand evaluates to the name of a built-in or defined function, whereas
the right operand is an expression that is passed as an argument to the
function. The $ evaluates the right operand before it is passed over, the '
doesn't. Parameter passing is by value, although the implementation postpones
and limits copying of data as much as possible. In the code of the called
function, the passed argument is bound to a local variable that is always
called arg.

Most often, the left operand of the $ and the ' operator evaluates to an
alphanumeric name. There are a few special function names:
* No name at all. Here, the $ and the ' operator have decidedly different and
  complementary roles. (Forced evaluation of subexpressions in otherwise
  unevaluated expressions, such as patterns)
* An integral number. (Array indexing.)
* Only prefixes. (Prefix pasting or influencing success and failure of
  non-atomic expressions.)

Function calls are even effective in patterns, as it is fair to assume
that the $ and ' operators seldom occur in subjects and so need not to be
matched. (The same is, a fortiori, true for the & and | operators.) In patterns,
the return value of a function is part of the pattern. A function may be
called several times during one evaluation of a matching expression, due to
backtracking and retrying."
    )
  & ( macrotxt
    =   T
      , "Macro evaluation"
      , "The ' operator with empty LHS is the macro evaluator. The macro evaluator
returns the RHS unchanged, except where $ operators with empty LHS occur.

The expression to the RHS of such a $ operator must evaluate to the name of a
variable or to a definition. The whole $ expression is then replaced by the
value of the variable or the definition. The following example illustrates
three ways how you can make sure that the LHS of the $ operator is empty.

{?} x=un
{?} y=(member=deux)
{?} '(one ($x), two \"\"$(y.member), three ()$(=trois))
{!} =one un,two deux,three trois

Here is an example that shows that the RHS of the $ operator can be an
expression that first needs to be evaluated:

{?} a=eins
{?} b=zwei
{?} dice=clk$
{?} '(Eins oder zwei? ()$(!dice:<1&a|b))
{!} =Eins oder zwei? eins
    {Do something that makes the clock tick for a while.}
{?} '(Eins oder zwei? ()$(!dice:<1&a|b))
{!} =Eins oder zwei? zwei

You can construct any Bracmat expression using macro evaluation. For example,
the function |_F_|, below, transforms an expression with + and * operators to a
pattern, replacing any non-empty atom that is not a number to a pattern
variable that either is receiving or giving, depending on whether the atom
occurs for the first time or not, when reading the expression from the
beginning to the end.

{?} (F=
      seen f
    .   :?seen
      & ( f
        =   a b
          .   !arg:%?a+%?b&'($(f$!a)+$(f$!b))
            | !arg:%?a*%?b&'($(f$!a)*$(f$!b))
            |     !arg
                : (
                  | #
                  | e
                  | i
                  | pi
                  )
              & '$arg
            | !seen:? !arg ?&glf$('(!.$arg))
            | !arg !seen:?seen&glf$('(%?.$arg))
        )
      & f$!arg
    );
{?} F$(a*b+3*a*c)
{!} =%?a*%?b+3*!a*%?c

Now we can use the pattern to match expressions with the same structure and
with the same operators

{?} x*y+3*x*z:!(F$(a*b+3*a*c))

The function F can only handle expressions containing + and * operators.
Now we will in a few steps amend F so that it can handle any operator. This is
done by using the dummy |___| operator.

As a first step, we will have to protect the argument of F against evaluation,
because otherwise we will never be able to analyse expressions that evolve to
different expressions when evaluated. So, from now on we will use F with the
' operator, like so.

{?} F'(a*b+3*a*c)

To simplify the first amendment, we will only handle expressions with the +
operator. Later we will generalize to handling any operator.

{?} (F=
      seen f
    .   :?seen
      & ( f
        =   a b g
          .     !arg:(=%?a+%?b)
              & '($(f$('$a))+$(f$('$b)))
            |   !arg:(=?g)
              & (     !g
                    : (
                      | #
                      | e
                      | i
                      | pi
                      )
                  & !arg
                | !seen:? !g ?&glf$('(!.$g))
                | !g !seen:?seen&glf$('(%?.$g))
                )
        )
      & f$('$arg)
    );

{?} F'(a+b+pi+a)
{!} =%?a+%?b+pi+!a

Now we replace the |_+_| operator by the dummy operator |___|. If we only do that,
then we will only see |___| operators in the result. That is because in a macro
context, a |___| operator is not evaluated to its current value. However, if the
RHS expression of a $ operator with empty LHS is headed by the |___| operator,
then the |___| operator is evaluated to its current value, analogous to what
happens if the RHS were the name of a variable. So we add an extra $ operator.

When the |___| operator is evaluated to its current value, the LHS and the RHS are
also evaluated.

{?} a^b:?_?
{?} LHS:?left
{?} '$(($left)_($(=RHS)))

Without evaluation of |___| operator:

{?} '($left)_($(=RHS))
{!} =LHS_RHS

With evaluation of |___| operator:

{?} '$($left)_($(=RHS))
{!} =LHS^RHS

Now we use this in the function |_F_|:

{?} (F=
      seen f
    .   :?seen
      & ( f
        =   a b g
          .     !arg:(=%?a_%?b)
              & '$($(f$('$a)))_($(f$('$b)))
            |   !arg:(=?g)
              & (     !g
                    : (
                      | #
                      | e
                      | i
                      | pi
                      )
                  & !arg
                | !seen:? !g ?&glf$('(!.$g))
                | !g !seen:?seen&glf$('(%?.$g))
                )
        )
      & f$('$arg)
    );

{?} F'(a+b_k&out$y&$$(=.arg))
Finally, we ensure that atoms that already have a prefix are treated in the
same way as empty strings and numbers.

{?} (F=
      seen f
    .   :?seen
      & ( f
        =   a b g
          .     !arg:(=%?a_%?b)
              & '$($(f$('$a)))_($(f$('$b)))
            |   !arg:(=?g)
              & (   (   !g
                      : (
                        | #
                        | e
                        | i
                        | pi
                        )
                    | ~(glf$('(~`/#<>%@?!.$g)))
                    )
                  & !arg
                | !seen:? !g ?&glf$('(!.$g))
                | !g !seen:?seen&glf$('(%?.$g))
                )
        )
      & f$('$arg)
    );

{?} F'('(the hare&$the tortoise))
{!} ='(%?the %?hare&$!the %?tortoise)

In the above example the argument of the |_F_| function is returned in an
unevaluated state, though transformed to something else. The last input was a
macro expression, and the result is still a macro expression.

Now suppose that we want to produce the macro expression

    '(There are 23 elements in list ()$L)

by means of another macro expression that evaluated the number of elements to
23. Something like this:

{?} 23:?N
{?} '('(There are ()$N elements in list ()$L))

This generates the error |_macro evaluation fails because rhs of $ operator is not bound to a value: $L_|.
What is needed is to 'escape' the $ operator in the subexpression ()$L, since we do not want ()$L to be
evaluated. This is done with and extra $ operator, similar to how a backslash is escaped in many
programming languages:

{?} 23:?N
{?} '('(There are ()$N elements in list ()$($L)))
{!} ='(There are 23 elements in list ()$L)

More examples:
{?} '(b+a c)
{!} =b+a c
{?} (x=value) & '(a ($x) z)
{!} =a value z
{?} (object=(member=value)) & '(a ($(object.member)) z)
{!} =a value z
{?} '(a ($(=value)) z)
{!} =a value z

{?} (=a^b):(=?_?) & '(dummy (a_b) power ($(a_b)))
{!} =dummy a_b power a^b

{?} '(one dollar ($($)))
{!} =one dollar ()$
{?} '(two dollars ($($($($)))))
{!} =two dollars ()$($)
"
    )
  & ( transformtxt
    =   T
      , "Program transformation"
      , "Bracmat code is data. Yet it is easier to transform the internal representation
of JSON or XML data than to transform a Bracmat program. The reason is that for
code introspection it is necessary to turn off the expression evaluation that
normally takes place in patterns. This can be achieved by using macros. Here is
an example that reverses (|_rev$_|) and lowercases (|_low$_|) all leaves, but
keeps everything else the same: prefixes, operators - even those that play
special roles inside patterns, such as the |_!_| prefix and the |_ _ _| operator.

{?} ( tr
    =   a b f
      .   flg$!arg:(=?f.?arg)
        &   glf
          $ (
            ' ( $f
              .
                $ (   '$arg:(=?a_?b)
                    & '$($(tr$('$a)))_($(tr$('$b)))
                  | low$rev$!arg:?arg&arg
                  )
              )
            )
    )
{?} tr$(=foo\\L\"STRing\" ~!(sin$4/56) !and_?<UNDERSCORE)
{!} (=oof\\Lgnirts ~!(nis$65/4) !dna_<?erocsrednu)"
    )
  & ( unops
    =   T
      , "Minus sign"
      , "The minus sign |_-_| has only its normal arithmetic meaning when used as an
unary operator in front of a rational number or the imaginary number |_i_|.

If a product contains both a rational number and the number |_i_|, the |_i_|
takes precedence in accepting a minus sign:

                   -7*i*a

is evaluated to

                   7*-i*a

The advantage of having both |_i_| and |_-i_| becomes clear by considering
the following:

                   (-1*i)^1/3

evaluates to

                   (-i)^1/3

which is written as |_-i^1/3_|. As expected, this is the complex conjugate of

                    i^1/3

If Bracmat did not have a separate representation for |_-i_|, then

                   (-1*i)^1/3

would evaluate to |_i_|,

(because i^3 is equal to |_-i_|),which means that Bracmat would not consider
(-1*i)^1/3 and i^1/3 as complex conjugates.

The transcendental numbers |_e_| and |_pi_| do not accept arithmetic minus signs.
"
    )
  & ( naamloos
    =   T
      , "The nameless functions $<expression> and |_'<expression>_|"
      ,   "Sometimes a variable predictably will evaluate to the same value repeatedly,
for example in an inner loop or a pattern that repeatedly backtracks. In
such situations macro substitution can improve performance by replacing the
variable by its value in an early stage.

In Bracmat, a macro has the general form |_'<expression>_|. When |_'<expression>_| is
evaluated, <expression> is searched for subexpressions headed by the operator
$, with empty LHS. Such subexpressions are replaced, depending on what is
found on the RHS of the $ operator.

After macro substitution has taken place, what remains is an expression of
the form =<expression>. The = operator is a safeguard against evaluation of
<expression>.

Macro substitution makes it possible to dynamically create unevaluated code and
bind it to a variable.

{?} '($out):?my-fun-var
{?} !my-fun-var$(Hello world)
{?} '($out):(=?my-fun-alias)
{?} my-fun-alias$(Hello world)"
          "Pattern matching can sometimes be made more efficient by using macro
substitution, but the resulting code is harder to understand:

{?} ( 0:?count
    &   41 3 5 7 6 23 12 11 19
      :   ?
          %?`A
          ?
          ( %?`B                        {Each number pair [A,B]}
          & !A+!B:?C                    {is added only once, giving C. }
          &   '(? ()$(!count+1:?count&C) ?)
            : (=?rem)                   {C's value is hard-coded into rem}
          )
          !rem                          {which is the remaining pattern. }
    & out$(after !count \"trials:\" !A \"+\" !B \"=\" !C )
    )
after 16 trials: 5 + 7 = 12"
          "In the same way, function code can be pieced together before it is ever
executed.

{?} power=three
{?} ((!power : two & (=!arg^2)) | (=!arg^3)) : (=?abc)  {If power=\"two\",
   \"abc\" is bound to \"!arg^2\" (unevaluated). Otherwise, \"abc\" is bound to \"!arg^3\".}
{?} '(.!arg + -1*$abc + 2) : (=?poly) {\"poly\" is the name of a new function
        that will return a value that depends on the current value of arg
        and on the value of power at the time when abc got its binding.}
{?} lst$poly { show poly's definition }
{?} poly$4
{!} -58"
          "The macro construct '<expr> is useful if an expression has to be executed
many times while parts of it remain constant, for example in nested loops:

Without macro construct (5 by 5 multiplication table) :

{?} 0 : ?m                    { initialise counter of outer loop }
{?} (outer = 1+!m : <6 : ?m   { code for outer loop }
            & put$\\n          { start output on new line }
            & 0 : ?n          { initialise counter of inner loop }
            & `!inner         { execute inner loop }
            & !outer)         { loop }
{?} (inner = 1+!n : <6 : ?n   { code for inner loop }
           & put$(!m X !n \"=\" !m*!n \", \")
                              { the same !m is expanded 10 times }
           & !inner)          { loop }
{?} !outer"
          "With macro construct :

{?} 0:?m
{?} (outer = 1+!m : <6 : ?m
            & '( 1+!n : <6 : ?n
               & put$($m X !n \"=\" ()$m*!n \",\")
                              { \"!m\" is expanded only 2 times }
               & !inner
               ) : (=?inner) { at each pass through the outer loop
                              the inner loop \"inner\" is defined anew }
            & put$\\n
            & 0 : ?n
            & `!inner
            & !outer)
{?} !outer"
    )
  & ( lambda
    =   T
      , "Lambda calculus, currying"
      , "The lambda abstraction
      (λx.x)y

translates to
    /('(x.$x))$y

Bracmat's implementation of lambda calculus is a variant of Bracmat's macro
substitution. The expression
     /('(x.$x))

evaluates to itself, not to something like
    /(=(x.foo))

(assuming that the variable |_x_| had the value |_foo_|). In contrast, the same
expression without the leading slash
    ('(x.$x))

evaluates to
    =x.foo

The RHS of the $ operator must be an atom.

In an lambda abstraction
    /('(x.$x,$y))

$x is a bound variable and $y is a free variable.

The expression $x is only replaced by a value if |_x_| is the variable in the
lambda abstraction or a lambda abstraction that contains the lambda
abstraction, as in
    /('(x.(/('(y.($x) ($y)))$aap)))$noot

which evaluates to
    noot aap

No Bracmat variables come into play, not even |_arg_|. Thus, in the example above
the value |_aap_| is bound in |_($x)_|, but never assigned to a variable |_x_|.

The expression
    /('(x.(/('(x.($x) ($x)))$aap)))$noot

evaluates to
    aap aap"
    )
  & ( difftxt
    =   T
      , Differentiation
      ,   "<variable> \\D <expr>

Bracmat knows how to differentiate expressions in which no other binary
operators occur but + * ^ and \\L.
Example:

{?} y\\Dx\\D(a^(x^2+y^2))
{!} 4*a^(x^2+y^2)*x*y*e\\La^2
{?} y\\Dr
{!} 0
"
          "The last example gives zero, which in many applications isn't what we want.
Often, with |_y_| we express the <y>-component of a vector with length <r>, and <r>
consequently is a function of <y> (and the other components). We can solve this
as follows:

{?} dep=(r.x) (r.y) (r.z) {'dep' is a special variable}
{?} y\\Dr
{!} y\\Dr
"
          "Now the expression is just left unevaluated. Later, you can substitute an
expression for |_r_| in terms of its components

{?} y\\D(r^-1):?derivative
{!} -1*r^-2*y\\Dr
{?} sub$(!derivative.r.(x^2+y^2+z^2)^1/2):?derivative
{!} -1*y*(x^2+y^2+z^2)^-3/2
"
          "And, if you like, you can simplify the result by putting |_r_| back in:

{?} sub$(!derivative.x^2+y^2+z^2.r^2):?derivative
{!} -1*r^-3*y
"
    )
  & ( algtxt
    =   T
      , "Algebraic operations"
      ,   "addition
    <term> + <term>
multiplication
    <factor> * <factor>
exponentiation
    <base> ^ <exponent>
logarithm
    <base> \\L <expr>

Subtraction and division are treated as special forms of addition and
multiplication. Therefore there are no binary operators for subtraction and
division. (The minus sign |_-_| and the slash |_/_| can be used in numbers, however.)

If one operand of an algebraic operator is evaluated then the other one is
normally evaluated as well, even if this may seem unnecessary (multiplication
by 0). This is done to ensure that all side effects take place as intended.
However, if an operand fails to evaluate, then the algebraic expression fails
too and if the failing operand is the left hand side of the expression, then
the right hand side is not evaluated. In this sense algebraic operators behave
like the logical & operator."
          "Bracmat gives the user practically no control over the format of evaluated
algebraic expressions, such as the order of terms or factors. Bracmat tries to
present algebraic objects in a unique (canonical) form. This is in many cases
an unattainable goal : the forms

    (a+b)*(c+d)

and

    a*c+a*d+b*c+b*d

are both stable expressions. On the other hand,

    (a+b)*(c+d)+e

becomes

    e+a*c+a*d+b*c+b*d

Bracmat keeps completely factorised expressions as they are, because
factorization is an expensive operation. For the same reason, Bracmat does not
automatically factorise factorisable expressions. Another domain of duality
are expressions with logarithms.

Sums and products start with rational numbers, followed by |_pi_|, |_i_| and |_e_|
(if present, that is). Then follow other terms and factors. It is recommended
not to assume anything about the ordering of these terms and factors, as
this may change in later versions of the program."
    )
  & ( unpattxt
    =   T
      , "Prefixes and pattern matching"
      ,   "In patterns, atoms and expressions within parentheses may be preceded by
prefixes that control the matching process.

Below, use the term `trivial elements' for elements that are either neutral or
zero. A list expression (an expression that links elements with the space
operator) has the empty string as neutral element. In sums, |_0_| (zero) is the
neutral element. In products, |_1_| is the neutral element. So the empty string,
|_0_| and |_1_| are trivial elements in lists, sums and products, respectively. In
addition, |_0_| is also a trivial element in products. Lists and sums do not have
`zeros'.

|_!_| and |_!!_|
    in front of an non-nil atom or an expression denoting a member of an
    object causes expansion of the atom or the member to its direct or
    indirect binding. This binding is matched with the subject.
|_`_|
    causes backtracking if the pattern did not successfully unify with a
    non-trivial element of the subject-list. A list is an expression
    consisting of terms (|_+_| operator), factors (|_*_| operator) or words
    (whitespace operator). In non-sophisticated patterns, |_`_| means
    simply : unify with at most one non-trivial element.
    Zero non-trivial elements are allowed, in which case unification takes
    place with an implicit trivial element: Bracmat sees 0's everywhere in a
    sum, 1's in a product and zero length words in a sentence.
|_?_|
    unifies with anything. If ? is followed by a non-nil atom denoting a
    variable or an expression denoting a member of an object, then the matched
    part of the subject is captured by this variable or member. In other
    words, pattern matching can have assignment as a side-effect.
|_@_|
    unifies only with atoms. Also, if prefixed to the |_:_| operator, it
    indicates that the pattern applies to the characters inside the atom
    (string match).
|_%_|
    causes the match to succeed only with one or more non-trivial elements of
    the subject-list. (Exception: in combination with |_[_| prefix.)
|_<_|
    unifies only with atoms that are less than the atom following the |_<_|
    prefix.
|_>_|
    unifies only with atoms that are greater than the atom following the |_>_|
    prefix.
|_#_|
    unifies only with rational numbers.
|_/_|
    unifies only with non-integer rational numbers.
|_~_|
    constrains the match to subjects that are not equal to the atom following
    the ~ prefix.
|_[_|
    Position prefix. Must be followed by an expression that evaluates to a
    number (for example |_[4_| or |_[(!pos+3)_| ) or by a variable having a question
    mark as in |_[?pos_|. In the first case, the pattern cannot succeed unless the
    element following the [ element is at the indicated position. The |_[_|
    element itself does not occupy a position; it sits in front of the
    indicated position. The second form is for querying the current position.
    Position 0 is the start of the subject. Positive positions count from the
    beginning of the subject, negative positions from the end. Position -1 is
    the position following the last element. (When combined with |_%_| the
    meaning is different.)


The above prefixes may be combined. The ordering in which they are input by the
user is irrelevant; Bracmat keeps prefixes in this order :
    [ ~ / # < > % @ ` ? ! !!
Repeating prefixes in front of the same atom does not convey a new meaning to
the pattern, except for the |_!_| and the |_~_| prefixes. More than one |_!_| is
interpreted as the |_!!_| prefix. An odd number of |_~_| is treated as a single |_~_|, an
even number thereof is treated as none. A |_~_| in front of other prefixes negates
the first of them. The most useful combinations are:

|_?!_|
    in front of an atom causes the atom to be expanded to its binding.
    This binding is treated as a variable name.
|_?!!_|
    is like ?!, but expands two levels deep (with an evaluation of the
    first level expansion), instead of one.
|_<>_|
    is like a solitary ~, but uses case insensitive matching. See also |_~<>_| below.
    |_<>_| is for negated case insensitive matching.
|_/<>5/6_|
    unifies only with non-integer rational numbers unequal to 5/6.
|_~<_|
    means `greater or equal' (`not less').
|_~>_|
    means `less or equal'.
|_~<>_|
    means `not different', i.e. `the same, in some sense'. Strings
    are compared case insensitive. This applies to the full Unicode
    table, but defaults to ASCII and the upper 128 characters in the
    ISO8859-1 (Latin 1) character set if the characters are not UTF-8
    encoded. Subject and pattern can have different encodings and still
    match with success.
|_~#_|
    does not unify with rational numbers.
|_~/_|
    does not unify with non-integer rational numbers.
|_~/#_|
    unifies only with integer numbers.
|_~/#<9_|
    unifies only with integer numbers less than 9.
|_~/#<>0_|
    unifies only with non-zero integer numbers.
|_~@_|
    unifies only with non-atomic expressions.
|_~`_|
    backtrack immediately.
|_[%_|
    The current subject is stored in the variable |_sjt_| and the expression
    carrying this prefix combination is evaluated. If the evaluation succeeds,
    the match succeeds and vice versa. The subject can be a neutral element of
    the subject list.

Many of these combinations can be combined further, e.g., ~/#?!! accepts only
an integer number and binds it to the indirect binding of the atom following
the prefixes."
          "
If you want to match pattern !pat one or more times (in Regex lingo this is
written as {pat}+ ), use the complex pattern |_(? !pat|`)_|. Likewise, if you
want to match |_!pat_| zero or more times ( {pat}* ), use |_(|? !pat|`)_|.
These patterns should not be the last subpattern or precede a subpattern that
is static and fixes the end point of the repeating sequence, because the
correct working of the repeating patterns depends on repeated backtracking
from following subpatterns. Bracmat may be optimized to skip such
backtracking and jump to the `right' end position if that is fixed by the next
subpattern.

In the last resort, you can add a pattern like |_()_| or |_(&)_| or |_(|)_| or |_(:)_|,
which match with an empty list only (assuming that the connecting nodes are
spaces, otherwise use 0 in the case of a sum and 1 in the case of a product).
Such patterns don't fix the next position.
This example implements the regular expression |_{a}+ {b}* {c}+_|:

{?} a a a c c:(? a|`) (|? b|`) (? c|`) (&) & Success! | Failure!
{!} Success!
    S

The next pattern matching operation fails, because the |_k_| cannot be matched
by any of the subpatterns.

{?} a a a k a m:(? a|`) m ()
    F

However, if we apply the same pattern to the string |_aaakam_| in a string pattern
matching operation, the match succeeds:

{?} @(aaakam:(? a|`) m ())
{!} aaakam
    S

The reason why this patterns behaves differently is that string pattern matching is
made more efficient by first handling the low hanging fruits, i.e. the subpatterns
that are non-empty strings, in casu, the |_m_| subpattern. When the algorithm has
found \"m\" in the subject string |_aaakam_|, it knows immediately that the preceding
subpattern has to match the string that precedes the |_m_|, which is |_aaaka_|.
The preceding subpattern is |_(? a|`)_|.
So let us try that:

{?} @(\"aaaka\":(? a|`))
    S

To make the subpattern |_(? a|`)_| work as intended (namely as matching any number
of |_a_|'s and nothing else) we have to append another subpattern, one that
is not a non-empty string, such as |_()_|. In fact, we have to add yet another
one to make it work.

{?} @(\"aaaka\":(? a|`) () ())
    F

Now we can see how the original pattern can be changed to make it work for string
pattern matching: we replace the last |_()_| by a subpattern |_m_|

{?} @(\"aaakam\":(? a|`) () m)
    F

Stuffing a string pattern with empty strings |_()_| circumvents optimization.
This is useful if we want to use subpatterns that expect the matcher to
repeatedly backtrack.

In list pattern matching such neutral elements don't change the result of the
match, but they can slow down the process.

{?} a a a k a m:() (? a|`) () m ()
    F

{?} a a a k a a m:() (? a|`) () k (? a|`) () m ()
{!} a a a k a a m
    S"
    )
  & ( escappattxt
    =   T
      , "Escaping operator in patterns"
      ,   "Some operators can not be part of a pattern unless 'escaped', because these
operators play an active role in pattern matching instead of being passive part
of a pattern. These operators are = | & : ' $ _"
          "The normal role of these operators is ignored by the pattern matching
evaluator if they are escaped with a $ node with an empty LHS.
{?} (=foo'bar):(=$(foo'bar))
{!} =foo'bar

{?} (=foo'bar):(=$(?f'?x)) & !f !x
{!} foo bar

The escape operator only affects the top node of the escape operator's RHS.
The LHS and RHS of the affected node are matched against the subject in the
normal way.
{?} vowel=.!sjt:(a|e|i|o|u|y)  { Function to be used in a pattern to
                            check that the subject is a single vowel. }

{?} (=a$123):(=$((vowel')$(#:?n))) { Only the \"$\" between \")\" and \"(\"
                            is escaped, because that is the top node of
                               \"(vowel')$(#:?n)\"
                            So the pattern expressions \"vowel'\" and \"#:?n\"
                            are evaluated as normal. }
{!} =a$123

{?} !n
{!} 123                    { This proves that the RHS of the top \"$\"
                            was evaluated. }

{?} (=b$456):(=$((vowel')$(#:?m))) { This fails, proving that the pattern
                            expression \"vowel'\" doesn't recognise the \"b\"
                            in the subject as a vowel. No assignment
                            to variable \"?m\" takes place. }

{?} (=(vowel')$456) : (=$(($(vowel'))$(#:?m))) { This succeeds,
                            because the \"'\" in the pattern expression
                            \"$(vowel')\" is escaped; so the pattern
                            \"$(vowel')\" matches the subject \"vowel'\" }
{!} =(vowel')$456

{?} !m
{!} 456

The escape operator functions with all Bracmat operators, but the
operators |_._|, |_,_|, whitespace, |_+_|, |_*_|, |_^_|, |_\\L_|, and |_\\D_| should not be escaped normally."
    )
  & ( predefmenu
    =   M
      , "Predefined functions"
      , "Besides hard-coded built-in functions, Bracmat offers a number of soft-coded
functions which behave as user defined functions in all respects. They are
redefinable and removable, for example. Some functions are called by the
interpreter itself and should never be changed by the user. Such functions have
names that start with an 8-bit character with the high-bit set. Bracmat has
been drilled to leave these names out when the user asks for a list of variable
names (lst$ or mem$), so you will not notice their existence. The following
visible functions are predefined:

0 |_abs_|
    absolute value
1 |_cat_|
    list existing variable names selectively
2 |_cos_|
    cosine formula
3 |_fct_|
    factorisation
4 |_flt_|
    floating point notation of numbers
5 |_jsn_|
    serialize data to JSON format
6 |_let_|
    decide whether a uncode character is a 'letter'/'mark' or something else
7 |_MLencoding_|
    detect the encoding used in XML or HTML data
8 |_nestML_|
    nest the internal representation of XML or HTML data
9 |_out_|
    output to screen, then new line
10 |_sgn_|
    sign
11 |_sin_|
    sine formula
12 |_sub_|
    substitution
13 |_tay_|
    Taylor series development
14 |_toML_|
    convert an internal representation of XML or HTML to XML resp. HTML"
      ,   (0,sgntxt)
          (1,cattxt)
          (2,gontxt)
          (3,factxt)
          (4,flttxt)
          (5,jsntxt)
          (6,lettxt)
          (7,MLencodingtxt)
          (8,nestMLtxt)
          (9,outtxt debugtxt2 debugtxt3)
          (10,sgntxt)
          (11,gontxt)
          (12,subtxt1)
          (13,taytxt)
          (14,toMLtxt)
    )
  & ( flttxt
    =   T
      , "flt$(<rational-number>,<number-of-decimals>)"
      , "flt$ converts a rational number to a floating point presentation. The result is
stored in an atom and can be used to export results in foreign formats such as
XML, JSON, CSV. Floating point numbers can also be employed in UFP objects.

{?} flt$(123/456,78)
{!} 2.697368421052631578947368421052631578947368421052631578947368421052631578947368E-1
{?} flt$(sub$(tay$(sin$x,x,40).x.11/7),12)
{!} 9.999998001334E-1"
    )
  & ( sgntxt
    =   T
      , "abs$<expression> and sgn$<expression>"
      , "sgn$ determines the sign of the numerical factor of <expression>. If the sign
is |_-_|, then |_sgn_| returns |_-1_|. In all other cases the returned value is 1.

abs$<expression> is defined as |_sgn$<expression>*<expression>_|.

{?} sgn$(-1*i)
{?} abs$(-7*a)"
    )
  & ( cattxt
    =   T
      , "cat$([<include-list>][,[<exclude-list>][,EXT]])"
      , "cat$ is like the built-in function mem$, but offers the possibility to exclude
names that are not in the first parameter and/or to exclude names that are in
the second parameter. The optional third parameter adds information about array
size and current index value, e.g., (arg,5,5). If the first parameter is
missing, this is taken to mean that no names are excluded (unless by virtue of
the second parameter). You can use cat$ to save the state of the variable space
for later use, e.g., removing all variables that have been created since.

{?} cat$(,,EXT):?save-state  { mem$EXT is also OK. }
{?} newvar1=12345            { create new variables }
{?} tbl$(newvar2,100)
{?} cat$(,!save-state,EXT)   { show the newcomers }"
    )
  & ( gontxt
    =   T
      , "cos$<expression> and sin$<expression>"
      , "These functions produce cos(expression) and sin(expression), expressed in
powers of |_e_|. In this way, expressions with goniometric functions can be
differentiated and, sometimes, simplified."
    )
  & ( factxt
    =   T
      , "fct$<expression>"
      , "fct$ uses some heuristics in trying to factorise <expression>.

{?} 1+(2*a^3+6/7*t)*(3*x+4*y+z^-1)+-1:?sum
{!} 18/7*t*x + 24/7*t*y + 6/7*t*z^-1 + 6*a^3*x + 8*a^3*y + 2*a^3*z^-1
{?} fct$!sum
{!} 6/7 * z^-1 * (1+3*x*z+4*y*z) * (t+7/3*a^3)"
    )
  & ( jsntxt
    =   T
      , "jsn$<expression>"
      , "
|_jsn$_| serializes <expression> to JSON format.

Suppose |_mars.json_| contains

    {\"planet\":\"Mars\",
     \"moons\":[\"Deimos\",\"Phobos\"],
     \"Eccentricity\":0.0934}

Read |_mars.json_| into variable |_mars_|:

{?} get$(\"mars.json\",JSN):?mars
{!}     (Eccentricity.934/10000)
      + (moons.,(.Deimos) (.Phobos))
      + (planet..Mars)
    ,

{?} !mars:(?name-value-pairs,)
{!}     (Eccentricity.934/10000)
      + (moons.,(.Deimos) (.Phobos))
      + (planet..Mars)
    ,

Now add the fact that Mars' gravity, compared to the Earth's, is about 3711/9807

{?} !name-value-pairs+(ratio.3711/9807):?name-value-pairs
{!}   (Eccentricity.934/10000)
    + (moons.,(.Deimos) (.Phobos))
    + (planet..Mars)
    + (ratio.3711/9807)

{?} (!name-value-pairs,):?mars
{!}     (Eccentricity.934/10000)
      + (moons.,(.Deimos) (.Phobos))
      + (planet..Mars)
      + (ratio.3711/9807)
    ,

Finally, serialize the new data to JSON
{?} jsn$!mars:?jsonSerialized
{?} out$!jsonSerialized

{\"Eccentricity\":0.0934,\"moons\":[\"Deimos\",\"Phobos\"],\"planet\":\"Mars\",
                                    \"ratio\":0.378403181401040073417}

A full circle update of the JSON file |_mars.json_| with an extra |_ratio_|
field as a single Bracmat expression:

{?} (  get$(\"mars.json\",JSN):(?name-value-pairs,)
    &   put
      $ ( jsn$(!name-value-pairs+(ratio.3711/9807),)
        , \"marsUpdated.json\"
        , NEW
        )
    )

Numbers are, if possible, represented in exact fixed decimal notation.
If rounding is inevitable, numbers are represented in floating point notation
with 21 digits. Numbers that have been read from JSON input are always
considered to be unrounded, and therefore represented in fixed decimal notation
upon writing to JSON.

Objects have their elements sorted.

No attempt is made to make the result look pretty using indentation."
    )
  & ( jsntranstxt
    =   T
      , "Mapping between JSON and Bracmat expressions"
      , "
A JSON object is represented as a sum of dotted pairs as the LHS (left hand
side) of a comma operator, while the RHS must be empty. The original ordering
of members may be lost, as the sum operator sorts its terms. In each dotted
pair, the LHS represents the object member's key while the RHS represents the
object member's value. An empty object is represented as (0,)

A JSON array is a space separated list as the RHS of a comma operator with an
empty string as LHS.

A string is mapped to the atomic RHS of a dot operator, leaving the LHS empty.

Integer numbers map onto themselves. A non integral number is represented in
fixed point notation if there is an exact representation. Otherwise, a floating
point representation with 21 digits is produced.

true, false and null map onto themselves."
    )
  & ( subtxt1
    =   T
      , "sub$(<expression>.<pattern>.<replacement>)"
      , "substitution function
argument 1 : subject
argument 2 : pattern
argument 3 : replacement for subexpressions matched by pattern."
    )
  & ( outtxt
    =   T
      , "out$<expression>"
      , "Uses the built-in function put$ to output <expression> to the output stream
(usually the screen). Output is ended with a new line. Normally, out$ returns
its argument. out$ is a good debugging tool, but put$ is slightly safer, as it
handles failing arguments in the correct way, contrary to out$.
{?} put$a & put$b
ab{!} b

{?} out$a & out$b
    a
    b
{!} b"
    )
  & ( taytxt
    =   T
      , "tay$(<expression>,<variable>,<number-of-terms>)"
      , "A Taylor expansion is applied to <expression>.
The second argument is the independent variable.
The third argument denotes the number of terms, including vanishing terms.

{?} tay$((cos$x)^-1,x,20)"
    )
  & ( MLencodingtxt
    =   T
      , "MLencoding$<internal-expression-of-XML-or-HTML-data>"
      , "This function parses the data for indicators of the used character encoding."
    )
  & ( nestMLtxt
    =   T
      , "nestML$<internal-expression-of-XML-or-HTML-data>"
      , "After reading XML or HTML data, all text and tags are in a flat list.
The function |_nestML_| attempts to match opening and closing tags and creates
a tree structure. This works best for XML data"
    )
  & ( toMLtxt
    =   T
      , "toML$<internal-expression-of-XML-or-HTML-data>"
      , "This function creates a string containing XML or HTML formatted data from an
internal representation of those data. |_toML_| works both with nested and
unnested data. All necessary character conversions are made in PCDATA and
attributes."
    )
  & ( pattxttxt
    =   T
      , "Pattern matching in strings"
      ,   "@(<string> : <pattern>)

Match <string> with <pattern>

Pattern matching in a string of characters (a single atom) is like pattern
matching in a string of atoms. Use the @ to instruct the program to look inside
the atom and use space operators to combine subpatterns. The space operator
does not itself match any characters. To match a space in an atom, use a space
in an atom!"
          "You cannot negate the result of string pattern matching by adding the ~ prefix.

{?} a b:(~@(? b:a %)) {succeeds, ~@ means:`not an atom'}
{!} a b
    S

{?} ~@(a b:a ?)       {succeeds, ~@ means: `not a string match'}
{!} a b
    S

{?} @(a b:a ?)        {illegal, LHS of string match operator must be atomic}
                      {Bracmat exits}

{?} ~@(a:b)           {fails, pattern matching}

    F

{?} @(a:b)            {fails, string pattern matching}

    F

{?} 12/34:@(?x:#?a (~#%@:?y) #?b) {succeeds,}
        { \"?x\" matches the atom \"12/34\", while
         \"#?a (~#%@:?y) #?b\" matches \"12/34\" as a string.}
{!} 12/34
    S
{?} !a
{!} 12
    S
{?} !b
{!} 34
    S

{?} 12:~/@(?x:#%?a #%?b) {succeeds, ~ negates /, not @,
                         so we have a string match.}
{!} 12
    S
{?} !x
{!} 12
    S
{?} !a
{!} 1
    S
{?} !b
{!} 2
    S
"
    )
  & ( pattxt2
    =   T
      , "Matching a number in a string"
      , "In a string match, the % can be used to force characterwise matching if the
subject is a number and the pattern otherwise would have been treated as a
number.
You have to take care with minuses: the patterns %\"-20/5\" and %-20/5 are
different. In %\"-20/5\", the % is superfluous and the pattern matches
characterwise. In %-20/5, the pattern matches |_20/5_| and the minus is ignored!
{?} @(abcd40/10efgh:?a    20/5  ?z) {succeeds, because 4 = 20/5 = 4}
{!} abcd40/10efgh
    S   0,00 sec
{?} !a !z
{!} abcd 0/10efgh
    S   0,00 sec

{?} @(abcd52/13efgh:?a    20/5  ?z) {succeeds, because 52/13 = 20/5 = 4}
{!} abcd52/13efgh
    S   0,00 sec
{?} !a !z
{!} abcd efgh
    S   0,00 sec

{?} @(abcd40/10efgh:?a   %20/5  ?z) {fails}

    F

{?} @(abcd-20/5efgh:?a %\"-20/5\" ?z){succeeds}
{!} abcd-20/5efgh
    S   0,00 sec
{?} !a !z
{!} abcd efgh
    S   0,00 sec

{?} @(abcd-20/5efgh:?a  %-20/5  ?z) {succeeds, a = abcd-}
{!} abcd-20/5efgh
    S   0,00 sec
{?} !a !z
{!} abcd- efgh
    S   0,00 sec

{?} @(abcd-20/5efgh:?a   -20/5  ?z) {succeeds, a = abcd }
{!} abcd-20/5efgh
    S   0,00 sec
{?} !a !z
{!} abcd efgh
    S   0,00 sec
"
    )
  & ( pattxt
    =   T
      , "Binary operators in pattern matching"
      ,   "<subject> : <pattern>

Match <subject> with <pattern>

A match succeeds if <subject> succeeds and <pattern> is successfully matched
with <subject>. The returned value is the left operand, <subject>.

Patterns may be built up from subpatterns and may also include actions that
are triggered if a subpattern successfully matches (part of) the subject.

As with the evaluation of other binary operators, the left operand of the :
operator is evaluated first. The other operand, <pattern>, is not evaluated,
but in the process of pattern matching (parts of) <pattern> may be evaluated
several times. This is the case with function calls, atoms with a |_!_| prefix
and all right hand sides of the |_&_| operator. The use of the involved binary
operators (|_$_|, |_'_| and |_&_|) and prefixes (|_!_| and |_!!_|) as `meta operators' does not restrict
the range of matchable expressions in a serious way, as these operators and
prefixes normally do not occur in evaluated subject expressions. The same is
true for some other operators (|_:_|, |_|_|, |___|, and |_=_|). These operators, too, have a
special meaning within patterns. All other binary operators occurring in a
pattern are searched for in the subject expression as part of the pattern
matching."
          "Especially the |_&_|, |_|_| and |_:_| operators are helpful in formulating complex
patterns with alternatives, conjunctions and side effects in the form of
actions. In the following examples, !s stands for the subject expression,
the expressions in parentheses are patterns and |_!p_|, |_!pa_|, |_!pb_|,
etc., are subpatterns therein. |_!a_|, |_!aa_|, etc., stand for an action
(a part of the pattern that is conditionally evaluated).

    !s:(!p&!a)

If !p matches successfully with !s, then !a is evaluated. If !a
fails, the whole match fails. In more complex patterns, only part
of the match might fail, resulting in backtracking and retry.

    !s:(!pa|!pb)

If pattern !pa does not match with subject !s, then !pb is tried.

    !s:(!pa:!pb)

If pattern !pa matches with !s, then pattern !pb is also tried.

The next example combines these operators in a grammar-like expression:

 !s:( !pa         & !A    { If either !pa, or !pb or both of !pc1 and !pc2 }
    | !pb         & !B    { fire, actions !A, !B and !C, respectively are  }
    | (!pc1:!pc2) & !C    { triggered.                                     }
    )"
          "Notice the grouping of the |_:_|, |_&_| and |_|_| operators :

|_(!s:!pa):!pb_| and |_!s:(!pa:!pb)_| have, incidentally, the same effect, but the
following expressions are very different :

(!s:!p)&!e or !s:!p&!e
    If |_!s_| matches with |_!p_|, |_!e_| is returned.
!s:(!p&!a)
    If |_!s_| matches with |_!p_|, |_!a_| is evaluated, but the expression as a whole
    returns !s.
(!s:!p)|!e or !s:!p|!e
    If |_!s_| matches with |_!p_|, |_!s_| is returned. Otherwise, |_!e_| is returned.
!s:(!pa|!pb)
    If |_!s_| matches with either |_!pa_| or |_!pb_| (in that order), |_!s_| is returned."
          "The possibility that !s might fail further complicates the above examples."
    )
  & ( asstxt
    =   T
      , "Assignment to variables"
      , "There are two forms of assignment to a variable:

<variable> = <expression>
      <expression> is not evaluated before assignment to <variable>.
<expression> : ?<variable>
      <expression> is evaluated before assignment takes place.

The = operator is used to bind (still) unevaluated expressions such as
patterns and functions to variables.

Assignment with the |_:_| makes use of pattern matching with a universally
unifying pattern. This way of assignment is very powerful and can even be
used to assign unevaluated expressions, by preceding the subject with an
= or an ' operator. Example: define Lisp's car-function, first using = and
then using : to bind the function definition to the variable |_car_|.

{?} car=.!arg:(?%arg ?)&!arg          { one may freely reuse arg ! }
{?} (=(.!arg:(?%arg ?)&!arg)):(=?car) { another way to define car }
{?} car$(one two three)
{!} one
{?} (four five six):(?`%first ?rem) {`: 0 of 1, %: 1 or more, together 1}
{?} The first element is !first and the remainder is !rem
{!} The first element is four and the remainder is five six"
    )
  & ( unstuurtxt
    =   T
      , "Prefixes and program flow"
      ,   "Unlike other programming languages, Bracmat does not return the value of a
variable or object member if we type its name. In Bracmat, variables and
object members have to be told explicitly that we want their value, not their
name. This is achieved with the ! and the !! prefixes in front of the variable
name or object member name.

!<atom>
    is replaced by the binding of <atom>
!!<atom>
    is replaced by the binding of the binding (after evaluation) of <atom>

Likewise !(<object-name>.<member-name>) is replaced by the binding
of <object-name>.<member-name>

Bindings can be evaluated or unevaluated. In the last case, the next step after
expansion is the evaluation of the binding, unless expansion took place within
a pattern.

{?} 2+3:?four     { bind 5 to \"four\" }
{?} !four         { evaluation has already taken place when four is expanded }
{!} 5

{?} 5=2+!four     { numbers are legal names. \"5\" is bound to \"2 + !four\"}
{?} !5            { evaluation takes place immediately after expansion }
{!} 7

{?} sum=%+%       { define pattern \"sum\" }
{?} a+b+c:!sum    { is \"a+b+c\" a sum? After expansion, \"%+%\" is not evaluated }
{!} a+b+c
"
          "The !! prefix is not used as often as the single !, but comes in handy if you
want to pass a variable by name instead of by value.

{?} (check=one,two,criterion
      .     !arg:(?one,?criterion,?two)
          & !!criterion
          & TRUE
        | FALSE
    )
{?} is-greater-than = !one:>!two
{?} is-divisor-of = (div$(!two,!one)*!one):!two

{?} check$(3,is-greater-than,15)  { pass by name }
{!} FALSE

{?} check$(3,is-divisor-of,15)
{!} TRUE

Passing by name is used here to postpone the evaluation of the second argument
until it has arrived in the function check and the local variables |_one_| and
|_two_| have been bound to the first and the third arguments, respectively."
          "Postponement of evaluation can also be achieved with the = and the '
operators.

{?} (chack=one,two,criterion
      .    !arg:(?one,(=?criterion),?two)
         & !criterion
         & TRUE
       | FALSE
    )
{?} is-greater-than = = !one:>!two                  { an extra = }
{?} is-divisor-of = '((div$(!two,!one)*!one):!two)  { an extra ' }
{?} chack$(3,!is-greater-than,15)                   { pass by value }
{?} chack$(3,!is-divisor-of,15)"
    )
  & ( debugtxt
    =   T
      , Debugging
      , "If a program written in the Bracmat language doesn't work properly, the
same debugging protocol applies as with other programming languages :

* Test extensively, above all with absurd and trivial input, in order to
  locate the pain in the many limbs of your program code.
* Create watch points by inserting out$ instructions at sensible places
  (entry and exit points of functions, branches, before and after assignments).
* If you are in doubt whether Bracmat has interpreted your program in the way
  you intended, use lst$(<function-name>,<file-name>) and inspect the
  code that is output into <file-name>.
* Errors that are easily made are :
  - Forget that Bracmat may see neutral elements (0 terms, 1 factors, zero
    length words) at places where this is not what you intend. Are all
    % ` and @ prefixes in place?
  - Forget the grouping of operators. For example,
    |_a b c : ?%x ?%y_|  is grouped as |_(a b c):(?%x ?%y)_| , but on the other hand,
    |_a,b,c : ?%x,?%y_|  is grouped as |_a,b,(c:?%x),?%y_|.
    Remember that |_=_| and |_._| have very low priorities, often making a pair of
    parentheses necessary.
  - A misconceived idea about the Bracmat's backtracking mechanism. Unlike
    other languages with backtracking capabilities, Bracmat does not offer
    suspend/resume cycles. An expression embodying alternatives does not
    successively produce each alternative on every evaluation."
    )
  & ( debugtxt2
    =   T
      , "Using out$ as debugging aid"
      ,   "The best aid in finding out what a program does, is using the out$ function.
The following code is part of a function that computes n! .

 (loop = !k+1 : ?k          { increment k }
              : <!n         { compare (old) k+1 with n; if not less, stop }
       & !fac*!k : ?fac     { multiply fac with k }
       & !loop)             { repeat until k = n }

Outside patterns out$ is most easily used. Inside patterns, if you want to
inspect a variable that has just been assigned a new value, you use the &
operator to temporarily escape into the non-pattern world. If you want to add
extra text to the output, remember that the atgument to out$ is returned.

 (loop = out$!k+1 : (?k & out$(k is !k)) {show k before and after
                                          increment}
                  : <!n                  {but before comparison with n}
       & out$(\"new fac is:\" (!fac*!k:?fac)) {show fac after computation}
       & out$(still need !n+-1*!k loops) {you don't always need quotation
                                          marks}
       & !loop)"
          "Now an example that is faulty. The purpose is to find two equal words in a
sentence with a non-linear pattern.
This expression succeeds, but finds nothing:

    (   De kok snijdt recht en de meid snijdt scheef
      : (? ?a ? !a ?)
    & out$(!a is occurring twice)
    )

Check what is unified with |_? ?a_|. To do so, put a variable after the first
|_?_| and insert an output action after each subpattern.

    (   De kok snijdt recht en de meid snijdt scheef
      : ( (?x & out$(x is !x))    {output x after unification}
          (?a & out$(a is !a))    {output a after unification}
          ? !a ?                  {the remainder of the pattern}
        )
    & out$(!a is occurring twice)
    )

The program would have to backtrack several times until ?a was unified with
|_snijdt_|, but the match succeeds with ?a unified with the omnipresent zero
length word. A % sign avoids this. A back quote |_`_| helps speeding up, since it
avoids multi-word assignments and forces immediate backtracking.

    (   De kok snijdt recht en de meid snijdt scheef
      : ( (?x & out$(x is !x))    { Watch the number of words in ?x grow }
          (%`?a & out$(a is !a))  { while ?a moves towards \"snijdt\". }
          ? !a ?                  { There, backtracking stops }
        )
    & out$(!a is occurring twice) { and the message is output. }
    )"
    )
  & ( debugtxt3
    =   T
      , "Using dbg' as debugging aid"
      , "Some programming errors may be found with the built-in |_dbg_| function. The
argument of the |_dbg_| function is evaluated with an internal debugging flag set.
With this flag set, suspicious code is warned against.

It is important that the argument is not evaluated before being passed to the
|_dbg_| function.

The |_dbg_| function is only available if the DEBUGBRACMAT macro is defined as

    #define DEBUGBRACMAT 1

in `bracmat.c'."
    )
  & ( varmattxt
    =   T
      , Literals
      ,   "In Bracmat, symbols have only literal meaning, unless we explicitly state that
we want a symbol to behave like a programming variable. Contrary to most
computer languages, Bracmat evaluates an expression with literals not by
expanding these literals to their associated values (if they have any) and
computing with these values until a result is obtained, but by rearranging
and transforming the expression until a stable form is reached.

{?} a + a
{!} 2*a

{?} i*i
{!} -1

{?} e^(19/2*pi*i)
{!} -i"
          "In Bracmat, the context of a symbol decides whether it is treated as a
variable or as a literal. So it is not necessary to kill a variable in order
to use its symbol as a literal, the two uses live peacefully together.

{?} i=2         { variable i is bound to the literal \"2\" }
{?} !i^2        { the associated value of i is squared }
{!} 4

{?} i^2         { the literal \"i\" (a special one, like \"pi\" and \"e\") is squared }
{!} -1

{?} 7 = prime   { the variable \"7\" is bound to the literal \"prime\"}
{?} 7 is !7     { the symbol \"7\" is used as both a literal and a variable}
{!} 7 is prime"
    )
  & ( varprotxt
    =   T
      , Variables
      , "Variables are represented by <atom>s, but not all <atom>s are variables.
The context of a symbol determines whether it is a variable or not :
1 the left operand of the = operator, unless this operand has zero length.
2 the atom following the ! and !! prefixes
3 within a pattern, a non-zero length atom following the ? prefix
4 the left operand of the $ and ' operators
5 the right operand of the $ operator in macro constructs (e.g., '(1+$a) )."
    )
  & ( alctxt
    =   T
      , "alc$<number-of-bytes>"
      , "This function allocates memory and returns the starting address of the
allocated memory, but crashes the program if not enough memory can be
allocated. Access to memory that has been allocated in this way is by means of
pee$ and pok$. Any allocated memory should at some time be returned to the
memory heap with the function fre$.

{?} alc$1000:?p {allocate 1000 bytes and assign starting address to p}"
    )
  & ( argtxt
    =   T
      , "arg$ or arg$<number>"
      , "If Bracmat is started with any arguments (argc > 1) every argument is
evaluated from left to right, unless arguments are consumed by calls to arg$.
For example,

    bracmat get$myprog -i c:\\documents\\input.txt -o d:\\html\\index.html

would evaluate

    get$myprog
    -i
    c:\\documents\\input.txt
    -o
    d:\\html\\index.html

in that order. Evaluating the last four arguments is not very meaningful,
however: the backslashes are interpreted as escapes, which they are not.
Moreover, the colon and the dot are interpreted as operators. However, the
Bracmat program |_myprog_| can call the function arg$ four times and in that way
empty the queue of arguments. arg$ returns an atom containing an exact copy of
the next program argument. Using string matching the arguments can be parsed,
if necessary.

Precautions must be taken if the path or name of the Bracmat program contains
characters that can be mistakenly interpreted. E.g. (in Windows)

    bracmat \"get$@\\\"c:Program Files\\yourprog.bra\\\"\"

In *N?X the apostrophes surrounding the first argument must be replaced by
quotes.

A second form is arg$N, where 0 <= N < argc. arg$0 will normally return the
command name |_bracmat_| or a path leading to `bracmat'. Here is a simple
program |_myprog_| that demonstrates the two ways of calling the |_arg$_| function

    { myprog }

    (test=
      0:?N
    &   whl
      ' ( arg$:?argument
        & out$(The next argument is !argument)
        )
    &   whl
      ' ( arg$!N:?argument
        & out$(Argument !N is !argument)
        & 1+!N:?N
        )
    );

    !test;

Now running Bracmat with these arguments (example is Windows):

    bracmat get$myprog -i c:\\documents\\input.txt -o d:\\html\\index.html

results in the following output being written to the terminal:

    The next argument is -i
    The next argument is c:documentsinput.txt
    The next argument is -o
    The next argument is d:htmlindex.html
    Argument 0 is bin\\bracmat
    Argument 1 is get$myprog
    Argument 2 is -i
    Argument 3 is c:documentsinput.txt
    Argument 4 is -o
    Argument 5 is d:htmlindex.html"
    )
  & ( asctxt
    =   T
      , "asc$<character>"
      , "asc$ returns the integer value that corresponds to the character according to
the current table used by the operating system (e.g., an extended ASCII table).
{?} asc$\"+\" {return ASCII value of character +}
{!} 43"
    )
  & ( utftxt
    =   T
      , "utf$<UTF-8-character>"
      , "utf$ returns the Unicode code point of the UTF-8 character.
The function fails if the string is too short or too long, or if the sequence
is an invalid UTF-8 string.

It is safe to use utf$ in a pattern:
@(!txt:(?%c & utf$!c) ?)
If the value of |_txt_| starts with a valid UTF-8 sequence, Bracmat backtracks
until the value of |_c_| matches the UTF-8 sequence.
If |_txt_| starts with a sequence that is not UTF-8, Bracmat stops backtracking
when that fact has been established."
    )
  & ( beztxt
    =   T
      , "bez$"
      , "bez$ returns two numbers separated by a dot operator. The first number is the
number of currently allocated binary nodes and leafs. The second number is the
maximum number of allocated binary nodes and leafs in this session, until now.
These numbers are not of much use, except for controlling that there are no
memory leaks. The function bez$ can be turned off by setting |_TELMAX_| to zero
in `bracmat.c' before compilation.

In interactive mode, with TELMAX set to one, Bracmat shows
(1) whether the evaluation was successful or not, (2) the amount of CPU time
and (3) the result of calling bez$ after each non-empty evaluation result.

{?} 2^10000+-1*3^100000*5^-10000
{!} -13349714142304014694589143904897822922452485076062773553456279939
...55869676383936027544370832840538165786625768305384553968906402587890625
    S   0,28 sec
"
    )
  & ( chrtxt
    =   T
      , "chr$<value>"
      , "chr$ returns the character at location <value> in the current table of
characters used by the operating system. (e.g., an extended ASCII table).
chr$ fails if <value> equals 0.
{?} chr$255 {return the last character from the current table of characters
             (assuming a machine with 8-bit characters)}
{?} ( tolower=.
        !arg:~<A:~>Z                  {If arg is in the range A-Z,}
      & chr$(asc$!arg+-1*asc$A+asc$a) {then return its lower case equivalent,}
    | !arg                            {else return arg unchanged.}
    ) {(Works only correctly if the `distance' between lower and upper case
        versions is the same for all characters in the range A-Z.)}
{?} tolower$G"
    )
  & ( chutxt
    =   T
      , "chu$<value>"
      , "chu$ returns the UTF-8 character at Unicode code point <value>.
chu$ fails if <value> equals 0 or less or if <value> exceeds 2147483647
(7FFFFFFF). According to the UTF-8 standard values above 1114111 (10FFFF)
are illegal.
{?} d2x$utf$chu$x2d$7fffffff
{!} 7FFFFFFF"
    )
  & ( clktxt
    =   T
      , "clk$"
      , "clk$ returns the number of CPU seconds that that has been spend on running the
current session of Bracmat. The number is an unreduced quotient of number of
clock ticks and the number of clock ticks per second.
{?} clk$
{!} 30375/1000"
    )
  & ( d2xtxt
    =   T
      , "d2x$<decimal-value>"
      , "d2x$ converts a decimal number between 0 and 4294967295 (2^32+-1) to an
hexadecimal number consisting of characters 0-9 and A-F. On 64-bit platforms
the upper bound is 18446744073709551615 (2^64+-1). The function fails if the
argument is not an integer number or if the number is outside this range.
{?} d2x$(2^32+-1)"
    )
  & ( x2dtxt
    =   T
      , "x2d$<hexadecimal-value>"
      , "x2d$ converts an hexadecimal number between 0 and FFFFFFFF to a decimal
number. On 64-bit platforms the upper bound is FFFFFFFFFFFFFFFF.
The function fails if the argument is not a string with a length
between 1 and 8 only containing the characters 0-9, a-f and A-F.
{?} x2d$ffffffff
{!} 4294967295"
    )
  & ( dbgtxt
    =   T
      , "|_dbg'<expression>_|"
      , "Create warnings in situations that probably are programming errors.
Currently, a warning is generated when a function definition can not be found.

{?} dbg'(foo$a)
{?} dbg'((myclass.yourfunc)$X)"
    )
  & ( dentxt
    =   T
      , "den$<rational-number>"
      , "The denominator of <rational-number> is returned. There is no built-in
numerator extractor function.

{?} den$22/7
{!} 7

{?} num = .!arg*den$!arg { home-made numerator function }
{?} num$22/7
{!} 22

{?} den$sim$(,monkey)   { return length of word \"monkey\"}
{!} 6"
    )
  & ( divtxt
    =   T
      , "div$(<rational-number>,<rational-number>)"
      , "div$ returns the (integral) quotient of its arguments.

{?} div$(123/45,67/890)
{!} 36"
    )
  & ( fretxt
    =   T
      , "fre$<memory-address>"
      , "fre$ returns a chunk of memory to the memory pool (heap). The only valid
parameter is a return value of alc$. Applying fre$ to a chunk of memory that
was never allocated or that has been returned already results in undefined
behaviour of the program.

{?} alc$1000:?p {allocate chunk of 1000 bytes from the memory pool}
{?} fre$!p      {return this chunk to the memory pool}"
    )
  & ( funtxt1
    =   T
      , "Definition of a function"
      , "<function-name>=<var1> [,<var2>, ...].<function-body>

<var1>,<var2>, etc. are explicitly declared local variables.

A function is
called by <function-name>$<argument-expression>
or |_<function-name>'<argument-expression>_| ,
depending on whether <argument-expression> must be evaluated ($)
or not |_(')_|.

All Bracmat functions have arity one or two, that is, they accept one or two
arguments. The |_<argument-expression>_| to the right of the ($) or |_(')_|
is always represented in the body of the function by a local variable |_arg_|.

The returned value of a function is simply the function body after it
has been evaluated.

{?} square=.!arg^2          {definition}
{?} square$5                {call}
{!} 25

{?} (swap = a,b             {declare local variables a and b}
        .   (!arg:(?a,?b))  {dissect arg to find the real arguments}
         & (!b,!a))         {swap and return}
{?} swap$(I think,I guess)
{!} I guess,I think

In a match context, a function call creates a second local variable,
|_sjt_| (think SuJeT, SubJecT), the current subject. The value returned from
a function in a match context is interpreted as a pattern by the match
evaluator. However, if the function call fails, the pattern match operation
is not attempted and fails as well. The behaviour is not defined if the
returned value is negated.

{?} ( like
    =
      .   sim$(!arg,!sjt):>9/10 & ?
        |   den$(sim$(!sjt,)):~<(den$(sim$(!arg,0)))
          & ~`
    )
{?} @( \"Dogs and Cats are my enemies\": ? like$cat ?)

Local variables in Bracmat are shallowly bound dynamically scoped variables.
This means that variables that are used in a function but not locally declared
in that function, are inherited from the (function or global) context from
which the function is called, which in turn may inherit any undeclared
variables from another calling context. This scheme contrasts with most
programming languages. It is efficient, but the effect of forgetting to
declare a local variable can be unexpected behaviour of conceptually unrelated
code.

It is possible to declare a function inside another function. Always declare
the name of an embedded function as a local variable."
    )
  & ( funtxt3
    =   T
      , "Recursion and the |___| operator"
      , "In Bracmat functions are allowed to call themselves. Often this happens
if a function's argument is split into a left subtree and a right
subtree and the function is called with each subtree in turn as its argument.
If the operator between the subtrees is unknown, it is time consuming
to try all patterns |_?+? ?*? ?$? ?'?_| etc. The |___| operator circumvents this
problem. It is a dummy operator that matches any other operator and
expands to the operator with which it matched last time. Thereby preceding
matches are forgotten : the |___| operator is a global variable.
{?} ( reverse
    =   l,r
      .     (!arg:?l_?r)              { If arg is a compound expression, }
          & (reverse$!r)_(reverse$!l) { then swap the reversed operands. }
        | !arg                        { Let atoms stay as they are. }
    )
{?} reverse$(Bill loves sweet Nancy. This is true)
{!} true is This.Nancy sweet loves Bill"
    )
  & ( lsttxt1
    =   T
      , "lst$(<(=expression) or variable>*[,LIN][,RAW][,WYD])"
      , "|_lst$_| outputs all present bindings of one or more variables to standard
output. If a variable is local to a function and a variable of the same name
already exists in the context of another function invocation or globally, all
instances will be listed!

If a variable is listed to stdout, the listing starts with |_(varname=_| and
ends with |_);_|. The surrounding parentheses are suppressed if a variable is
listed to a file.

Expressions headed by the |_=_| operator can be used instead of
variable names. In that case no semicolon is appended. The listing starts
with  |_(=_| and ends with |_)_|, followed by a newline.

With the |_RAW_| option, only the expression right of the |_=_| operator is
listed.

The LIN option suppresses most newlines and all other unneeded whitespace characters.

The WYD option makes lines wider. That is especially useful if your code is
deeply nested. This option has no effect if the LIN option is provided as well.


If the first parameter is the zero-length string, then all variables with
names starting with a character below ASCII 128 are shown. If a variable
has more than one binding (arrays/stacks) then the current value is preceded
by a |_>_| sign.
The second parameter is optional.

{?} lst$help      { shows this programme on screen,
                    unless stdout has been redirected }
{?} lst$(tay,LIN) { listing without indentations of function tay$ }"
    )
  & ( lsttxt2
    =   T
      , "lst$(<(=expression) or variable>*,MEM [,LIN][,RAW][,WYD])"
      , "The difference with the preceding form is that output takes place to
memory. What is normally visible on screen is put in one atom, which is
the return value of the call to lst. It has the opposite effect of
get$(<atom>,MEM). In theory one can save some memory by writing an expression
to a single leaf node, because each node in an expression has some memory
overhead. In practice the saving can be quite small or non-existent, because
Bracmat expressions often share part of their data structures with other
expressions.

Example:

{?} lst$(fct,MEM):?sleeping-fct
{?} tbl$(fct,0)   { remove function fct$ from memory }
{?} { .. celebrate space-saving, until fct$ is needed .. }
{?} get$(!sleeping-fct,MEM)"
    )
  & ( lsttxt3
    =   T
      , "|_lst$(<(=expression) or variable>*,<file-name>,NEW | APP [,LIN][,TXT][,BIN][,WYD])_|"
      , "This time, output is sent to the named file instead of standard output.
The third argument is explained below.
Code that has been saved with lst$ can be reloaded with get$.

{?} lst$(,\"all\",NEW,LIN)
    { write all current code without indentations to file \"all\" }
{?} lst$(tay,taylor,NEW)
    { save function \"tay\" to file \"taylor\" in indented format }"
    )
  & ( maptxt
    =   T
      , "map$(<fnc>.<list>)"
      ,   "map$ produces a list containing the results of applying <fnc> to each member
in <list>. <fnc> can be the name of a function, a function definition
(`anonymous function') or a lambda abstraction. <fnc> can also be the name of
a built-in function. (See the first example.) It is not necessary to specify a
mapping function at all. An empty string instead of a function name or function
definition has the effect of passing the the input to the output, unchanged.

The members in <list> must be
separated by the space operator.
{?} map$(rev.aap noot mies)
{!} paa toon seim
{?} map$(/('(x.$x^2)).1 2 3 4)
{!} 1 4 9 16
{?} map$((=.!arg^2).1 2 3 4)
{!} 1 4 9 16
{?} (square=.!arg^2)&map$(square.1 2 3 4)
{!} 1 4 9 16"
          "{?} (  map
    $ ( (
        =   x
          .     !arg:?*?^%?x*?*?^!x*?
              & (!arg.\"same exponent\" !x)
            | (!arg.)
        )
      . a*b^3*c^2 d*f^3*g^2*h*j^3 o*p
      )
    )
{!} (a*b^3*c^2.)
    (d*f^3*g^2*h*j^3.same exponent 3)
    (o*p.)"
    )
  & ( moptxt
    =   T
      , "mop$(<fnc>.<expression>.(=<non-leaf expression>)) or mop$(<fnc>.<expression>.(=<non-leaf expression>).(=<non-leaf expression>))"
      , "mop$ traverses a list-like expression element by element and outputs a space
operator separated list. For that to work, mop$ needs an extra argument that
tells which operator to use. That argument is always headed by |_=_|, the
right hand side of which is a non-leaf expression. The top operator of that
expression is used as the separating operator.
{?} mop$((=.!arg).aap+noot+mies.(=+))
{!} aap mies noot
{?} (x=2*a+i*b+e\\Lc) & mop$((=.!arg).!x.()'($x))
{!} 2*a e\\Lc i*b
{?} mop$((=.!arg)..(=*))
{!}

It is possible to have a list with space operators as separating operator:

{?} mop'((=.!arg).a b c.(=x y))
{!} a b c

Another way to do this is to use the map$ function

{?} map'((=.!arg).a b c)
{!} a b c

The second form creates a list with a separator operator of your choice.

If the output separator is |_+_| or |_*_|, the output is sorted using the
merge sort algorithm.

{?} (a.b)+(c.d)+(e.a):?s

{?} mop$((=.!arg:(?.?arg)&!arg).!s.(=+).(=,))
{!} b,d,a

{?} mop$((=.!arg:(?.?arg)&!arg).!s.(=+).(=*))
{!} a*b*d

It is not necessary to specify a mapping function. An empty string instead of
a function name or function definition has the effect of passing the elements
in the input to the output without any changes.
"
    )
  & ( vaptxt
    =   T
      , "vap$(<fnc>.<string>) or vap$(<fnc>.<string>.<separator>)"
      , "The version without specified separator splits the string in a list of
characters and applies fnc$ to each character. vap$ checks whether the string
is valid UTF-8 before splitting the string. If not, it splits the string in
8-byte characters, even if some substrings could be interpreted as valid UTF-8.

The version with a specified separator splits the string at each occurrence
of the separator. The separator can be any non-zero length string. The
separator does not become part of the output. This version is especially
useful for reading CSV files and tab-separated files. Note that, if the last
character of the input string is a separator, the last call to fnc$ is with
a zero-length string. This will often happen if a newline character terminates
every line in the input string and the newline character is specified as a
separator.

It is not necessary to specify a mapping function. An empty string instead of
a function name or function definition has the effect of passing the characters
in the input to the output.
"
    )
  & ( memtxt
    =   T
      , "mem$[EXT]"
      , "mem$ produces a list of all currently existing variables, except those
beginning with a character above ASCII 126. The |_EXT_| option adds information
about the number of occurrences (array or stack size - 1) of those variables
which have more than one occurrence and shows which of them is currently in
focus (index into array: 0 .. size-1).
The predefined function cat$ makes use of mem$.
{?} mem$
{?} mem$EXT"
    )
  & ( newtxt
    =   T
      , "options |_NEW_|, |_APP_|, |_TXT_| and |_BIN_|"
      , "One of the options |_NEW_| and |_APP_| must be present:

|_NEW_|
    Tells the computer to open a new file or overwrite an old one.
|_APP_|
    Directs output to an existing file. If the file does not exist, it is
    created first.

Options |_TXT_| and |_BIN_| overrule the default file mode of the functions
|_put_| and |_lst_|.

|_TXT_|
    Tells Bracmat to write a file in text mode. This is the default file mode
    for |_put_|. In Windows, each line feed character will be preceded by a
    carriage return. In Unix and Linux, text mode and binary mode are the same.
|_BIN_|
    Tells Bracmat to write a file in binary mode. This is the default file mode
    for |_lst_|."
    )
  & ( humtxt
    =   T
      , "option |_LIN_|"
      , "
If |_LIN_| is not present, output is very much indented, sometimes making it more
readable for humans. If |_LIN_| is present, output is as compact as possible."
    )
  & ( modtxt
    =   T
      , "mod$(<number>,<divisor>)"
      , "mod$ divides <number> by <divisor>. The remainder is returned.

{?} mod$(22,7)
{!} 1"
    )
  & ( newobjecttxt
    =   T
      , "new$<object> or new$(<object>,<args>)"
      ,   "new$ creates a shallow copy of an object and calls the method |_new_| of the
new object, if there is one. With the second form, <args> is passed to the
method |_new_|. Example:

{?} (patient=
  (name=(first=John),(last=Bull)) {name is a copy, first and last are not}
  , (age=20)
  , ( new
    =
      .   out$\"hello world\"
        & new$(its.name):(=?(its.name)) {create fresh copies of first and last}
        &   !arg
          : (?(its.name.first).?(its.name.last).?(its.age))
  ))
{?} new$(patient,(Albert.Keinstein.42)):?x
{?} new$(patient.name):(?Name)
{?} Alice:?(Name..first)
{?} new$(('$patient),(Albert.Keinstein.42)):?y {x and y are identical !}
{?} new$(=(a=1),(b=2)):?ab {\"die\" is called when \"ab\" is reassigned}
{?} 3:?(ab..a)
{?} new$(=(a=1),(b=2),(new=.),(die=.)):(=?cd) {\"die\" is called at once!}
{?} 3:?(cd.a)"
          "When an object was created with the new$ function, an internal flag is set in
the object telling the system that the |_die_| method must be called just
before deletion of the object. The |_die_| method, like the |_new_| method, is
optional and should be used to do clean-up."
    )
  & ( aligntxt
    = "
2 and 4 byte integers may only start at addresses that are multiples of 2 and
4, respectively. <address> is lowered to the nearest allowable value, if
needed. Notice that multi-byte integers are stored differently in little-endian
(iAPx86, VAX, ARM) and big-endian (MC680x0) machines. Many operating systems
abort programs that try to access non-existent or protected memory areas."
    )
  & ( peetxt
    =   T
      , "pee$(<address> [,<size>])"
      ,   "Depending on <size>, a 1, 2 or 4 byte sized integer allocated at <address> is
returned."
          !aligntxt
          "{?} chr$pee$34567  {return value at address 34567 (1 byte) as a character}
{?} pee$(34567,2)  {return value at address 34566 (2 bytes)}
{?} pee$(34567,4)  {return value at address 34564 (4 bytes)}"
    )
  & ( poktxt
    =   T
      , "pok$(<address>,<value> [,<size>])"
      ,   "Depending on <size>, a 1, 2 or 4 byte sized integer is stored at <address>."
          !aligntxt
          "{?} pok$(34567,asc$K) {store the internal value of the character K at memory
                      location 34567 (as 1 byte)}
{?} pok$(34567,-1,4)  {store 2^32-1 at memory location 34564
                      (assuming 1-complement arithmetic)}"
    )
  & ( puttxt1
    =   T
      , "put$(<expression>[,LIN][,WYD])"
      , "Sends <expression> to standard output. The cursor is positioned after the
last output character. The predefined function out$ does the same as put$,
with the exception that it positions the cursor on the beginning of the next
line.

{?} put$(\"b+a\" is after evaluation b+a)"
    )
  & ( puttxt2
    =   T
      , "put$(<expression>,MEM [,LIN][,WYD])"
      , "<expression> is stringified and placed into an atom, which is the return
value of the call. This use of put$ is similar to the str$ function, but
whereas str$ suppresses the space operator, put$ transfers every character,
including space operators, to the atom.

{?} put$(this is not Lotus 1 1+1 1+1+1,MEM):?proposition &
{?} !proposition
{!} this is not Lotus 1 2 3
"
    )
  & ( puttxt3
    =   T
      , "|_put$(<expression>,<file-name>,NEW | APP [,LIN][,WYD])_|"
      , "Write <expression> to the named file.

{?} put$(tay$(e^x,x,10),\"e.out\",APP)"
    )
  & ( simtxt
    =   T
      , "sim$(<atom-or-nil>,<atom-or-nil>)"
      , "sim$ uses the Ratcliff/Obershelp pattern matching algorithm in establishing
a measure of the similarity between its two (atomic) arguments. The returned
value is an unsimplified fraction. The denominator is the sum of the numbers
of characters in both arguments. The numerator is the total number of
characters that have been matched successfully. Matching is case-insensitive.
This applies to the full Unicode table, but defaults to ASCII and the upper
128 characters in the ISO8859-1 (Latin 1) character set if the characters are
not UTF-8 encoded.

{?} sim$(colour,Color)
{!} 10/11

{?} den$sim$(,\"this is an easy way to find this string's length\")
{!} 48

{?} div$(sim$(\"similarity rounded\",\"and in procents\")+1/200,1/100)
{!} 30"
    )
  & ( seltxt
    =   T
      , "<index>$<array-name>"
      , "Both <array-name> and <index> should evaluate to atoms. <array-name> may be
preceded by prefixes, such as ? or !. Indexing starts at 0 and is done
modulo(size-of-array). Negative values count from the upper end of the array.
The chosen index remains in force until a new indexing function is evaluated.

{?} tbl$(array,4)              { declare array[0..3] }
{?} a-value : 2 $ ?array       { array[2] := a-value }
{?} array = another-value      { array[2] := another-value }
{?} !array : -1 $ ?array       { array[3] := another-value }
{?} 45 : 1$?array              { array[1] := 45 }
{?} 2'!array : 3'!array       { are array[2] and array[3] equal?
                                 Notice use of ' instead of $. }"
    )
  & ( strtxt
    =   T
      , "str$<expression>"
      , "str$ writes <expression> into one single atom. All atoms, prefixes and
operators, with the exception of the space operator, are copied to the
output string. Main use : pasting of two or more atoms.

{?} n=3
{?} str$(var !n) = seventeen
{?} out$(var3 is !var3)
{?} editfile = mytxts/story
{?} sys$str$(\"vi \" !editfile)   { execute UNIX command \"vi mytxts/story\" }
{?} a=x+2*y;b=2*x+y
{?} put$str$(!a \"+\" !b \" = \" !a+!b)"
    )
  & ( switxt
    =   T
      , "swi$(<interrupt-number>.<input-value>,[<input-value>,...])"
      , "This function is the most operating-system-dependent function in Bracmat.
It was implemented for RISC-OS (Archimedes) and 16-bit MS-DOS versions.
All arguments must be integer values. The list of input values (registers
r0 and upwards) need not be complete. Missing values are assumed to be zero.
Blocks of memory should be passed by allocating memory with |_alc$_| and
passing the returned value. The returned value has the form

(<error code>.<output-value>,<output-value>,...)

An error code of 0 means that no error is reported.
In the MS-DOS version, the input registers are AX,BX,CX,DX,BP,SI,DI,DS,ES and
FLAGS, respectively.

RISC-OS only:

{?} ( putstr                    { goal:copy argument to memoryblock }
    =   ( loop,c,buf,ret
        .     alc$(den$(sim$(!arg,))+1) { allocate block for string to fit }
            : ?buf
            : ?ret
          & get$(!arg,MEM,VAP):?arg { argument -> single characters }
          & ( loop
            =   !arg:%?c ?arg
              & pok$(!buf.asc$!c.1)
              & !buf+1:?buf
              & !loop
            )
          & ~!loop              { poke each character into memory block }
          & pok$(!buf.0.1)      { poke string-delimiting zero }
          & !ret                { return pointer to block }
        )
{?} putstr$\"OS_EvaluateExpression\":?inbuf { create pointer to string }
{?} 57:?\"OS_SWINumberFromString\" { From manual }
{?} swi$(!\"OS_SWINumberFromString\".0,!inbuf): (?error.?nummer,?)
                                { find interrupt number corresponding
                                 to the string \"OS_EvaluateExpression\"}
{?} fre$!inbuf                  { deallocate block containing copy
                                 of input string }

MS-DOS only:

{?} ( gotoxy
    =   VIDEO,setCursorPosition,videoPage0
      .   16:?VIDEO                 { interrupt number 10H }
        & 2*256:?setCursorPosition  { AH }
        & 0*256:?videoPage0         { BH }
        & !arg:(?x,?y)              { DL and DH }
        &   swi
          $ (!VIDEO.!setCursorPosition,!videoPage0,0,!x+256*!y)
    )
"
    )
  & ( rentxt
    =   T
      , "ren$(<oldname>.<newname>)"
      , "Renames a file or directory or moves a file.
The ren$ function succeeds unless a syntactic error was made. If there is an
error at the operating system level, one of the following codes is returned:

|_EACCES_|
    File or directory specified by newname already exists or could not be
    created (invalid path); or oldname is a directory and newname specifies
    a different path.
|_ENOENT_|
    File or path specified by oldname not found.
|_EINVAL_|
    Name contains invalid characters.

If the command succeeds at the operating system level, the value 0 is returned."
    )
  & ( rmvtxt
    =   T
      , "rmv$<file-name>"
      , "Removes a file.
The rmv$ function succeeds, unless a syntactic error was made. If there is an
error at the operating system level, one of the following codes is returned:

|_EACCES_|
    Indicates that the path specifies a read-only file or that the file
    is open.
|_ENOENT_|
    Indicates that the filename or path was not found or that the path
    specifies a directory.
|_EINVAL_|
    Name contains invalid characters.

If the command succeeds at the operating system level, the value 0 is returned."
    )
  & ( revtxt
    =   T
      , "rev$<atom>"
      , "Reverses the order of bytes in an atom. This function can be useful in case of
a string match that asks for the last occurrence of a pattern.

The rev$ function succeeds on all atoms and fails on all other expressions."
    )
  & ( systxt
    =   T
      , "sys$<command-line-command>"
      ,   "In most environments, sys$ passes its argument to the command line
interpreter. Therefore, sys$ has a functionality that very much depends on
the operating system in which Bracmat runs. One has to take care for
memory limitations and the possibility that sys$ may never return.
Possible uses are for example :

* instructions to the video display unit for cursor movement or graphics
* running another program, such as an editor
* manipulation of files (directory listing, copying, etc.)

The functions put$(<expression>,MEM) or str$<expression> may be used for
constructing an argument for sys$ :
{?} file = bracmat.c
{?} !file:((?stem.?)|?stem) {remove file extension and put result in \"stem\"}
{?} sys$str$(\"copy \" !file \" \" !stem.bak)"
          "The sys$ function succeeds, unless a syntactic error was made. If there is an
error at the operating system level, one of the following codes is returned:

|_E2BIG_|
    Argument list (which is system-dependent) is too big.
|_ENOENT_|
    Command interpreter cannot be found.
|_ENOEXEC_|
    Command interpreter file has invalid format and is not executable.
|_ENOMEM_|
    Not enough memory is available to execute command; or available memory
    has been corrupted; or invalid block exists, indicating that process
    making call was not allocated properly.

If the command succeeds at the operating system level, the value 0 is returned."
    )
  & ( tbltxt
    =   T
      , "tbl$(<variable>,<array-size>)"
      , "The named variable is (re-)sized to an array with <array-size> elements.
Resizing always affects the elements with the highest indexes first :
shrinking means that the last elements are lost, expanding creates new
zero-valued elements at the end.

If <array-size> equals zero, the named variable ceases to exist in memory.
This is the only way in Bracmat to get rid of global variables.

Stacks and arrays are exactly the same thing in Bracmat. Therefore, it is not
possible to declare arrays locally.

Bracmat never accesses arrays as a whole; there is always just one element that
is in focus. By issuing an instruction of the form <index>$<array-name> or
|_<index>'<array-name>_| you can explicitly tell Bracmat to put focus on some
element. Bracmat does this automatically in the case of pushing and popping
local variables onto and from a stack.

{?} tbl$(bigarray,16000)
{?} lst$bigarray          { this may take a long time to execute }
{?} tbl$(bigarray,0)      { remove bigarray }
{?} lst$bigarray"
    )
  & ( flgtxt
    =   T
      , "flg$(=<expression>)"
      , "
|_flg_| returns a copy of the expression without prefixes (`flags') and a new
leaf with the prefixes of the original expression. These two results are
coupled with a dot operator, the prefixes to the left and the expression without
prefixes to the right. The result is protected against evaluation by a '='
operator.

{?} flg$(=~#<>?%@a)
{!} (=~#<>%@?).a

Use macro evaluation if the expression to be split is the value of a variable:

{?} X=~(%+%)
{!} X
{?} flg$('$X):(=?prefixes.?expr)
{!} =~.%+%
{?} glf$('($prefixes.%*%))
{!} =~(%*%)
"
    )
  & ( glftxt
    =   T
      , "glf$(=<prefixes>.<expression>)"
      , "
glf returns a copy of <expression> with <prefixes> added to its prefixes.
If <expression> has one or more prefixes also present in <prefixes>, then glf
fails. Therefore, glf can be used to test for the presence of one or more
prefixes. The result is protected against evaluation by a = operator.
The function glf has an effect that is the opposite of flg.

{?} glf$flg$(=?a)
{!} =?a

Use macro evaluation if the expression to be split is the value of a variable.

{?} X=?!x
{!} X
{?} flg$('$X):(=?prefixes.?expr)
{!} =?!.x
{?} glf$('($prefixes.z))
{!} =?!z
"
    )
  & ( errtxt
    =   T
      , "  err$<destination>   "
      , "Send error messages to destination.

<destination> is one of the following:

|_stderr_|
    Send error messages to the standard error stream. 
|_stdout_|
    Send error messages to the standard output stream. 
|_0_|
    Send error messages nowhere.
<filename>
    Send error messages to the specified file. Error messages are sent to the
    standard error stream if the specified file cannot be opened."
    )
  & ( filtxt
    =   M
      , "fil$([[<file-name>][,<option>[,<number>[,<value-to-output>]]]])"
      , "fil$ is a multi-purpose low level I/O function.

1 |_fil$([<file-name>],<mode>)_|
    Set file mode, open a file in a file mode
2 |_fil$([<file-name>],<type>,<size>[,<number>])_|
    Prepare for reading or writing fixed sized records
3 |_fil$([<file-name>],STR[,<stop>])_|
    Prepare for reading or writing variable sized record
4 |_fil$(<file-name>,TEL)_|
    Tell position inside file
5 |_fil$(<file-name>,<whence>,<offset>)_|
    Go to file position
6 |_fil$([<file-name>][,,<number>])_|
    Read from file
7 |_fil$([<file-name>],,<number>,<value>)_|
    Write to file
8 |_fil$([<file-name>],SET,-1)_|
    Close  a file"
      ,   (1,modetxt)
          (2,fixdtxt)
          (3,varitxt)
          (4,positiontxt)
          (5,filesettxt)
          (6,readtxt)
          (7,writetxt)
          (8,closetxt)
    )
  & ( modetxt
    =   T
      , "  fil$([<file-name>],<mode>)  "
      , "Set file mode, open file in file mode.

Option <mode> is one of the following:

|_r_|
    open text file for reading
|_w_|
    create text file for writing, or truncate to zero length
|_a_|
    append; open text file or create for writing at EOF
|_rb_|
    open binary file for reading
|_wb_|
    create binary file for writing, or truncate to zero length
|_ab_|
    append; open binary file or create for writing at EOF
|_\"r+\"_|
    open text file for update (reading and writing)
|_\"w+\"_|
    create text file for update, or truncate to zero length
|_\"a+\"_|
    append; open text file or create for update, writing at EOF
|_\"r+b\"_| or |_\"rb+\"_|
    open binary file for update (reading and writing)
|_\"w+b\"_| or |_\"wb+\"_|
    create binary file for update, or truncate to zero length
|_\"a+b\"_| or |_\"ab+\"_|
    append; open binary file or create for update, writing at EOF
"
    )
  & ( fixdtxt
    =   T
      , "  fil$([<file-name>],<type>,<size>[,<number>])  "
      , "Prepare for reading or writing fixed sized records.

Option <type> is one of the following :

|_CHR_|
    character or string I/O
|_DEC_|
    number I/O

Option <size> must be a non-negative integer and determines the number of
bytes that are read or written as one chunk during a future call to fil$.
If <type> is |_DEC_|, only values 1,2 and 4 are valid, corresponding to 1, 2
and 4 byte sized integers, respectively. Notice that 2 and 4 byte integers are
not portable between implementations with different byte order. The optional
<number> tells how many read or write operations of size <size> have to be
performed. If <type> is |_DEC_|, the product of <size> and <number> may not be
greater than 4. If a number is read or written in 2 or more chunks, the least
significant bytes or 16 bit words are read or written first (little-endian)."
    )
  & ( varitxt
    =   T
      , "  fil$([<file-name>],STR[,<stop>])  "
      , "Prepare for reading or writing variable sized record

Option <stop> is a string of characters. If the read character or the character
to be written is equal to one of the characters in the stop string, reading or
writing stops. The default is not to stop until the end of the file (reading)
or the end of the string (writing)."
    )
  & ( positiontxt
    =   T
      , "  fil$(<file-name>,TEL)  "
      , "Tell the position inside the file.

Returns the current value of the file position indicator."
    )
  & ( filesettxt
    =   T
      , "  fil$(<file-name>,<whence>,<offset>)  "
      , "Go to file position.

Sets the current value of the file position indicator to an <offset> based
on the value of <whence>.

Option <whence> is one of the following:

|_SET_|
    start of file
|_CUR_|
    current file position
|_END_|
    end of file.
    (In some implementations, binary files may not handle END.)

For a text file, <offset> must be 0, or the value returned from a call to
fil$(<file-name>,TEL), in which case <whence> must be SET."
    )
  & ( readtxt
    =   T
      , "  fil$([<file-name>][,,<number>])  "
      , "Reading from a file.

Reads (if <mode> permitting) <number> chunks of <size> bytes.
When reading variable sized records (|_STR_|), fil$ returns a dot-separated list
of two elements: the found stop character and the read string (which does not
contain the stop character).

{?} fil$(\"mytext.txt\",\"rb\") { Open for reading in binary mode. }
{?} fil$(,STR)              { Prepare for reading until the next 0-byte.}
{?} fil$:(?line.?stop)      { Read until the next 0-byte. }
{?} fil$(,SET,-1)           { Close the file. }

{?} fil$(\"mytext.txt\",\"rb\") { Open for reading in binary mode. }
{?} fil$(,STR,\"\\n \\t\\r\")    { Prepare for reading until the next whitespace.}
{?} :?words                 { Accumulate all words in this variable }
{?} whl'(fil$:(?word.?stop)&!word !words:?words)&   { Read all words. }
{?} fil$(,SET,-1)           { Close the file. }
{?} !words                  { Show all words, in reversed order. }"
    )
  & ( writetxt
    =   T
      , "  fil$([<file-name>],,<number>,<value>)  "
      , "Write to a file

writes (if <mode> permitting) <number> chunks of <size> bytes from <value>.
If <type> is |_DEC_|, <number>*<size> must be 1,2,3 or 4. <value> must be an
integer value and is cast to a binary number with at most <number>*<size>*8
bits. This number is stored in <number>*<size> bytes, which in turn are output.
If <number> is greater than 1, the byte(s) with the least significant digits
are output first. In machines with little-endian byte-order, only the
product <number>*<size> matters.
If <type> is |_CHR_| and the length of <value> is shorter than <number>*<size>,
<value> is padded with spaces (to the right). If <type> is |_STR_|, <number>
must be the empty string"
    )
  & ( closetxt
    =   T
      , "  fil$([<file-name>],SET,-1)  "
      , "Close a file.

An open file is closed by specifying an impossible file position."
    )
  & ( predvartxt
    =   T
      , "Predefined variables"
      , "There are three variables that are predefined, but that in no way are preserved
by Bracmat.

{?} !w

This returns article 11 of the GNU General Public License, Version 2.

{?} !c

This returns article 12 of the GNU General Public License, Version 2.

{?} !v

This returns the current version number and build date of Bracmat.
"
    )
  & ( show
    =   fnc,df,ex
      .   !arg:(?fnc.?df.?ex)
        & tbl$(!fnc,1)
        & '$df:(=?!fnc)
        & put'"{?} "
        & lst$!fnc
        & put'"{?} "
        & put$!ex
        & get'
        & get$(!ex,MEM):?arg
        & tbl$(!fnc,-1)
        & put'"{!} "
        & !arg
    )
  & ( streep
    =   len,"-","--"
      .   den$(sim$(,!arg)):?len
        & ( "--"
          =   !len+-7:>-1:?len
            & put$"-------"
            & !"--"
          )
        & ( "-"
          =   !len+-1:>-1:?len
            & put$"-"
            & !"-"
          )
        & `!"--"
        & `!"-"
        & out$\n
    )
  &   ( verwerk
      =     tit pag experiment ptxt
          , titel txt men sel pg antw keuze expr putout
        .     ( pag
              =   !txt:%?pg ?txt
                & put$!pg
                & !experiment
                & !pag
              )
            & ( putout
              =   n s wr t
                .     
                    & !arg:%?t ?arg
                    & 0:?n
                    & ( detag
                      =   a b c
                        .     whl
                            ' ( @(!arg:?a "|_" ?b "_|" ?c)
                              & str$(!a !b !c):?arg
                              )
                          & !arg
                      )
                    & ( wr
                      =   
                        .     !n+1:<23:?n
                            & out$!arg
                          |   0:?n
                            & put$!arg
                            & get'
                      )
                    & whl'(@(!t:?s \n ?t)&wr$(detag$!s))
                    & wr$(detag$!t)
                    & putout$!arg
                  | 
              )
            & ( pag
              =   !txt:%?pg ?txt
                & putout$!pg
                & !experiment
                & !pag
              )
            & ( tit
              = put$\n\n&out$!titel&streep$!titel
              )
            & ( experiment
              =     I:?expr
                  & ( put$"{?} "&get':?expr
                    | F:?expr
                    )
                  & '$expr:(=)
                |   put$"{!} "
                  & (   '$expr
                      : ( (=F)&out$Failure
                        | (=I)&out$"Ignored failure"
                        )
                    |     put
                        $ (   '$expr:(=?_?)
                            & str$('$_):("=$"|"='")
                            & '$expr
                          | !expr
                          )
                      & out$"
    Success"
                    )
                  & !experiment
              )
            & :?antw
            &   whl
              ' ( !arg:%@?ptxt ?arg
                &   !!ptxt
                  : ( (T,?titel,?txt)&!tit&~!pag
                    |   (M,?titel,?men,?sel)
                      &   whl
                        ' ( !tit
                          & putout$(!men "
~  last topic

Topic:")
                          &   get'
                            : ?antw
                            : ~
                            : ~html
                            : ~htmltable
                            : ~latex
                            : ~htmllatex
                            : ~save
                            : ~lex
                          & (   !sel:? (`!antw,?keuze) ?
                              & verwerk$!keuze
                            | out$(!antw " is an invalid choice")
                            )
                          )
                    )
                )
            & !antw
          |   put$\nexit
            & put$" \""
            & put$!titel
            & out$\"
            & out$(antw !antw)
            & !antw
      )
      ( doHTML
      =     writeHTML doMenu compactBlockquotes
          , fputall anchors convert2html entCP
          , angbrack codes inline1 createIndex
          , flatten flattenBlockLevel removeBr
          , removeBreaks removeEmpty removeEmptyP
          , unspace tablestuff
          , Contents Index allhelp helpbody
        .   ( angbrack
            =   a m
              .     @(!arg:?a "<" %?m ">" ?arg)
                  &   !a
                      ( @(!m:? \n ?)&"<" !m ">"
                      | (i.,!m)
                      )
                      angbrack$!arg
                | !arg
            )
          & ( codes
            =   e a cds code codev A K L Z
              .   ( code
                  =   a e z ZA AA az zz S seps P n A
                    .     @( str$!arg
                           :   ?a
                               %@( ( "$"
                                   | "`"
                                   | "|"
                                   | "&"
                                   | "%"
                                   | "\\"
                                   | "@"
                                   | "#"
                                   | "{"
                                   | "}"
                                   | "["
                                   | "]"
                                   | "~"
                                   | "^"
                                   | "*"
                                   | "+"
                                   |   "="
                                     & @(!a:~(? ("<"|">")))
                                   | "_"
                                   |   ( "."
                                       | ","
                                       | "!"
                                       | "?"
                                       | ":"
                                       | ";"
                                       | "'"
                                       )
                                     & ( !a:
                                       | @(!a:? " ")
                                       | @(!a:? \n)
                                       )
                                   )
                                 : ?e
                                 )
                               ( ?z
                               & ( !e:~"`"
                                 |   @(!z:~("`" ?))
                                   & @(!a:~(? "`"))
                                   & @(!z:(%?az&utf$!az) ?)
                                   & @(ugc$!az:~(L ?))
                                 )
                               )
                           )
                        & (S=" "|\n)
                        & " ":?seps
                        & @( rev$!a
                           : ( ?A ((\n|\r) ?:?P)
                             | ?A&:?P
                             )
                           )
                        & @( !A
                           :   ?ZA
                               (   %@( !S
                                     |   ">"
                                       & ("<":?S) !seps:?seps
                                       & ~
                                     |   ")"
                                       & ("(":?S) !seps:?seps
                                       & ~
                                     )
                                   ( ?AA
                                   & (!seps:% ?seps|)
                                   & (   !seps:
                                       & str$(!ZA !S):?ZA
                                     | !seps:%?S ?seps&~
                                     )
                                   )
                               | :?AA
                               )
                           )
                        & " ":?seps
                        & " ":?S
                        & @(!z:?z ((\n ?|):?n))
                        & @( !z
                           :   ?az
                               (   %@( !S
                                     |   (   "<"
                                           & (">":?S) !seps:?seps
                                         |   "("
                                           & (")":?S) !seps:?seps
                                         )
                                       & ~
                                     )
                                   ( ?zz
                                   & (!seps:% ?seps|)
                                   & (   !seps:
                                       & !az !S:?az
                                     | !seps:%?S ?&~
                                     )
                                   )
                               | :?zz
                               )
                           )
                        &   codev$(str$(rev$!P rev$!AA))
                            (   str$(rev$!ZA !e !az):?e
                              &   !e
                                : ( ","
                                  | ", "
                                  | ". "
                                  | "."
                                  )
                              & !e
                            | (code.,!e)
                            )
                            code$(str$(!zz !n))
                      | codev$!arg
                  )
                & ( codev
                  =   a e z,az zz S seps n
                    .     @( str$!arg
                           : ( ?a " !" ?z&" !":?e
                             | ?a " ?" ?z&" ?":?e
                             )
                           )
                        & :?seps
                        & " ":?S
                        & @(!z:?z ((\n ?|):?n))
                        & @( !z
                           :   ?az
                               (   %@( !S
                                     |   (   "<"
                                           & !S !seps:?seps
                                           & ">":?S
                                         |   "("
                                           & !S !seps:?seps
                                           & ")":?S
                                         )
                                       & ~
                                     )
                                   ( ?zz
                                   & ( !seps:
                                     | !seps:%?S ?&~
                                     )
                                   )
                               | :?zz
                               )
                           )
                        &   str$!a
                            (code.,str$(!e !az !S))
                            codev$(str$(!zz !n))
                      | !arg
                  )
                & code$!arg:?cds
                &   whl
                  ' ( !cds:?A (code.?,?K) (code.?,?L) ?Z
                    & !A (code.,str$(!K !L)) !Z:?cds
                    )
                &   map
                  $ ( ( 
                      =   
                        .   !arg:@&angbrack$!arg
                          |   !arg:(?e.?a,?arg)
                            & (!e.!a,angbrack$!arg)
                      )
                    . !cds
                    )
            )
          & ( inline1
            =   a m
              .     @(!arg:?a "|_" ?m "_|" ?arg)
                  &   (   !a
                        : ( ", "
                          | ". "
                          | "! "
                          | "? "
                          )
                      | codes$!a
                      )
                      (!m:|(code.,angbrack$!m))
                      inline1$!arg
                | codes$!arg
            )
          & ( convert2html
            =   xml file Ent atts ent entn write,doamp
              .   !arg:(?xml.?file)
                & ( doamp
                  =   x y
                    .     @(!arg:?x ";" ?y)
                        & (   @(get$(str$("&" !x ";"),HT,ML,MEM):"&" !x ";")
                            & amp
                          | !y:?arg&!x
                          )
                      | amp
                    . !arg
                  )
                & ( Ent
                  =   a c amp
                    .     @( str$!arg
                           :   ?a
                               ( ( "<"
                                 | "&"
                                 | ">"
                                 | \"
                                 | "'"
                                 )
                               : ?c
                               )
                               ?arg
                           )
                        &   !a
                            "&"
                            ( !c:"<"&lt
                            |   !c:"&"
                              & doamp$!arg:(?amp.?arg)
                              & !amp
                            | !c:">"&gt
                            | !c:\"&quot
                            | apos
                            )
                            ";"
                            Ent$!arg
                      | !arg
                  )
                & ( ent
                  =   a c amp
                    .     @( !arg
                           :   ?a
                               ( ("<"|"&"|">")
                               : ?c
                               )
                               ?arg
                           )
                        &   !a
                            "&"
                            ( !c:"<"&lt
                            |   !c:"&"
                              & doamp$!arg:(?amp.?arg)
                              & !amp
                            | gt
                            )
                            ";"
                            ent$!arg
                      | !arg
                  )
                & ( entn
                  =   A
                    .   !arg:%?A ?arg&toML$!A entn$!arg
                      | !arg
                  )
                & ( atts
                  =   a v
                    .     !arg:(?a.?v) ?arg
                        & " " ent$!a "=\"" Ent$!v \" atts$!arg
                      | 
                  )
                & ( write
                  =   xml car A B C att
                    .   !arg:?xml
                      &   whl
                        ' ( !xml:%?car ?xml
                          & (   !car:(?A.?B)
                              & (   !B:(?att,?C)
                                  & (     !A
                                        : ( dl
                                          | table
                                          | ul
                                          | ol
                                          | blockquote
                                          | p
                                          | @(?:h #)
                                          )
                                      & fil$(,,,\n)
                                    | 
                                    )
                                  & (   !C:
                                      & fil$(,,,str$("<" !A atts$!att " />"))
                                    |   fil$(,,,str$("<" !A atts$!att ">"))
                                      & write$!C
                                      & fil$(,,,str$("</" !A ">"))
                                    )
                                |   !A
                                  : (   
                                      & !B:(?B.)
                                      & fil$(,,,str$("</" ent$!B ">"))
                                    |   "!"
                                      & fil$(,,,str$("<!" !B ">"))
                                    |   "!--"
                                      & fil$(,,,str$("<!--" !B "-->"))
                                    |   "?"
                                      & fil$(,,,str$("<?" !B "?>"))
                                    |   "![CDATA["
                                      & fil$(,,,str$("<![CDATA[" !B "]]>"))
                                    |   "!DOCTYPE"
                                      & fil$(,,,str$("<!DOCTYPE" !B ">"))
                                    |   ?
                                      & fil$(,,,str$("<" !A atts$!B ">"))
                                    )
                                )
                            | fil$(,,,str$(entn$!car))
                            )
                          )
                  )
                & fil$(!file,w)
                & fil$(,STR)
                & write$!xml
                & (fil$(,SET,-1)|)
                & ok
            )
          & (entCP=.get$(!arg,MEM,HT,ML))
          & ( writeHTML
            =     refs Tit doMenuItems listmenu2 pag2 titel
                , topictitel overviewtitref backtotitref
                , txt men sel antw ptxt
                , keuze addContent2paragraphs menu
                , menutekst menutitel titl
                , break2 indented2 asCode2
                , ol2 ul2 subul trim blocklevel
                , chunk2 nbsp2 first next spaced
                , definitionList unindent
              .   ( refs
                  =     ptxt titl next nextptxts
                      , overviewtitel overviewref
                      , backtotitel backtoref
                    .     !arg
                        : ( ?ptxt
                          . (?overviewtitel.?overviewref)
                          . (?backtotitel.?backtoref)
                          . ?nextptxts
                          )
                      & ( :!overviewtitel
                        |   addContent2paragraphs
                          $ ( !ptxt
                            . overview
                            .   (span.(class.arrow),entCP$"&uArr;")
                                ( a
                                .     (href."#" !overviewref)
                                      (style."line-height:12pt")
                                  , inline1$!overviewtitel
                                )
                                (br.,)
                            )
                        )
                      & ( :!backtotitel
                        |   addContent2paragraphs
                          $ ( !ptxt
                            . back
                            .   (span.(class.arrow),entCP$"&lArr;")
                                ( a
                                .   (href."#" !backtoref) (style."line-height:12pt")
                                  ,   !!backtoref:(?,?titl,?)
                                    & inline1$!titl
                                )
                                (br.,)
                            )
                        )
                      & (   !nextptxts:%?next ?
                          &   addContent2paragraphs
                            $ ( !ptxt
                              . more
                              .   (span.(class.arrow),entCP$"&rArr;")
                                  ( a
                                  .   (href."#" !next) (style."line-height:12pt")
                                    ,   !!next:(?,?titl,?)
                                      & inline1$!titl
                                  )
                                  (br.,)
                              )
                        | 
                        )
                  )
                & (asCode2=.span.(class.courier),!arg)
                & ( addContent2paragraphs
                  =   a,b,c,e,f,g,par,section,content
                    .   !arg:(?par.?section.?content)
                      &   (   !paragraphs:?a (!par.?b) ?c
                            & (   !b:?e (!section.?f) ?g
                                & (   !f:? !content ?
                                    & !paragraphs
                                  |   !a
                                      (!par.!e (!section.!f !content) !g)
                                      !c
                                  )
                              | !a (!par.!b (!section.!content)) !c
                              )
                          | !paragraphs (!par.!section.!content)
                          )
                        : ?paragraphs
                  )
                & ( indented2
                  =   a
                    .     !arg:%?a %?arg
                        & indented2$!a indented2$!arg
                      | nbsp2$!arg
                  )
                & ( nbsp2
                  =   a
                    .     @(!arg:?a " " ?arg)
                        & inline1$!a entCP$"&nbsp;" nbsp2$!arg
                      | inline1$!arg
                  )
                & ( break2
                  =   b,id
                    .     ~
                        & @( !arg
                           :   (|? " "|`)
                               ()
                               "<"
                               ?id
                               ">"
                               ?b
                           )
                        & "<expression> : ?<variable>"
                        & asCode2$("<" indented2$!id ">") asCode2$(indented2$!b)
                      | inline1$!arg
                  )
                & ( subul
                  =   a b c d e
                    .     (   @(!arg:"  -" ?b "\n  -" ?c)
                            & :?a
                          | @(!arg:?a "\n  -" ?b "\n  -" ?c)
                          )
                        &   !a
                            (   @( !c
                                 : ?d \n ((%@:~" ":~"*") ?:?e)
                                 )
                              &   (ul.,ul2$("  -"."  -" !b \n "  -" !d))
                                  chunk2$!e
                            | (ul.,ul2$("  -"."  -" !b \n "  -" !c))
                            )
                      | inline1$!arg
                  )
                & ( ol2
                  =   n,s,t
                    .     @( str$!arg
                           :   #%?n
                               `%?s
                               ?t
                               ( \n ((=.!n+1)$() !s ?:?arg)
                               | :?arg
                               )
                           )
                        & ( @( !t
                             :   (|? " "|`)
                                 ()
                                 ~" "
                                 ?t
                             )
                          | 
                          )
                        & (li.,subul$!t) ol2$!arg
                      | 
                  )
                & ( ul2
                  =   t,bullet
                    .     !arg:(?bullet.?arg)
                        & @( str$!arg
                           :   !bullet
                               ?t
                               ( \n (!bullet ?:?arg)
                               | :?arg
                               )
                           )
                        & ( @( !t
                             :   (|? " "|`)
                                 ()
                                 ~" "
                                 ?t
                             )
                          | 
                          )
                        & (li.,subul$!t) ul2$(!bullet.!arg)
                      | 
                  )
                & ( trim
                  =   a b
                    .   rev$!arg:?arg
                      &   whl
                        ' ( @(!arg:?a \n \t ?b)
                          & str$(!a \n !b):?arg
                          )
                      &   whl
                        ' ( @(!arg:?a \n " " ?b)
                          & str$(!a \n !b):?arg
                          )
                      &   whl
                        ' ( @(!arg:?a \r ?b)
                          & str$(!a !b):?arg
                          )
                      &   whl
                        ' ( @(!arg:?a \n\n\n ?b)
                          & str$(!a \n\n !b):?arg
                          )
                      & whl'@(!arg:\n ?arg)
                      & rev$!arg
                  )
                & ( chunk2
                  =   a b c
                    .   @(!arg:\n ?c)&chunk2$!c
                      |   @(!arg:?a \n\n ?c)
                        & chunk2$!a chunk2$!c
                      |   @(!arg:"{" %@ "}" ?:?c)
                        & ( @(!c:?b \n (%@(~"{":~" ") ?:?c))
                          | (!c.):(?b.?c)
                          )
                        &   (br.,)
                            blocklevel$!b
                            (br.,)
                            chunk2$!c
                      |   @(!arg:?a \n ("{" %@ "}" ?:?c))
                        & ( @(!c:?b \n (%@(~"{":~" ") ?:?c))
                          | (!c.):(?b.?c)
                          )
                        &   chunk2$!a
                            (br.,)
                            blocklevel$!b
                            (br.,)
                            chunk2$!c
                      | (br.,) blocklevel$!arg (br.,)
                  )
                & ( unindent
                  =   line lines all ret
                    .     :?lines:?ret
                        & !arg:?all
                        &   whl
                          ' ( @( !all
                               : " " ?line (\n ?all|:?all)
                               )
                            & !lines !line:?lines
                            &   (!ret:|!ret \n) !line
                              : ?ret
                            )
                        & !all:
                        & unindent$(str$!ret)
                      | !arg
                  )
                & ( definitionList
                  =   T dt n dt dd dds dl
                    .   !arg:?T
                      & @(!T:?dt "\n " ?)
                      & @(!dt:~:~(" " ?):~(? \n ?))
                      & 0:?n
                      & :?dl:?dds
                      &   whl
                        ' ( @(!T:%?dt \n ?T)
                          & @(!dt:~(" " ?))
                          & ( :!dds
                            |   !dl (dd.,!dds):?dl
                              & :?dds
                            )
                          & !dl (dt.,inline1$!dt):?dl
                          & 1+!n:?n
                          & @(!T:" " ?dd \n ?T)
                          & !dd:?dds
                          &   whl
                            ' ( @(!T:" " ?dd \n ?T)
                              & !dds \n !dd:?dds
                              )
                          )
                      & !n:>1
                      & :?dd
                      & @( !T
                         : ( &:?dd
                           | " " ?dd
                           )
                         )
                      &     !dl
                            (dd.,(!dds:|!dds \n) !dd)
                        : ?dl
                      &     map
                          $ ( ( 
                              =   
                                .     !arg:(dd.?,?arg)
                                    & (dd.,blocklevel$(unindent$(str$!arg)))
                                  | !arg
                              )
                            . !dl
                            )
                        : ?dl
                      & (dl.,!dl)
                  )
                & ( trimn
                  =   c p
                    .   !arg:(?arg.?p)
                      &   str
                        $ ( vap
                          $ ( ( 
                              =   
                                .     whl
                                    ' ( !p+-1:~<0:?p
                                      & @(!arg:" " ?arg)
                                      )
                                  & !arg
                              )
                            . str$!arg
                            . \n
                            )
                          )
                  )
                & ( trim1
                  =   
                    .     whl
                        ' ( ~( 
                             & @( !arg
                                : ( 
                                  | (%@:~" ") ?
                                  | ? \n (%@:~" ":~\n) ?
                                  )
                                )
                             )
                          & trimn$(!arg.1):?arg
                          )
                      & !arg
                  )
                & ( commentOut
                  =   lines comments code com edoc p A Z,nls bal
                    .   :?lines:?comments
                      & ( nls
                        =   
                          .     @(!arg:? \n ?arg)
                              & \n nls$!arg
                            | 
                        )
                      & ( bal
                        =   a b c
                          .   @( !arg
                               :   ?a
                                   "{"
                                   ?b
                                   "}"
                                   ( ?c
                                   & bal$!a
                                   & bal$!b
                                   & bal$!c
                                   )
                               )
                            | ~( 
                               & @( !arg
                                  : (? "{" ?|!arg:? "}" ?)
                                  )
                               )
                        )
                      &   whl
                        ' ( @( !arg
                             : ?code "{" ?com ("}"&bal$!com) ?arg
                             )
                          & (   !com:"?"
                              & str$(!code "{?}"):?code
                              & :?com
                            | 
                            )
                          & (   @(!com:?A \n ?Z)
                              & rev$(str$(!lines !code)):?edoc
                              & ( @(!edoc:? \n [?p ?)
                                | @(!edoc:? [?p)
                                )
                              & str$(!A \n trimn$(!Z.!p+1)):?com
                            | trimn$(!com.1):?com
                            )
                          & !comments nls$!code !com:?comments
                          & !lines !code nls$!com:?lines
                          )
                      & (str$(!lines !arg).trim1$(str$(!comments nls$!arg)))
                  )
                & ( exinput
                  =   code comment
                    .     !tablestuff:convertBlockQuoteToTable
                        & commentOut$(str$!arg):(?code.?comment)
                        &   (pre.(class.exinput),!code)
                            (pre.(class.excomment),!comment)
                      | (pre.(class.exinput),str$!arg)
                  )
                & ( pre
                  =   a b c
                    .     @(!arg:"{?}" ?)
                        & (   @( !arg
                               : "{?}" ?a \n (~(? \n ?) "{!}" ?:?b)
                               )
                            & exinput$("{?}" !a) pre$!b
                          | exinput$!arg
                          )
                      |   @(!arg:?c "{!}" ?)
                        & @(!c:~(? \n ?))
                        & (   @(!arg:"{!}" ?a ("{?}" ?:?b))
                            &   (pre.(class.exoutput),"{!}" !a)
                                pre$!b
                          | (pre.(class.exoutput),!arg)
                          )
                      | out$(AAARRGG !arg)&AAARRGG
                  )
                & ( blocklevel
                  =   a b c d ee f g s x y
                    .     @(!arg:?a \n1 `%?s ?b \n2 !s ?c)
                        &   break2$!a
                            (   @( !c
                                 : ?d \n ((%@:~" ":~#) ?:?ee)
                                 )
                              &   (ol.,ol2$(1 !s !b \n 2 !s !d))
                                  (p.,chunk2$!ee)
                            | (ol.,ol2$(1 !s !b \n 2 !s !c))
                            )
                      |   (   @(!arg:"*" ?b "\n*" ?c)
                            & :?a
                          |   @(!arg:?a "\n*" ?b "\n*" ?c)
                            & break2$!a:?a
                          )
                        &   !a
                            (   @( !c
                                 : ?d \n ((%@:~" ":~"*") ?:?ee)
                                 )
                              &   (ul.,ul2$("*"."*" !b \n "*" !d))
                                  chunk2$!ee
                            | (ul.,ul2$("*"."*" !b \n "*" !c))
                            )
                      |   @(!arg:"{?}" ?)
                        & (   @( !arg
                               : "{?}" ?a \n (~(? \n ?) "{!}" ?:?b)
                               )
                            & (blockquote.,exinput$("{?}" !a) pre$!b)
                          | (blockquote.,exinput$!arg)
                          )
                      |   @(!arg:~(? \n ?) "{!}" ?)
                        & (   @(!arg:?c "{!}" ?a ("{?}" ?:?b))
                            & ( blockquote
                              .   
                                ,   (pre.(class.exoutput),!c "{!}" !a)
                                    pre$!b
                              )
                          | (blockquote.,(pre.(class.exoutput),!arg))
                          )
                      | definitionList$!arg
                      |   @(!arg:?a "\n " ?b)
                        &   blocklevel$!a
                            (   @(!b:?b \n ?c)
                              & (blockquote.,(pre.,!b)) blocklevel$!c
                            | (blockquote.,(pre.,!b))
                            )
                      |   @(!arg:" " ?b)
                        & (   @(!b:?b \n ?c)
                            & (blockquote.,(pre.,!b)) blocklevel$!c
                          | (blockquote.,(pre.,!b))
                          )
                      |   @( !arg
                           :   ( &:?a
                               | ?a \n
                               )
                               ( %?c \n ?d
                               & @(!c:?x "  " ?y)
                               & @( !d
                                  :   ?ee
                                      (   \n
                                          ( ?f
                                          & ( @( !f
                                               :   ?f
                                                   \n
                                                   ( (\n ?|~(? \n ?))
                                                   : ?g
                                                   )
                                               )
                                            | :?g
                                            )
                                          & ~( 
                                             & @(!f:? "  " ?)
                                             )
                                          )
                                      | &:?f:?g
                                      )
                                  )
                               )
                           )
                        &   break2$!a
                            (blockquote.,(pre.,!c \n !ee))
                            (!f:|\n !f)
                            (!g|\n !g)
                      | inline1$!arg
                      | break2$!arg
                  )
                & ( pag2
                  =   pg ptxt pgs
                    .   !arg:(?ptxt.?pgs)
                      &   whl
                        ' ( !pgs:%?pg ?pgs
                          & trim$!pg:?pg
                          & chunk2$!pg:?pg
                          & addContent2paragraphs$(!ptxt.text.!pg)
                          )
                  )
                & ( Tit
                  =   titel ptxt
                    .   !arg:(?ptxt.?titel)
                      &   addContent2paragraphs
                        $ (!ptxt.titel.h1.,(a.(name.!ptxt),inline1$!titel))
                  )
                & ( spaced
                  =   a
                    .   !arg:%?a %?arg&!a " " spaced$!arg
                      | !arg
                  )
                & ( first
                  =   
                    .   !arg:%?arg ?&!arg
                      | 
                  )
                & ( listmenu2
                  =     men sel tekst a b term definition
                      , ddlines padded menu/tekst
                    .   !arg:(?men.?sel)
                      & ( padded
                        =   
                          .     @(!arg:%@)
                              & entCP$"&nbsp;" !arg entCP$"&nbsp;"
                            |   @(!arg:%@ %@)
                              & entCP$"&nbsp;" !arg
                            | !arg
                        )
                      & ( ddlines
                        =   line
                          .     @(!arg:?line \n ?arg)
                              & inline1$!line (br.,) ddlines$!arg
                            | inline1$!arg
                        )
                      &     map
                          $ ( ( 
                              =   
                                .   !arg:(?antw,?keuze)
                                  & (   @( !men
                                         :   ( !antw&:?a
                                             | ?a \n !antw
                                             )
                                             " "
                                             ( ?tekst
                                             & ( !antw:#
                                               | str$(!antw " " !tekst):?tekst
                                               )
                                             )
                                             ( ( \n (%@:~" ") ?
                                               | 
                                               )
                                             : ?b
                                             )
                                         )
                                      & str$(!a !b):?men
                                    |     out
                                        $ ( "error men="
                                            str$!men
                                            " sel="
                                            str$!sel
                                            " antw="
                                            !antw
                                            " arg="
                                            !arg
                                          )
                                      & get'
                                    )
                                  & (   !keuze:
                                      |   @(!tekst:?term \n ?definition)
                                        &   ( dt
                                            .   
                                              , ( a
                                                .   (href."#" first$!keuze)
                                                  , inline1$!term
                                                )
                                            )
                                            (dd.,ddlines$!definition)
                                            \n
                                      |   ( dt
                                          .   
                                            , ( a
                                              .   (href."#" first$!keuze)
                                                , inline1$!tekst
                                              )
                                          )
                                          \n
                                    . !tekst
                                    )
                              )
                            . !sel
                            )
                        : ?menu/tekst
                      & ( !men
                        .   map
                          $ ( ( 
                              = .!arg:(?arg.?)&!arg
                              )
                            . !menu/tekst
                            )
                        .   map
                          $ ( ( 
                              = .!arg:(?.?arg)&!arg
                              )
                            . !menu/tekst
                            )
                        )
                  )
                & ( doMenuItems
                  =   sel menutekst antw keuze menutitel
                    .   !arg:(?sel.?menutekst)
                      &   whl
                        ' ( !sel:(?antw,?keuze) ?sel
                          & ( !keuze:
                            |   !menutekst:%?menutitel ?menutekst
                              & writeHTML$((!titel.!ptxt).!menutitel.!keuze)
                            )
                          )
                  )
                & (.):?backtotitref
                & !arg:(?overviewtitref.?topictitel.?arg)
                &   whl
                  ' ( !arg:%@?ptxt ?arg
                    &   !!ptxt
                      : (   (T,?titel,?txt)
                          & Tit$(!ptxt.!titel)
                          & pag2$(!ptxt.!txt)
                          & refs$(!ptxt.!overviewtitref.!backtotitref.!arg)
                        |   (M,?titel,?men,?sel)
                          & Tit$(!ptxt.!titel)
                          & listmenu2$(!men.!sel):(?txt.?menu.?menutekst)
                          & addContent2paragraphs$(!ptxt.text.chunk2$!txt (dl.,!menu))
                          & refs$(!ptxt.!overviewtitref.!backtotitref.!arg)
                          & doMenuItems$(!sel.!menutekst)
                        )
                    & (!topictitel.!ptxt):?backtotitref
                    )
            )
          & ( anchors
            =   R a m Z M L lastchar E A
              .   ( lastchar
                  =   "/"
                    | ~<a:~>z
                    | ~<A:~>Z
                    | ~<0:~>9
                  )
                &   map
                  $ ( ( 
                      =   
                        .     !arg:@
                            & :?R
                            &   whl
                              ' ( @( !arg
                                   :   ?a
                                       http
                                       ?m
                                       ( (   ( " "
                                             | \n
                                             | \r
                                             | \t
                                             )
                                             ?
                                         | 
                                         )
                                       : ?arg
                                       )
                                   )
                                & @(rev$!m:?Z (%@?L:!lastchar) ?M)
                                & http rev$(str$(!L !M)):?m
                                & str$(rev$!Z !arg):?arg
                                & !R !a (a.(href.!m),!m):?R
                                )
                            & !R !arg
                          |   !arg:(?E.?A,?arg)
                            & (!E.!A,anchors$!arg)
                          | !arg
                      )
                    . !arg
                    )
            )
          & ( fputall
            =   
              .   map
                $ ( ( 
                    =   parcontent
                      .   !arg:(?.?parcontent)
                        &   map
                          $ ( ( 
                              =   content
                                .   !arg:(?.%?content)
                                  & map$((=.anchors$!arg).!content)
                              )
                            . !parcontent
                            )
                    )
                  . !arg
                  )
            )
          & ( removeEmpty
            =   Z es
              .   !arg:(?Z.?es)
                &   map
                  $ ( ( 
                      =   M e a
                        .     !arg:(?e.?a,?M)
                            & (!e.!a,removeEmpty$(!M.!es):?M):?arg
                            & (   !M:
                                & !es:? !e ?
                                & 
                              | !arg
                              )
                          | !arg
                      )
                    . !Z
                    )
            )
          & ( flatten
            =   A D
              .     !arg:?A (?.?,?D) ?arg
                  & !A flatten$!D flatten$!arg
                | !arg
            )
          & ( unspace
            =   
              .       vap
                    $ ( ( 
                        =   
                          .   vap
                            $ ( ( 
                                =   
                                  .   vap
                                    $ ( ( 
                                        =   
                                          .   !arg:
                                            | " " !arg
                                        )
                                      . !arg
                                      . \t
                                      )
                                )
                              . !arg
                              . \n
                              )
                        )
                      . !arg
                      . " "
                      )
                  : " " ?arg
                & str$!arg
            )
          & ( createIndex
            =     a Anchors L h dts body nam tit Tits
                , lastdt chapter b thisdt lasttit lasth
                , LL
              .   0:?Anchors
                & !arg:?body
                & 0:?Tits
                &   whl
                  ' (   !body
                      : ? (?.,(a.(name.?nam),?tit)) ?body
                    & (!nam.!tit)+!Tits:?Tits
                    )
                &   whl
                  ' ( !arg
                    :   ?
                        ( (?.,(a.(name.?chapter),?))
                        |   (dl.?,?L:?LL)
                          &   whl
                            ' ( !L:? (dt.?,?b) ?L
                              & (   !b:(a.?h,?a)
                                  &   (unspace$(str$(flatten$!a)).!h,!a)+!Anchors
                                    : ?Anchors
                                |   !b:?a
                                  &     ( unspace$(str$(flatten$!a))
                                        . (href."#" !chapter),!a
                                        )
                                      + !Anchors
                                    : ?Anchors
                                )
                              )
                        )
                        ?arg
                    )
                &   
                  : ?dts
                  : ?lastdt
                  : ?thisdt
                  : ?lasttit
                  : ?lasth
                &   whl
                  ' ( !Anchors:#*(?thisdt.(href."#" ?h),?a)+?Anchors
                    & !Tits:?+#*(!h.?tit)+?
                    & ( !tit:!lasttit
                      | :!lasttit&!tit:?lasttit
                      |     !dts (dd.,(a.(href."#" !lasth),!lasttit))
                          : ?dts
                        & !tit:?lasttit
                        & !h:?lasth
                      )
                    & ( !lastdt:!thisdt
                      |   !thisdt:?lastdt
                        & !dts (dt.,!a):?dts
                      )
                    )
                & !dts (dd.,(a.(href."#" !h),!tit)):?dts
                & (dl.,!dts)
            )
          & ( removeEmptyP
            =   A
              .     !arg:?A (p.,) ?arg
                  & !A removeEmptyP$!arg
                | !arg
            )
          & ( removeBr
            =   A E x a
              .     !arg:?A (?E.?x,?a) ?arg
                  & !A (!E.!x,removeBreaks$!a) removeBr$!arg
                | !arg
            )
          & ( removeBreaks
            =   A E x a z
              .     !arg:?A (?E.?x,?a (br.,) ?z) ?arg
                  &   removeBr$!A
                      (!a:|(!E.!x,removeBreaks$!a))
                      ( !z:
                      | removeBreaks$(!E.!x,removeBreaks$!z)
                      )
                      removeBreaks$!arg
                | removeBr$!arg
            )
          & ( flattenBlockLevel
            =   block data at X B Z
              .     !arg:(?block.?at,?data)
                  &   !data
                    :   ?X
                        ( (   dl
                            | table
                            | ul
                            | ol
                            | blockquote
                            | p
                            | @(?:h #)
                          . ?
                          )
                        : ?B
                        )
                        ?Z
                  &   (!block.!at,!X)
                      flattenBlockLevel$!B
                      flattenBlockLevel$(!block.!at,!Z)
                | !arg
            )
          &   ( compactBlockquotes
              =   A B M Z z e a x y
                .       map
                      $ ( ( 
                          =   
                            .   !arg:\n&
                              |   !arg:(~blockquote:?e.?a,?M)
                                & (!e.!a,compactBlockquotes$!M)
                              | !arg
                          )
                        . !arg
                        )
                    : ?Z
                  &   whl
                    ' (   !Z
                        :   ?a
                            (blockquote.?x,(pre.,?A))
                            (blockquote.!x,(pre.,?B))
                            ?z
                      & !a (blockquote.!x,(pre.,!A \r\n !B)) !z:?Z
                      )
                  &   whl
                    ' (   !Z
                        :   ?a
                            (blockquote.,(pre.(class.?e),?):?A)
                            (br.,)
                            (br.,)
                            (blockquote.,(pre.(class.~!e),?):?B)
                            ?z
                      & !a (blockquote.,!A \n !B) !z:?Z
                      )
                  &   whl
                    ' (   !Z
                        :   ?a
                            (br.?,)
                            (br.?,)
                            (blockquote.?x,(pre.,?A))
                            ?z
                      &     !a
                            (br.,)
                            (blockquote.!x,(pre.,!A))
                            !z
                        : ?Z
                      )
                  &   whl
                    ' (   !Z
                        :   ?a
                            (blockquote.?x,(pre.,?A))
                            (br.?,)
                            (br.?,)
                            ?z
                      &     !a
                            (blockquote.!x,(pre.,!A))
                            (br.,)
                            !z
                        : ?Z
                      )
                  & !Z
              )
              ( doMenu
              =     inner menus levmen todl LL
                  , A Anc Anc1 B C L LLhtml
                  , M MM Menus Menutje N anc l n
                .   :?menus
                  & ( inner
                    =     level anc men LA a b A B
                        , Anc T x m s S
                      .     !arg:(?men.?level.?anc)
                          &   (   !menus:?a (!men.?LA) ?b
                                &   !a
                                    ( !men
                                    .     !LA:?A+(!level.?Anc)+?B
                                        & (   !Anc:? !anc ?
                                            & !LA
                                          | !A+(!level.!Anc !anc)+!B
                                          )
                                      | !LA+(!level.!anc)
                                    )
                                    !b
                              | !menus !arg
                              )
                            : ?menus
                          & !!men:(M,?T,?x,?m)
                          &   whl
                            ' ( !m:(?,?s) ?m
                              &   whl
                                ' ( !s:%?S ?s
                                  & ( inner$(!S.!level+1.!anc,!men)
                                    | 
                                    )
                                  )
                              )
                        | 
                    )
                  & inner$(lusmenu.0.)
                  & !menus
                  &   whl
                    ' ( !menus:?A (?M.%?B+%) ?C
                      & !A (!M.!B) !C:?menus
                      )
                  & !menus:?Menus
                  & :?MM
                  &   whl
                    ' ( !Menus:(?N.?L.?Anc) ?Menus
                      & !MM (!N.!L.!Anc):?MM
                      &   whl
                        ' ( !Anc:%?Anc1 ?Anc
                          & (!Anc1,!N):?anc
                          & :?Menutje
                          &   whl
                            ' ( !Menus:?A (?n.?l.? !anc ?) ?B
                              & !Menutje (!n.!l.!anc):?Menutje
                              & !A !B:?Menus
                              )
                          & !Menutje !Menus:?Menus
                          )
                      )
                  & ( levmen
                    =   U T L A levs R M t
                      .     !arg:(?T.?L.?A) ?arg
                          & levmen$!arg:?levs
                          & !L+1:?M
                          & :?U
                          &   whl
                            ' ( !levs:(?t.!M.?R) ?levs
                              & !U (!t.!M.!R):?U
                              )
                          & ( !!T:(?,?t,?)
                            | UNKNOWN:?t
                            )
                          & (!T.!L.!t.!U) !levs
                        | !arg
                    )
                  & levmen$!MM:?LL
                  & ( todl
                    =   T L t S
                      . dl
                      .   
                        ,   map
                          $ ( ( 
                              =   
                                .   !arg:(?T.?L.?t.?S)
                                  &   ( dt
                                      .   
                                        , (a.(href.str$("#" !T)),inline1$!t)
                                      )
                                      ( !S:
                                      | (dd.,todl$!S)
                                      )
                              )
                            . !arg
                            )
                    )
                  & todl$!LL:?LLhtml
                  & (!LL.!LLhtml)
              )
          & ( flatMenuList
            =   NN menlist trv
              .   0:?NN
                & :?menlist
                & ( trv
                  =   name lev tit subs sub
                    .   !arg:(?name.?lev.?tit.?subs)
                      & !menlist (1+!NN:?NN.!name.!lev):?menlist
                      & whl'(!subs:%?sub ?subs&trv$!sub)
                  )
                & trv$!arg
                & !menlist
            )
          & ( reorderParagraphs
            =   menlist paragraphs pars,NN name lev A B C D
              .   !arg:(?menlist.?pars)
                &   map
                  $ ( ( 
                      =   
                        .   !arg:(?NN.?name.?lev)
                          &   !pars
                            : ?A (!name.(titel.?.?B) ?C) ?D
                          & !A !D:?pars
                          & (!name.(titel.str$(h !lev+1).!B) !C)
                      )
                    . !menlist
                    )
            )
          & ( rtrim
            =   
              .   str
                $ (     vap
                      $ ( ( 
                          = .whl'@(!arg:?arg " ")&!arg \n
                          )
                        . str$!arg
                        . \n
                        )
                    : ?arg \n
                  & !arg
                  )
            )
          & ( rightTrimPre
            =   A X E P
              .   map
                $ ( ( 
                    =   
                      .     !arg:(?E.?Y)
                          & (   !Y:(?A,?P)
                              & (   !E:pre
                                  & (pre.!A,rtrim$!P)
                                | (!E.!A,rightTrimPre$!P)
                                )
                            | (!E.rightTrimPre$!Y)
                            )
                        | !arg
                    )
                  . !arg
                  )
            )
          & ( convertBlockQuoteToTable
            =   A Z prows ret rows row,input comment output
              .   :?ret
                &   whl
                  ' (   !arg
                      :   ?A
                          ( blockquote
                          .   
                            ,     ?
                                  ( pre
                                  .   ( class
                                      .   exinput
                                        | excomment
                                        | exoutput
                                      )
                                    , ?
                                  )
                                  ?
                              : ?prows
                          )
                          ?arg
                    & :?row:?rows
                    &   whl
                      ' ( !prows
                        :   (   (pre.(class.exinput),?input)
                              &     !rows
                                    (!row:|(tr.,!row))
                                : ?rows
                              & :?comment:?output
                              &   (td.(class.exinput),!input chu$160)
                                : ?row
                            |   (pre.(class.excomment),?comment)
                              &     !row
                                    (td.(class.excomment),!comment chu$160)
                                : ?row
                            |   (pre.(class.exoutput),?output)
                              &   !row (td.(class.exoutput),!output)
                                : ?row
                            )
                            ?prows
                        )
                    &   !rows (!row:|(tr.,!row))
                      : ?rows
                    & !ret !A (table.,!rows):?ret
                    )
                & !ret !arg
            )
          & ( fixArrows
            =     A Z aa back backmore href inh
                , more name nback nmore seen txt za
              .   :?seen
                &   map
                  $ ( ( 
                      =   
                        .     !arg:(?name.?inh)
                            & !name !seen:?seen
                            & :?back:?more
                            & (   !inh:?A (back.?back) ?Z
                                & !A !Z:?inh
                              | 
                              )
                            & (   !inh:?A (more.?more) ?Z
                                & !A !Z:?inh
                              | 
                              )
                            & !back !more:~:?backmore
                            & :?nback:?nmore
                            &   whl
                              ' (   !backmore
                                  :   (span.(class.arrow),?)
                                      ( a
                                      .   ?aa (href."#" ?href) ?za
                                        , ?txt
                                      )
                                      (br.,)
                                      ?backmore
                                & (   !seen:? !href ?
                                    &     !nback
                                          (span.(class.arrow),⇐)
                                          ( a
                                          .   !aa (href."#" !href) !za
                                            , !txt
                                          )
                                          (br.,)
                                      : ?nback
                                  |     !nmore
                                        (span.(class.arrow),⇒)
                                        ( a
                                        .   !aa (href."#" !href) !za
                                          , !txt
                                        )
                                        (br.,)
                                    : ?nmore
                                  )
                                )
                            & (!name.!inh (more.!nmore) (back.!nback))
                          | !arg
                      )
                    . !arg
                    )
            )
          & !arg:(?fname.?tablestuff)
          & doMenu$:(?theMenu.?Contents)
          & flatMenuList$!theMenu:?menlist
          & :?paragraphs
          & writeHTML$((.).Bracmat.lusmenu)
          & reorderParagraphs$(!menlist.!paragraphs):?paragraphs
          & fixArrows$!paragraphs:?paragraphs
          & fputall$!paragraphs:?helpbody
          & removeEmpty$(!helpbody.code i):?helpbody
          & lst$(helpbody,helpbody,NEW,BIN)
          & compactBlockquotes$!helpbody:?helpbody
          & flattenBlockLevel$(p.,!helpbody):?helpbody
          & removeEmptyP$(removeBreaks$!helpbody):?helpbody
          & rightTrimPre$!helpbody:?helpbody
          & (!tablestuff:|!tablestuff$!helpbody:?helpbody)
          & createIndex$!helpbody:?Index
          &     ( "!DOCTYPE"
                . " html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\""
                )
                ( html
                .   (xmlns."http://www.w3.org/1999/xhtml")
                  ,   ( head
                      .   
                        ,   ( style
                            .   (type.text/css)
                              ,   ("!--"."span.courier {font-family: monospace;}")
                                  "span.arrow {line-height: 12pt;}
dl a {text-decoration:none;}
.exinput {color:blue;white-space:pre;font-family:consolas,monospace;font-size:0.8em;}
.excomment {color:green;white-space:pre;font-family:consolas,monospace;font-size:0.8em;}
.exoutput {color:brown;white-space:pre;font-family:consolas,monospace;font-size:0.8em;}"
                            )
                            ( meta
                            .     (http-equiv.Content-Type)
                                  (content."text/html; charset=UTF-8")
                              , 
                            )
                            (meta.(name.robots) (content."all, index"),)
                            (title.,"Bracmat Help")
                      )
                      ( body
                      .   
                        ,   ( p
                            .   
                              , ( i
                                .   
                                  , "This HTML document is automatically generated from the Help file that
accompanies Bracmat, using Bracmat to do the conversion."
                                )
                            )
                            (h1.,(a.(href.str$("#" INDEX)),INDEX))
                            (h1.,(a.(href.str$("#" CONTENTS)),Contents))
                            (hr.,)
                            !helpbody
                            (h1.,(a.(name.INDEX),INDEX))
                            (p.,(i.,(a.(href."#" lusmenu),"main menu")))
                            !Index
                            (h1.,(a.(name.CONTENTS),CONTENTS))
                            (p.,(i.,(a.(href."#" lusmenu),"main menu")))
                            !Contents
                            (p.,(i.,(a.(href."#" lusmenu),"main menu")))
                            ( p
                            .   
                              , ( a
                                .   (href."http://validator.w3.org/check?uri=referer")
                                  , ( img
                                    .     (src."http://www.w3.org/Icons/valid-xhtml10-blue")
                                          (alt."Valid XHTML 1.0 Strict")
                                          (height.31)
                                          (width.88)
                                      , 
                                    )
                                )
                            )
                      )
                )
            : ?allhelp
          & lst$(allhelp,str$(!fname ".bra"),NEW)
          & convert2html$(!allhelp.!fname)
          & out$(str$(!fname " written"))
      )
  & ( doTEX
    =   texprolog texepilog
      .   ( texprolog
          = "\\documentclass[12pt]{article}

\\usepackage[T1]{fontenc}
\\usepackage[utf8]{inputenc}
%\\usepackage{times}
\\usepackage{fancyvrb}
\\usepackage[x11names]{xcolor}
\\usepackage[a4paper,margin=2.54cm]{geometry}
\\usepackage{makeidx}
\\usepackage{booktabs}
\\usepackage[pdftex,colorlinks,linkcolor={blue!40!black},bookmarks]{hyperref}
\\usepackage{tocloft}

\\makeindex

\\DefineVerbatimEnvironment
  {ex}
  {Verbatim}
  {baselinestretch=1.2,formatcom=\\color{blue},vspace=0ex,xleftmargin=2em,commandchars=_\\[\\]}
\\DefineVerbatimEnvironment
  {v}
  {Verbatim}
  {baselinestretch=1.2,vspace=0ex,xleftmargin=2em,commandchars=_\\[\\]}
\\definecolor{comcolor}{HTML}{2D4D0E}
\\newcommand{\\com}[1]{\\textcolor{comcolor}{\\textrm{\\{ #1 \\}}}}
\\newcommand{\\coma}[1]{\\textcolor{comcolor}{\\textrm{\\{ #1}}}
\\newcommand{\\comb}[1]{\\textcolor{comcolor}{\\textrm{\\phantom{\\{ }#1}}}
\\newcommand{\\comc}[1]{\\textcolor{comcolor}{\\textrm{\\phantom{\\{ }#1 \\}}}}
\\newcommand{\\oct}{\\color{Firebrick3}}
\\newcommand{\\dollar}{\\$}
\\newcommand{\\bfun}[1]{\\subsubsection*{\\normalfont{#1}}}
\\newcommand{\\bc}[1]{\\texttt{#1}}
\\newcommand{\\bi}[1]{\\textit{#1}}
\\renewcommand{\\d}{\\$}

\\parindent=0cm
\\parskip=1ex
\\frenchspacing

\\begin{document}

\\title{Bracmat}
\\author{Bart Jongejan}

\\maketitle

\\newpage

\\tableofcontents

\\newpage

\\newcommand{\\caret}{\\char`\\^}

"
          )
        & ( texepilog
          = "\\section{Acknowledgements}
G\\'{e}rard Milmeister is the creator of the initial \\LaTeX version of this document. He has meticulously tried out all examples and reported the inconsistencies that he found. He also noticed that a few subjects were nowhere described. Following his advice, I have added the missing sections and improved some existing sections. Gérard also corrected spelling errors and improved wording in some places. This version of the document is generated by and from the Bracmat file called `help', using G\\'{e}rard Milmeister's improvements, style and layout as much as possible.

\\printindex

\\end{document}

%%% Local Variables:
%%% mode: latex
%%% TeX-master: t
%%% End:
"
          )
        & !arg:(?input.?output)
        & nestML$(get$(!input,HT ML)):?html
        & !html:? (html.?,? (body.?,?body) ?) ?
        & lst$(html,html,NEW)
        &   !body
          :   ?
              ( (h2.,(a.(name.intro),?Introduction) ?) ?
              : ?body
              )
        & lst$(body,body,NEW)
        & ( commentquotes
          =   A M
            .     !arg:?A \" ?M \" ?arg
                & !A !macro bc !begin !M !end commentquotes$!arg
              | !arg
          )
        & ( ldots
          =   A
            .     !arg:?A "." "." "." ?arg
                & !A "\\" ldots ldots$!arg
              | !arg
          )
        & ( lt
          =   A
            .     @(!arg:?A "<" ?arg)
                &   !A
                    ( @(!arg:"=" ?arg)&"$\\le$"
                    | "$<$"
                    )
                    lt$!arg
              | !arg
          )
        & ( gtlt
          =   A
            .     @(!arg:?A ">" ?arg)
                &   lt$!A
                    ( @(!arg:"=" ?arg)&"$\\ge$"
                    | "$>$"
                    )
                    gtlt$!arg
              | lt$!arg
          )
        & ( ldotss
          =   A
            .     @(!arg:?A "..." ?arg)
                & gtlt$!A "\\" ldots ldotss$!arg
              | gtlt$!arg
          )
        & ( LD
          =   A B
            .     !arg:?A "\\" %@?B ?arg
                & ldots$!A "\\char`\\\\" !B LD$!arg
              | ldots$!arg
          )
        & ( bfun
          =   
            .   map
              $ ( ( 
                  =   value dollar
                    .     !arg:@
                        & 2:?dollar
                        &   "\\bc{"
                              LD
                            $ ( vap
                              $ ( ( 
                                  =   
                                    .     !arg:"$"
                                        & 1:?dollar
                                        & "\\$"
                                      | !arg:"&"&"\\&"
                                      | !arg:"%"&"\\%"
                                      | !arg:"#"&"\\#"
                                      | !arg:"~"&"\\~"
                                      | !arg:"^"&"\\caret{}"
                                      | !arg:"_"&"\\char`\\_"
                                      | !arg:"{"&"\\{"
                                      | !arg:"}"&"\\}"
                                      |   !dollar:1
                                        & 2:?dollar
                                        & ( !arg:" "
                                          | "{}" !arg
                                          )
                                      | !arg
                                  )
                                . trim$!arg
                                )
                              )
                            "}"
                      | !arg:(i.,?value)&"\\bi{" !value "}"
                      | out$(bfun !arg)&UUU8\n
                  )
                . !arg
                )
          )
        & ( commentbc
          =   macro begin end
            .   !arg:(?arg.?macro.?begin.?end)
              &   trim
                $ ( str
                  $ ( map
                    $ ( ( 
                        =   dollar
                          .   !arg:@
                            & 2:?dollar
                            &   LD
                              $ ( commentquotes
                                $ ( vap
                                  $ ( ( 
                                      =   
                                        .     !arg:"$"
                                            & 1:?dollar
                                            & "$"
                                          |     !arg
                                              : ( "&"
                                                | "%"
                                                | "#"
                                                | "~"
                                                | "^"
                                                | "_"
                                                | "{"
                                                | "}"
                                                | "["
                                                | "]"
                                                )
                                            & !macro bc !arg
                                          |   !dollar:1
                                            & 2:?dollar
                                            & ( !arg:" "
                                              | !begin !end !arg
                                              )
                                          | !arg
                                      )
                                    . trim$!arg
                                    )
                                  )
                                )
                        )
                      . !arg
                      )
                    )
                  )
          )
        & (indexed=.map$((=."\\index{" !arg "@\\bc{" !arg "}}\n").!arg))
        & ( quotes
          =   A M a z f l
            .     @(!arg:?A \" ?M \" ?arg)
                &   (   @(!A:(:?a|? @?a))
                      & @(!arg:(:?z|%@?z ?))
                      & ( !a:"("&!z:")"
                        |   !a:(" "|\n|)
                          &   !z
                            : ( 
                              | " "
                              | ","
                              | "."
                              | "!"
                              | "?"
                              | \n
                              )
                        )
                      & ( @(!M:%@?f ? %@?l)
                        | !M:?f:?l
                        )
                      & @(ugc$!f:L ?)
                      & (!l:"."|@(ugc$!l:L ?))
                      & !A "``" !M "''"
                    | !A \" !M \"
                    )
                    quotes$!arg
              | !arg
          )
        & ( neat
          =   Y sub indices
            .   !arg:(?indices.?sub.?arg)
              & (   quotes
                  $ ( trim
                    $ ( str
                      $ ( map
                        $ ( ( 
                            =   http
                              .     !arg:@
                                  & (   @(!arg:? "$" ?)
                                      & bfun$!arg
                                    |       ldotss
                                          $ ( str
                                            $ (vap$((=.!arg).!arg.\r))
                                            )
                                        : ?Y
                                      &   (     !Y
                                              :   ( %@
                                                  : @( ?
                                                     :   ( ","
                                                         | "."
                                                         | "!"
                                                         )
                                                         ?
                                                     )
                                                  )
                                                  ?
                                            & 
                                          | " "
                                          )
                                          !Y
                                          " "
                                    )
                                |   !arg:(code.,?arg)
                                  & add2index$(!indices.!arg):?indices
                                  & bfun$!arg:?arg
                                |   !arg:(i.,?arg)
                                  & "\\bi{" trim$!arg "}"
                                |   !arg:(a.(href.?arg),?)
                                  & @(!arg:?http "//" ?arg)
                                  &   "\\allowbreak{}\\texttt{"
                                      !http
                                      "/"
                                        vap
                                      $ ((=."/\\allowbreak{}" !arg).!arg."/")
                                      "}"
                                | out$(!sub sectiontitle !arg)&UUU7
                            )
                          . !arg
                          )
                        )
                      )
                    )
                . !indices
                )
          )
        & ( dosectiontitle
          =   sub code indices
            .   !arg:(?sub.?arg)
              & :?indices
              &   (   !arg:@
                    &   (   @(!arg:(? "$" ?|? "'" ?))
                          & bfun$!arg
                        | "\\" !sub "section{" trim$(str$(quotes$!arg)) "}"
                        )
                        \n\n
                  |   !arg:? (code.,?) ?
                    &   "\\bfun{"
                        ( neat$(!indices..!arg):(?arg.?indices)
                        & !arg
                        )
                        "}"
                  |   "\\"
                      !sub
                      "section{"
                      (neat$(.!sub.!arg):(?arg.?)&!arg)
                      "}"
                  )
                  \n
                  indexed$(toindex$(!indices.!arg))
          )
        & ( toindex
          =   indices
            .     !arg:(?indices.?arg)
                & (!arg:(code.,?arg)|)
                &   !arg
                  :   ( %@
                      : @( ?
                         :   ?arg
                             ( "$("
                             | "$"
                             | "'"&@(!arg:~(? "'" ? "'" ?))
                             )
                         )
                      )
                      ?
                & add2index$(!indices.!arg)
              | !indices
          )
        & ( getTxt
          =   A
            .     !arg:(?.?,?A) ?arg
                & getTxt$!A getTxt$!arg
              | !arg
          )
        & ( commandchars
          =   macro begin end has lack A Z pairs txt verbatim
            .   !arg:?txt
              & getTxt$!txt:?txt
              &     map
                  $ ( ( 
                      =   
                        .       !txt
                              : ? (%@:@(?:? !arg ?)) ?
                            & !arg
                          | 
                      )
                    . "_" "[" "]"
                    )
                : ?has
              &     vap
                  $ ( ( 
                      =   
                        .       !txt
                              : ? %@(@(?:? !arg ?)&) ?
                            & 
                          | !arg
                      )
                    . "{}()/;<>`'{$^#~,.!?@%+-:\"|=\\*&"
                    )
                : ?lack
              & ("_"."["."]"):(?macro.?begin.?end)
              &   ("{"."}") ("["."]") ("("|")") ("(".")")
                : ?pairs
              & (   ( !has:~(? "[" ?)
                    |     !lack
                        :   ?A
                            %@?begin
                            %@?end
                            ( ?Z
                            & ( !pairs:? (!begin.!end) ?
                              | !pairs:~(? (?.!begin) ?)
                              )
                            )
                      & !A !Z:?lack
                      & (   !has:?A "]" ?Z
                          & !A !Z:?has
                        | 
                        )
                    | out$CANNOTBEGINEND&~
                    )
                  & ( !has:~(? "]" ?)
                    |   !lack
                      :   ?
                          %@?begin
                          %@?end
                          (   ?lack
                            & !pairs:? (!begin.!end) ?
                          | !pairs:~(? (?.!begin) ?)
                          )
                    )
                  & ( !has:~(? "_" ?)
                    | !lack:?lack %@?macro
                    )
                | out$("CANNOT DEFINE ALTCOMMANDCHARS!" !txt)
                )
              &   (   !txt:? (%@:@(?:? "{?}" ?)) ?
                    & ex
                  | v
                  )
                : ?verbatim
              & (!macro.!begin.!end.!verbatim)
          )
        & ( q
          =   
            .   (@("{}\\[]":? !arg ?)&"\\"|)
                !arg
          )
        & 0:?count
        & ( trim
          =   
            .   ( ltrim
                =   
                  .   @(!arg:? ((%@:~" ") ?:?arg))
                    & !arg
                )
              & (rtrim=.rev$(ltrim$(rev$!arg)))
              & ltrim$(rtrim$!arg)
          )
        & (com=.!macro com !begin commentbc$(!arg.!macro.!begin.!end) !end)
        & ( coma
          =   H
            .   @(!arg:?H ((%@:~" ") ?:?arg))
              & !H !macro coma !begin commentbc$(!arg.!macro.!begin.!end) !end
          )
        & ( comb
          =   H
            .   @(!arg:?H ((%@:~" ") ?:?arg))
              & !H !macro comb !begin commentbc$(!arg.!macro.!begin.!end) !end
          )
        & ( comc
          =   H
            .   @(!arg:?H ((%@:~" ") ?:?arg))
              & !H !macro comc !begin commentbc$(!arg.!macro.!begin.!end) !end
          )
        & ( add2index
          =   cand indices
            .   !arg:(?indices.?arg)
              & (   !arg:@(?:?cand "$" ?) ?
                  & ( @( !cand
                       :   ?
                           ( "+"
                           | "*"
                           | "^"
                           | "|"
                           | "'"
                           )
                           ?
                       )
                    |   trim$!cand:?cand
                      & ( !indices:? !cand ?
                        | !indices !cand:?indices
                        )
                    )
                | 
                )
              & !indices
          )
        & ( delimiter
          =   
            .   @( "/;`'{$^#~,.!?@%+-:\"|=\\*&"
                 :   ?
                     ( %@
                     : [%(@(!arg:~(? !sjt ?))&!sjt:?arg)
                     )
                     ?
                 )
              & !arg
          )
        & ( coding
          =   
            .   add2index$(.!arg)
              &   " "
                    map
                  $ ( ( 
                      =   dlmt
                        .     !arg:@
                            & (   @(!arg:? "..." ?)
                                & "\\bfun{" bfun$!arg "}"
                              |   delimiter$!arg:?dlmt
                                & "\\verb" !dlmt trim$!arg !dlmt
                              )
                          |   !arg:(i.,?arg)
                            & (   !arg:@
                                & (   @(!arg:? "..." ?)
                                    & bfun$!arg
                                  | "\\emph{" trim$!arg "}"
                                  )
                              | CURSIVE
                              )
                      )
                    . !arg
                    )
                  " "
          )
        & ( codify
          =   
            .   map
              $ ( ( 
                  =   
                    .     !arg:@
                        &   map
                          $ ( (=.vap$((=.!arg).!arg.\r))
                            . quotes$!arg
                            )
                      | !arg:(code.,?arg)&coding$!arg
                      | !arg:(i.,?arg)&"\\emph{" !arg "}"
                      |   !arg:(ol.,?arg)
                        & "\\begin{enumerate}" \n items$!arg "\\end{enumerate}"
                      |   !arg:(ul.,?arg)
                        & "\\begin{itemize}" \n items$!arg "\\end{itemize}" \n
                      | !arg:(?.,?arg)&
                  )
                . !arg
                )
          )
        & ( items
          =   
            .   map
              $ ( ( 
                  =   
                    .     !arg:(li.?,?arg)
                        & "\\item " codify$!arg \n
                      | 
                  )
                . !arg
                )
          )
        & ( defterm
          =   
            .   map
              $ ( ( 
                  =   
                    .     !arg:(dt.?,?arg)
                        & (!arg:(a.?,?arg)|)
                        & "\\item " codify$!arg
                      |   !arg:(dd.?,?arg)
                        & (!arg:(a.?,?arg)|)
                        & "\\par\n  " codify$!arg \n
                      | 
                  )
                . !arg
                )
          )
        & ( bal
          =   L
            .   0:?L
              &   vap
                $ ( ( 
                    =   
                      .   !arg:"{"&1+!L:?L
                        | !arg:"}"&-1+!L:?L
                        | 
                    )
                  . !arg
                  )
              & !L:0
          )
        & ( comments
          =   fun A Z M oct
            .   !arg:(?fun.?arg)
              & :?oct
              &     map
                  $ ( ( 
                      =   
                        .     !fun:(com|)
                            & (   @(!arg:?A "   F")
                                & !macro oct !begin !end !A "   F" \n
                              |   @(!arg:?A "   S")
                                & !macro oct !begin !end !A "   S" \n
                              |   @(!arg:?A "..." ?Z)
                                & !A !macro ldots !begin !end !Z \n
                              |   @( !arg
                                   :   ?A
                                       ("{" ?M ("}"&bal$!M))
                                       ?Z
                                   )
                                &   (   !M:"?"
                                      & :?oct
                                      & !A "{?}"
                                    |   !M:"!"
                                      & oct:?oct
                                      & !A !macro oct "{!}"
                                    |   ( !oct:
                                        | !macro oct
                                        )
                                        !A
                                        com$!M
                                    )
                                    (   !Z:~
                                      & comments$(com.!Z):(?fun.?Z)
                                      & !Z
                                    | \n
                                    )
                              |   @(!arg:?A "{" ?M)
                                & comb:?fun
                                &   (!oct:|!macro oct)
                                    !A
                                    coma$!M
                                    \n
                              |   (!oct:|!macro oct)
                                  !arg
                                  \n
                              )
                          |   !fun:comb
                            & (   @(!arg:?M "}" ?Z)
                                & com:?fun
                                &   comc$!M
                                    (   !Z:~
                                      & comments$(com.!Z):(?fun.?Z)
                                      & !Z
                                    | \n
                                    )
                              |   @(!arg:?A "   F")
                                & !macro oct !begin !end !A "   F" \n
                              |   @(!arg:?A "   S")
                                & !macro oct !begin !end !A "   S" \n
                              | comb$!arg \n
                              )
                          | (!oct:|!macro oct) !arg \n
                      )
                    . vap$((=.!arg).!arg.\n)
                    )
                : ?arg
              & (!fun.!arg)
          )
        & ( makeItemList
          =   
            .       !itemlist
                  : ? (dt.,? (a.(~href.?),@) ?) ?
                & UUU9
              |   "\\begin{quote}"
                  \n
                  "\\begin{description}"
                  \n
                  defterm$!arg
                  "\\end{description}"
                  \n
                  "\\end{quote}"
                  \n
          )
        & 0:?skipdl
        &     !texprolog
                map
              $ ( ( 
                  =   
                    .   !arg:(h1.,?h1)&
                      |   !arg:(h2.,?h2)
                        & (   !h2:(a.(name.?sectionname),?sectiontitle)
                            & dosectiontitle$(.!sectiontitle)
                          | out$(h2 !h2)&UUU5\n
                          )
                      |   !arg:(h3.,?h3)
                        & (     !h3
                              :   ?
                                  (a.(name.?subsectionname),?subsectiontitle)
                                  ?
                            & dosectiontitle$(sub.!subsectiontitle)
                          | out$(h3 !h3)&UUU4\n
                          )
                      |   !arg:(h4.,?h4)
                        & (     !h4
                              : ( a
                                . (name|href.?bfunname),?code
                                )
                            & dosectiontitle$(subsub.!code)
                          | lst$h4&UUU3\n
                          )
                      |   !arg:(h5.,?h5)
                        & (     !h5
                              : ( a
                                . (name|href.?bfunname),?code
                                )
                            & dosectiontitle$(.!code)
                          | out$(h5 !h5)&UUU2\n
                          )
                      |     !arg
                          : (p.,(i.,(a.(href."#lusmenu"),"main menu")))
                        & 1:?skipdl
                        & 
                      |   !arg:(p.,?par)
                        & (     !par
                              : (span.(class.arrow),?) (a.?,?)
                            & 
                          |     !par
                              : (   ?
                                    ( a
                                    .     ?
                                          ( href
                                          . @( ?
                                             : ( "#" ?
                                               | ? "validator.w3.org" ?
                                               )
                                             )
                                          )
                                          ?
                                      , ?
                                    )
                                    ?
                                | ( i
                                  .   
                                    ,   ?
                                        ( a
                                        .     ?
                                              ( href
                                              . @( ?
                                                 : ( "#" ?
                                                   | ? "validator.w3.org" ?
                                                   )
                                                 )
                                              )
                                              ?
                                          , ?
                                        )
                                        ?
                                  )
                                )
                            & 
                          |   ( neat$(..!par):(?par.?)
                              & !par
                              )
                              \n\n
                          )
                      |   !arg:(blockquote.,?blockquote)
                        & commandchars$!blockquote:(?macro.?begin.?end.?verbatim)
                        & com:?fun
                        &   \n
                            "\\begin{"
                            !verbatim
                            "}"
                            (   (!macro.!begin.!end):("_"."["."]")
                              & 
                            | "[commandchars=" q$!macro q$!begin q$!end "]"
                            )
                            \n
                            ( 1+!count:?count:>1000000
                            |   map
                              $ ( ( 
                                  =   
                                    .   ( !arg:(pre.?,?arg)
                                        | 
                                        )
                                      &     comments
                                          $ ( !fun
                                            .   str
                                              $ ( vap
                                                $ ( ( 
                                                    =   
                                                      .     !arg:\r
                                                          & 
                                                        |   !arg:λ
                                                          &   !macro
                                                              ensuremath
                                                              !begin
                                                              !macro
                                                              lambda
                                                              !end
                                                        | !arg
                                                    )
                                                  . !arg
                                                  )
                                                )
                                            )
                                        : (?fun.?arg)
                                      & !arg
                                  )
                                . !blockquote
                                )
                            )
                            "\\end{"
                            !verbatim
                            "}\n"
                      | !arg:(\r\n|\n)&
                      |   !arg:(dl.,?itemlist)
                        & (   !skipdl:1
                            & 0:?skipdl
                            & 
                          |     !itemlist
                              :   ?
                                  ( dt
                                  .   
                                    ,   ?
                                        (a.(href.@(?:"#" ?)),?arg)
                                        ?
                                  )
                                  ?
                            & (     !itemlist
                                  :   ?
                                      (dd.?,~(? (dl.?,?) ?))
                                      ?
                                & makeItemList$!itemlist
                              | 
                              )
                          | makeItemList$!itemlist
                          )
                      |   !arg:(ol.,?itemlist)
                        & "\\begin{enumerate}" \n items$!itemlist "\\end{enumerate}"
                      |   !arg:(ul.,?itemlist)
                        & "\\begin{itemize}" \n items$!itemlist "\\end{itemize}"
                      |   out$(str$("[" !arg "]"))
                        & str$("[" !arg "]UUU1\n")
                  )
                . !body
                )
              !texepilog
          : ?texstuff
        & put$(str$!texstuff,!output,NEW,BIN)
        & out$(str$(!output " written"))
    )
  &   out
    $ "* Choose from the menus the topics that interest you.
* Enter the number or character string that precedes your choice.
* Press <return> to return to the previous menu or to leave this tutor.
* If the {?} prompt appears without a menu, you can enter expressions that
  Bracmat will evaluate. Only pressing <return> pages through the information."
  &   verwerk$lusmenu
    : ( html&out$HTML&doHTML$("bracmat.html".)
      |   htmltable
        & out$"HTML with excercises in tables"
        & doHTML$("bracmat.html".convertBlockQuoteToTable)
      |   latex
        & out$TeX
        & doTEX$("bracmat.html"."bracmat.tex")
      |   htmllatex
        & out$"1:HTML"
        & doHTML$("bracmat.html".)
        & out$"2:LATEX"
        & doTEX$("bracmat.html"."bracmat.tex")
      | lex&get$"lex.bra"&lex$help
      |   save
        & lst$(help,"help.bra",NEW,WYD)
        &   put
          $ ( "
  help$()
& tbl$(help,0)
& \"
_________________________________________________________________________
\"
"
            , "help.bra"
            , APP
            , BIN
            )
      | ?
      );

  help$()
& tbl$(help,0)
& "
_________________________________________________________________________
"
