*CMD AbsN --- absolute value of x or |x| (arbitrary-precision math function)
*CORE
*CALL
	AbsN(x)

*DESC

This command performs the calculation of an elementary mathematical
function.  The arguments <i>must</i> be numbers.  The reason for the
postfix {N} is that the library needs to define equivalent non-numerical
functions for symbolic computations, such as {Exp}, {Sin}, etc.

Note that all xxxN functions accept integers as well as floating-point numbers.
The resulting values may be integers or floats.  If the mathematical result is an
exact integer, then the integer is returned.  For example, {Sqrt(25)} returns
the integer {5}, and {Power(2,3)} returns the integer {8}.  In such cases, the
integer result is returned even if the calculation requires more digits than set by
{BuiltinPrecisionSet}.  However, when the result is mathematically not an integer,
the functions return a floating-point result which is correct only to the current precision.

*EXAMPLES
In> AbsN(-1) 
Result: 1


*SOURCE org/mathpiper/builtin/procedures/core/Abs.java
==========
*CMD AddN --- add two numbers (arbitrary-precision math function)
*CORE
*CALL
	AddN(x,y)

*DESC

This command performs the calculation of an elementary mathematical
function.  The arguments <i>must</i> be numbers.  The reason for the
postfix {N} is that the library needs to define equivalent non-numerical
functions for symbolic computations, such as {Exp}, {Sin}, etc.

Note that all xxxN functions accept integers as well as floating-point numbers.
The resulting values may be integers or floats.  If the mathematical result is an
exact integer, then the integer is returned.  For example, {Sqrt(25)} returns
the integer {5}, and {Power(2,3)} returns the integer {8}.  In such cases, the
integer result is returned even if the calculation requires more digits than set by
{BuiltinPrecisionSet}.  However, when the result is mathematically not an integer,
the functions return a floating-point result which is correct only to the current precision.

*E.G.
In>
Result:


*SOURCE org/mathpiper/builtin/procedures/core/Add.java
==========
*CMD And? &? --- logical conjunction
*CORE
*CALL
	a1 &? a2
	And?(a1, a2, a3, ..., aN)

*PARMS

{a}1, ..., {a}N -- boolean values (may evaluate to {True} or {False})

*DESC

This function returns {True} if all arguments are true. The
{And?} operation is "lazy", i.e. it returns {False} as soon as a {False} argument
is found (from left to right).  This is faster, but also means that none of the
arguments should cause side effects when they are evaluated.
 If an argument other than {True} or
{False} is encountered a new {And?} expression is returned with all
arguments that didn't evaluate to {True} or {False} yet.
{And?(...)} and {Or?(...)} do also exist, defined in the script
library. You can redefine them as infix operators yourself, so you have the
choice of precedence. In the standard scripts they are in fact declared as
infix operators, so you can write {expr1 &? expr}.

*E.G.

In> True &? False
Result: False;

In> And?(True,True)
Result: True;

In> False &? _a
Result: False;

In> True &? _a
Result: &?(_a);

In> And?(True, _a, True, b)
Result: b &? a;

*SEE Or?, Not?, Implies?, Equivales?

*SOURCE org/mathpiper/builtin/procedures/core/And_.java
==========
*CMD &? --- logical conjunction
*SEE And?

*SOURCE org/mathpiper/builtin/procedures/core/And_.java
==========
*CMD ApplyFast --- a fast built-in version of the Apply function
*CALL
	ApplyFast(fn, arglist)

*PARMS

{fn} -- function to apply

{arglist} -- list of arguments

*DESC
This function is a fast built-in version of the Apply function.

*E.G.
In> ApplyFast("+", [5,9]);
Result: 14

In> ApplyFast([[x,y], x-y^2], [Cos(a), Sin(a)]);
Result: Cos(a)-Sin(a)^2

In>  ApplyFast(Lambda([x,y], x-y^2), [Cos(a), Sin(a)]);
Result: Cos(a)-Sin(a)^2

*SEE Apply

*SOURCE org/mathpiper/builtin/procedures/core/ApplyFast.java
==========
*CMD ArcCosD --- double-precision math function
*CORE
*CALL
	ArcCosD(x)

*PARMS
{x} -- a decimal number (0 and 1 allowed too).

*DESC
A double precision version of the ArcCos function.


*EXAMPLES
In> ArcCosD(.7) 
Result: 0.7953988302

In> ArcCosD(-0.2) 
Result: 1.772154248
*SEE SinD, CosD, TanD, CscD, SecD, CotD, ArcSinD, ArcTanD, ArcCscD, ArcSecD, ArcCotD

*SOURCE org/mathpiper/builtin/procedures/core/ArcCosD.java
==========
*CMD ArcCotD --- double-precision math function
*CORE
*CALL
	ArcCotD(x)

*PARMS
{x} -- a number

*DESC
A double precision version of the ArcCot function.


*EXAMPLES
In> ArcCotD(.7) 
Result: 0.9600703624

In> ArcCotD(-1.2) 
Result: -0.6947382762
*SEE SinD, CosD, TanD, CscD, SecD, CotD, ArcSinD, ArcCosD, ArcTanD, ArcCscD, ArcSecD

*SOURCE org/mathpiper/builtin/procedures/core/ArcCotD.java
==========
*CMD ArcCscD --- double-precision math function
*CORE
*CALL
	ArcCscD(x)

*PARMS
{x} -- a number

*DESC
A double precision version of the ArcCsc function.


*EXAMPLES
In> ArcCscD(1) 
Result: 1.570796327

In> ArcCscD(-1.2) 
Result: -0.9851107833
*SEE SinD, CosD, TanD, CscD, SecD, CotD, ArcSinD, ArcCosD, ArcTanD, ArcSecD, ArcCotD

*SOURCE org/mathpiper/builtin/procedures/core/ArcCscD.java
==========
*CMD ArcSecD --- double-precision math function
*CORE
*CALL
	ArcSecD(x)

*PARMS
{x} -- a decimal number

*DESC
A double precision version of the ArcSec function.


*EXAMPLES
In> ArcSecD(1) 
Result: 0

In> ArcSecD(-1.2) 
Result: 2.55590711
*SEE SinD, CosD, TanD, CscD, SecD, CotD, ArcSinD, ArcCosD, ArcTanD, ArcCscD, ArcCotD

*SOURCE org/mathpiper/builtin/procedures/core/ArcSecD.java
==========
*CMD ArcSinD --- double-precision math function
*CORE
*CALL
	ArcSinD(x)

*PARMS
{x} -- a number

*DESC
A double precision version of the ArcSin function.


*EXAMPLES
In> ArcSinD(.7) 
Result: 0.7753974966

In> ArcSinD(-0.2) 
Result: -0.2013579208
*SEE SinD, CosD, TanD, CscD, SecD, CotD, ArcCosD, ArcTanD, ArcCscD, ArcSecD, ArcCotD

*SOURCE org/mathpiper/builtin/procedures/core/ArcSinD.java
==========
*CMD ArcTanD --- double-precision math function
*CORE
*CALL
	ArcTanD(x)

*PARMS
{x} -- a number

*DESC
A double precision version of the ArcTan function.


*EXAMPLES
In> ArcTanD(.7) 
Result: 0.6107259644

In> ArcTanD(-1.2) 
Result: -0.8760580506
*SEE SinD, CosD, TanD, CscD, SecD, CotD, ArcSinD, ArcCosD, ArcCscD, ArcSecD, ArcCotD

*SOURCE org/mathpiper/builtin/procedures/core/ArcTanD.java
==========
*CMD ArrayCreate --- create array
*CORE
*CALL
	ArrayCreate(size,init)

*DESC
Creates an array with {size} elements, all initialized to the
value {init}.


*SOURCE org/mathpiper/builtin/procedures/core/ArrayCreate.java
==========
*CMD ArrayGet --- fetch array element
*CORE
*CALL
	ArrayGet(array,index)

*DESC
Returns the element at position index in the array passed. Arrays are treated
as base-one, so {index} set to 1 would return the car element.

Arrays can also be accessed through the {[]} operators. So
{array[index]} would return the same as {ArrayGet(array, index)}.


*SOURCE org/mathpiper/builtin/procedures/core/ArrayGet.java
==========
*CMD ArraySet --- set array element
*CORE
*CALL
	ArraySet(array,index,element)

*DESC
Sets the element at position index in the array passed to the value
passed in as argument to element. Arrays are treated
as base-one, so {index} set to 1 would set car element.

Arrays can also be accessed through the {[]} operators. So
{array[index] := element} would do the same as {ArraySet(array, index,element)}.


*SOURCE org/mathpiper/builtin/procedures/core/ArraySet.java
==========
*CMD ArraySize --- get array size
*CORE
*CALL
	ArraySize(array)

*DESC
Returns the size of an array (number of elements in the array).

PKHG TODO 18-11-2013
All 4 array alements ar[1] .. ar[4]

In> ar := ArrayCreate(4,[1 .. 4 ])
Result: class org.mathpiper.builtin.Array

In> ArraySize(ar)
Result: 4

In> ar[2]
Result: [[1,2,3,4]]

In> Type(ar[2])
Result: "List"

In> First(ar[2])
Result: [1,2,3,4]

In> First(ar[2])[4]
Result: 4



*SOURCE org/mathpiper/builtin/procedures/core/ArraySize.java
==========
*CMD Assign --- assignment
*CORE
*CALL
	Assign(var, exp)

*PARMS

{var} -- variable that should be assigned or a string that contains the name of the variable

{exp} -- expression to assign to the variable

*DESC

The expression "exp" is evaluated and assigned it to the variable
named "var". The first argument is not evaluated. The value True
is returned.

The statement {Assign(var, exp)} is equivalent to {var := exp}, but the {:=} operator
has more uses, e.g. changing individual entries in a list.

*E.G.

In> Assign(a, Sin(_x)+3);
Result: True;

In> a;
Result: Sin(_x)+3;

*SEE Unassign, :=

*SOURCE org/mathpiper/builtin/procedures/core/Assign.java
==========
*CMD AssignGlobalLazy --- global variable is to be evaluated lazily
*CORE
*CALL
	AssignGlobalLazy(var,value)

*PARMS

{var} -- variable (held argument)

{value} -- value to be set to (evaluated before it is assigned)

*DESC

{AssignGlobalLazy} enforces that a global variable will re-evaluate
when used. This functionality doesn't survive if {Unassign(var)}
is called afterwards.

Places where this is used include the global variables {%} and {I}.

The use of lazy in the name stems from the concept of lazy evaluation.
The object the global variable is bound to will only be evaluated when
called. The {AssignGlobalLazy} property only holds once: after
that, the result of evaluation is stored in the global variable, and it won't be reevaluated again:

In> AssignGlobalLazy(a,Hold(Taylor(x,0,30)Sin(x)))
Result: True

Then the first time you call {a} it evaluates {Taylor(...)} and assigns the result to {a}. The next time
you call {a} it immediately returns the result.
{AssignGlobalLazy} is called for {%} each time {%} changes.

The following example demonstrates the sequence of execution:

In> AssignGlobalLazy(test,Hold(Write("hello")))
Result: True

The text "hello" is not written out to screen yet. However, evaluating
the variable {test} forces the expression to be evaluated:

In> test
Result: True
Side Effects:
"hello"

*E.G.

In> Assign(a,Hold(2+3))
Result: True

In> a
Result: 2+3

In> AssignGlobalLazy(a,Hold(2+3))
Result: True

In> a
Result: 5


*SEE Assign, Unassign, Local, ?, I
Note: ? works only in the mathpiper console!

*SOURCE org/mathpiper/builtin/procedures/core/AssignGlobalLazy.java
==========
*CMD Assigned? --- determine if a variable has a value assigned to it
*CORE
*CALL
	Assigned?(var)

*PARMS

{var} -- variable to test

*DESC

This function tests whether the variable "var" has a value assigned to it. 
The argument "var" is not evaluated.

*E.G.

In> Assigned?(x);
Result: False;

In> x := 5;
Result: 5;

In> Assigned?(x);
Result: True;

*SEE Atom?

*SOURCE org/mathpiper/builtin/procedures/core/Assigned_.java
==========
*CMD Atom? --- test for an atom
*CORE
*CALL
	Atom?(expr)

*PARMS

{expr} -- expression to test

*DESC

This function tests whether "expr" is an atom. Numbers, strings, and
variables are all atoms.

*E.G.

In> Atom?('x+5);
Result: False;

In> Atom?(5);
Result: True;

*SEE Procedure?, Number?, String?

*SOURCE org/mathpiper/builtin/procedures/core/Atom_.java
==========
*A {/`}
*CMD Backquoting --- macro expansion (LISP-style backquoting)
*CORE
*CALL
	/`(expression)

*PARMS

{expression} -- expression containing "{@var}" combinations to substitute the value of variable "{var}"

*DESC

Backquoting is a macro substitution mechanism. A backquoted {expression}
is evaluated in two stages: first, variables prefixed by {@} are evaluated
inside an expression, and second, the new expression is evaluated.

To invoke this functionality, a backquote operator {/`} needs to be placed in front of
an expression. Parentheses around the expression are needed because the
backquote binds tighter than other operators.

The expression should contain some variables (assigned atoms) with the special
prefix operator {@}. Variables prefixed by {@} will be evaluated even if they
are inside function arguments that are normally not evaluated (e.g. functions
declared with {HoldArgument}).

If the {@var} pair is in place of a function name,
e.g. "{@f(x)}", then at the first stage of evaluation the function name itself
is replaced, not the return value of the function (see example); so at the
second stage of evaluation, a new function may be called. If the function is 
single quoted, then the unreplaced function is evaluated (Note: there needs
to be a space between the @ character and the ' character.

One way to view backquoting is to view it as a parametric expression
generator. {@var} pairs get substituted with the value of the variable {var}
even in contexts where nothing would be evaluated. This effect can be also
achieved using {ListToProcedure} and {Hold} but the resulting code is much more
difficult to read and maintain.

This operation is relatively slow since a new expression is built
before it is evaluated, but nonetheless backquoting is a powerful mechanism
that sometimes allows to greatly simplify code.

*E.G.

This example defines a function that automatically evaluates to a number as
soon as the argument is a number (a lot of functions  do this only when inside
a {NM(...)} section).

In> Decl(f1,f2) :=  /`(@f1(x_Number?) --> NM(@f2(x)));
Result: True;

PKHG_TODO 17-11-2013: better example?! See the quote before sin!
In> Decl('sin,SinN)
Result: True

In> sin(1)
Result: 0.8414709848

PKHG_TODO 17-11-2013 Sin does not exist now
In> Decl(nSin,Sin)
Result: True;

In> Sin(1)
Result: Sin(1);

In> nSin(1)
Result: 0.8414709848;

This example assigns the expression {func(value)} to variable {var}. Normally
the first argument of {Assign} would be unevaluated.

In> SetF(var,func,value) := /`(Assign(@var,@func(@value)));
Result: True;

In> SetF(a,Sin,x)
Result: True;

In> a
Result: Sin(x);

In> /`(@ 'Echo(3))
Result: True
Side Effects:
3 

*SEE /``, MacroAssign, MacroLocal, MacroRulebaseHoldArguments, Hold, HoldArgument, MacroRulebaseHoldArguments, MacroExpand

*SOURCE org/mathpiper/builtin/procedures/core/BackQuote.java
==========
*CMD BitAnd --- bitwise "and" operation
*CORE
*CALL
	BitAnd(n,m)


*DESC
This function returns the bitwise "and"
of two numbers.

*SEE BitOr, BitXor, BitNot


*SOURCE org/mathpiper/builtin/procedures/core/BitAnd.java
==========
*CMD BitCount --- Returns the number of bits as given by variable passed.
*CORE
*CALL
	BitCount(var)

*DESC
Returns the given value or variable's number of bits in memory.  




*SOURCE org/mathpiper/builtin/procedures/core/BitCount.java
==========
*CMD BitNot --- bitwise 'not' operation
*CORE
*CALL
	BitNot(n)


*DESC
This function returns the bitwise "not"
of a number.

*SEE BitOr, BitXor, BitAnd


*SOURCE org/mathpiper/builtin/procedures/core/BitNot.java
==========
*CMD BitOr --- bitwise "or" operation
*CORE
*CALL
	BitOr(n,m)

*DESC
This function returns the bitwise "or"
of two numbers.

*SEE BitAnd, BitXor, BitNot


*SOURCE org/mathpiper/builtin/procedures/core/BitOr.java
==========
*CMD BitXor --- bitwise "xor" operation
*CORE
*CALL
	BitXor(n,m)

*DESC
This function returns the bitwise "xor"
of two numbers.

*SEE BitAnd, BitOr


*SOURCE org/mathpiper/builtin/procedures/core/BitXor.java
==========
*CMD BitsToDigits --- changes 2 small ints to digits
*CORE
*CALL
	BitsToDigits(int1,int2)

*DESC
Takes two small ints and changes them into digits to be expressed in binary.

*EXAMPLES
In> BitsToDigits(4, 10) 
Result: 1

In> BitsToDigits(7, 10) 
Result: 2

In> BitsToDigits(8, 16) 
Result: 2

*SEE BitsToDigits


*SOURCE org/mathpiper/builtin/procedures/core/BitsToDigits.java
==========
*CMD Bodied --- define procedure syntax (bodied procedure)
*CORE
*CALL
	Bodied("op", precedence)

*PARMS

{"op"} -- string, the name of a procedure

{precedence} -- nonnegative integer (evaluated)

*DESC

Declares a special syntax for the procedure to be parsed as a bodied operator.

"Bodied" procedures have all arguments except the first one inside parentheses and the last argument outside, for example:
	For(pre, condition, post) statement;
Here the procedure {For} has 4 arguments and the last argument is placed outside the parentheses.
The {precedence} of a "bodied" procedure refers to how tightly the last argument is bound to the parentheses.
This makes a difference when the last argument contains other operators.
For example, when taking the derivative
	D(x) Sin(x)+Cos(x)
both {Sin} and {Cos} are under the derivative because the bodied procedure {D} binds less tightly than the infix operator "{+}".

Function name can be any string but meaningful usage and readability would
require it to be either made up entirely of letters or entirely of non-letter
characters (such as "+", ":" etc.).
Precedence is optional (will be set to 0 by default).

*E.G.
In> todo

*SEE Bodied?, PrecedenceGet, Infix, Postfix, Prefix

*SOURCE org/mathpiper/builtin/procedures/core/Bodied.java
==========
*CMD Bodied? --- check for procedure syntax
*CORE
*CALL
	Bodied?("op")

*PARMS

{"op"} -- string, the name of a procedure

*DESC

Check whether the procedure with given name {"op"} has been declared as a
"bodied", operator, and  return {True} or {False}.

*E.G.

In> Bodied?("While");
Result: True;

In> Bodied?("Sin");
Result: False;

*SEE PrecedenceGet,Infix?,Postfix?,Prefix?

*SOURCE org/mathpiper/builtin/procedures/core/Bodied_.java
==========
*CMD Break --- break out of a loop
*CORE
*CALL

    Break()

*DESC

If Break is executed inside of a While, Until, For, or ForEach loop, it will
cause the loop to be exited.

*E.G.
/%mathpiper
x := 1;

While(x <=? 10)
{
    Echo(x);

    If(x =? 5,) Break();

    x++;
};
/%/mathpiper

    /%output,sequence="5",timestamp="2013-12-09 12:41:41.334",preserve="false"
      Result: True
      
      Side Effects:
      1 
      2 
      3 
      4 
      5 
      
.   /%/output

*SEE While, DoWhile, For, ForEach, Continue

*SOURCE org/mathpiper/builtin/procedures/core/Break.java
==========
*CMD BuiltinAssoc --- Takes a key and argument and returns element at that key
*CORE
*CALL
	BuiltinAssociation(key,argument)

*DESC
Takes a key and argument and returns the association or assigns the argument given to
the associated key.



*SOURCE org/mathpiper/builtin/procedures/core/BuiltinAssociation.java
==========
*CMD BuiltinPrecisionGet --- get the current precision
*CORE
*CALL
	BuiltinPrecisionGet()

*DESC

This command returns the current precision, as set by {BuiltinPrecisionSet}.

*E.G.

In> BuiltinPrecisionGet();
Result: 10;

In> BuiltinPrecisionSet(20);
Result: True;

In> BuiltinPrecisionGet();
Result: 20;

*SEE BuiltinPrecisionSet, NM


*SOURCE org/mathpiper/builtin/procedures/core/BuiltinPrecisionGet.java
==========
*CMD BuiltinPrecisionSet --- set the precision
*CORE
*CALL
	BuiltinPrecisionSet(n)

*PARMS

{n} -- integer, new value of precision

returns old precsion!

*DESC

This command sets the number of decimal digits to be used in calculations.
All subsequent floating point operations will allow for
at least {n} digits of mantissa.

This is not the number of digits after the decimal point.
For example, {123.456} has 3 digits after the decimal point and 6 digits of mantissa.
The number {123.456} is adequately computed by specifying {BuiltinPrecisionSet(6)}.

The call {BuiltinPrecisionSet(n)} will not guarantee that all results are precise to {n} digits.

When the precision is changed, all variables containing previously calculated values
remain unchanged.
The {BuiltinPrecisionSet} function only makes all further calculations proceed with a different precision.

Also, when typing floating-point numbers, the current value of {BuiltinPrecisionSet} is used to implicitly determine the number of precise digits in the number.

*E.G.

In> NM(Sin(1))
Result: 0.8414709848;

In> BuiltinPrecisionSet(20)
Result: 10;

In> x:=NM(Sin(1))
Result: 0.84147098480789650665;

The value {x} is not changed by a {BuiltinPrecisionSet()} call:

In> [ BuiltinPrecisionSet(10); x; ]
Result: 0.84147098480789650665;

The value {x} is rounded off to 10 digits after an arithmetic operation:

In> x+0.
Result: 0.8414709848;

In the above operation, {0.} was interpreted as a number which is precise to 10 digits (the user does not need to type {0.0000000000} for this to happen).
So the result of {x+0.} is precise only to 10 digits.

*SEE BuiltinPrecisionGet, NM


*SOURCE org/mathpiper/builtin/procedures/core/BuiltinPrecisionSet.java
==========
*CMD Car --- the first element of a Lisp list
*CORE
*CALL
	Car(lispList)

*PARMS

{lispList} -- a lisp list

*DESC

This function returns the first element of a Lisp list. An error is
returned if {lispList} is an atom.

*E.G.

In> Car([_a,_b,_c])
Result: List

reason why you see List:
In> UnparseLisp([1,3,4])
Result: [1,3,4]
Side Effects:
(List 1 3 4)


*SEE Cdr

*SOURCE org/mathpiper/builtin/procedures/core/Car.java
==========
*CMD Cdr --- the rest of a Lisp list
*CORE
*CALL
	Cdr(lispList)

*PARMS

{lispList} -- a lisp list

*DESC

This function returns the rest of a Lisp list.

*E.G.

In> Cdr(Car([_a,_b,_c]))
Result: _a

*SEE Car

*SOURCE org/mathpiper/builtin/procedures/core/Cdr.java
==========
*CMD CeilN --- smallest integer not smaller than xx (arbitrary-precision math function)
*CORE
*CALL
    CeilN(xx)

*DESC

This command performs the calculation of an elementary mathematical
function.  The arguments <i>must</i> be numbers.  The reason for the
postfix {N} is that the library needs to define equivalent non-numerical
functions for symbolic computations, such as {Exp}, {Sin}, etc.

Note that all xxxN functions accept integers as well as floating-point numbers.
The resulting values may be integers or floats.  If the mathematical result is an
exact integer, then the integer is returned.  For example, {Sqrt(25)} returns
the integer {5}, and {Power(2,3)} returns the integer {8}.  In such cases, the
integer result is returned even if the calculation requires more digits than set by
{BuiltinPrecisionSet}.  However, when the result is mathematically not an integer,
the functions return a floating-point result which is correct only to the current precision.

*E.G.
In>
Result:

*See FloorN


*SOURCE org/mathpiper/builtin/procedures/core/Ceil.java
==========
*CMD Check --- throw an exception if a predicate expression returns False
*CORE
*CALL
	Check(predicate, "exceptionMessage")

*PARMS

{predicate} -- expression returning {True} or {False}

{"exceptionMessage"} -- string which holds the exception message

*DESC
If {predicate} does not evaluate to {True},
the current operation will be stopped and an exception will be thrown.
This facility can be used to assure that some condition
is satisfied during evaluation of expressions.

*E.G.

In> Check(Integer?(2.3), "The argument must be an integer.")
Result: Exception
Exception: The argument must be an integer.


*SEE CheckType


*SOURCE org/mathpiper/builtin/procedures/core/Check.java
==========
*CMD CheckParametersMadeLocal --- checks for procedure parameters being made local

*CALL

    CheckParametersMadeLocal(procedureName, parametersList, body)

*PARMS
{procedureName} -- the name of the procedure being defined

{parameterssList} -- the procedure's parameters

{body} -- the procedure's body

*DESC
Checks for procedure parameters being made local.

*EXAMPLES
In> CheckParametersMadeLocal("foo", ["one", "two", "three"], '{ Local(one); }) 
Result: Exception
Exception: The variable "one" is a parameter in procedure "foo", and parameters cannot be made local.  Starting at index 0.


*SOURCE org/mathpiper/builtin/procedures/core/CheckParametersMadeLocal.java
==========
*CMD CommonLispTokenizer --- Not yet implemented
*CORE
*CALL
	CommonLispTokenizer()

*DESC
Not yet implemented


*SOURCE org/mathpiper/builtin/procedures/core/CommonLispTokenizer.java
==========
*CMD Concat --- concatenate lists
*CORE
*CALL
	Concat(list1, list2, ...)

*PARMS

{list1}, {list2}, ... -- lists to concatenate

*DESC

The lists "list1", "list2", ... are evaluated and
concatenated. The resulting big list is returned.

*EXAMPLES
In> Concat(["a","b"], ["c","d"]) 
Result: ["a","b","c","d"]

In> Concat([5,7], ["a","b","c"], [["Blue"]]) 
Result: [5,7,"a","b","c",["Blue"]]

*SEE ConcatStrings, :, Insert

*SOURCE org/mathpiper/builtin/procedures/core/Concatenate.java
==========
*CMD ConcatStrings --- concatenate strings
*CORE
*CALL
	ConcatStrings(strings)

*PARMS

{strings} -- one or more strings

*DESC

Concatenates strings.

*E.G.

In> ConcatStrings("a","b","c")
Result: "abc";

*SEE :

*SOURCE org/mathpiper/builtin/procedures/core/ConcatenateStrings.java
==========
*CMD Constant --- make a symbol a constant or a nonconstant
*CALL
	Constant(symbol, boolean)

*PARMS

{symbol} -- the symbol to be modified

{boolean} -- True means make the symbol constant, and False means make the symbol nonconstant

*DESC
This function makes a symbol a constant or a nonconstant.

*E.G.
In> rock
Result: Exception
Exception: Error: The variable <rock> does not have a value assigned to it. Starting at index 0.

In> Constant('rock, True);
Result: True

In> rock
Result: rock

In> Constant(rock, False);
Result: True

In> rock
Result: Exception
Exception: Error: The variable <rock> does not have a value assigned to it. Starting at index 0.

*SOURCE org/mathpiper/builtin/procedures/core/Constant.java
==========
*CMD Continue --- skips executing the remainder of code in this loop iteration and begins the next iteration
*CORE
*CALL

    Continue()

*DESC

If Continue is executed inside of a While, Until, or For loop, all the code between
the continue command and the end of the loop will be skipped and the next loop iteration
will be started.

*E.G.

/%mathpiper

x := 0;

While(x <? 8)
{
    x++;

    Decide(x =? 5, Continue());

    Echo(x);
};

/%/mathpiper

    /%output,preserve="false"
      Result: True

      Side Effects:
      1
      2
      3
      4
      6
      7
      8
.   /%/output

*SEE While, DoWhile, For, Break

*SOURCE org/mathpiper/builtin/procedures/core/Continue.java
==========
*CMD CosD --- double-precision math function
*CORE
*CALL
	CosD(x)

*PARMS
{x} -- a number

*DESC
A double precision version of the Cos function.


*EXAMPLES
In> CosD(.7) 
Result: 0.7648421873

In> CosD(-1.2) 
Result: 0.3623577545
*SEE SinD, TanD, CscD, SecD, CotD, ArcSinD, ArcCosD, ArcTanD, ArcCscD, ArcSecD, ArcCotD

*SOURCE org/mathpiper/builtin/procedures/core/CosD.java
==========
*CMD CotD --- double-precision math function
*CORE
*CALL
	CotD(x)

*PARMS
{x} -- a number

*DESC
A double precision version of the Cot function.


*EXAMPLES
In> CotD(.7) 
Result: 1.187241832

In> CotD(-1.2) 
Result: -0.3887795694
*SEE SinD, CosD, TanD, CscD, SecD, ArcSinD, ArcCosD, ArcTanD, ArcCscD, ArcSecD, ArcCotD

*SOURCE org/mathpiper/builtin/procedures/core/CotD.java
==========
*CMD CscD --- double-precision math function
*CORE
*CALL
	CscD(x)

*PARMS
{x} -- a number

*DESC
A double precision version of the Csc function.

*EXAMPLES
In> CscD(.7) 
Result: 1.552270327

In> CscD(-1.2) 
Result: -1.072916378
*SEE SinD, CosD, TanD, SecD, CotD, ArcSinD, ArcCosD, ArcTanD, ArcCscD, ArcSecD, ArcCotD

*SOURCE org/mathpiper/builtin/procedures/core/CscD.java
==========
*CMD CurrentFile --- return current input file
*CORE
*CALL
	CurrentFile()

*DESC

The procedures {CurrentFile} returns a string
with the file name of the current file .

This function is most useful in batch file calculations, where
there is a need to determine at which line an error occurred.
One can define a function

	tst() := Echo([CurrentFile(),CurrentLine()]);
which can then be inserted into the input file at various places,
to see how far the interpreter reaches before an error occurs.

*SEE Echo, CurrentLine


*SOURCE org/mathpiper/builtin/procedures/core/CurrentFile.java
==========
*CMD CurrentLine --- return current line number on input
*CORE
*CALL
	CurrentLine()

*DESC

The procedure {CurrentLine} returns a string
with the current line of the input file.

These functions are most useful in batch file calculations, where
there is a need to determine at which line an error occurred.
One can define a function

	tst() := Echo([CurrentFile(),CurrentLine()]);
which can then be inserted into the input file at various places,
to see how far the interpreter reaches before an error occurs.

*SEE Echo, CurrentFile


*SOURCE org/mathpiper/builtin/procedures/core/CurrentLine.java
==========
*CMD CustomEval --- Not yet implemented
*CORE
*CALL
	CustomEval()

*DESC
Not yet implemented


*SOURCE org/mathpiper/builtin/procedures/core/CustomEval.java
==========
*CMD CustomEvalExpression --- Not yet implemented
*CORE
*CALL
	CustomEvalExpression()

*DESC
Not yet implemented


*SOURCE org/mathpiper/builtin/procedures/core/CustomEvalExpression.java
==========
*CMD CustomEvalLocals --- Not yet implemented
*CORE
*CALL
	CustomEvalLocals()

*DESC
Not yet implemented


*SOURCE org/mathpiper/builtin/procedures/core/CustomEvalLocals.java
==========
*CMD CustomEvalResult --- Not yet implemented
*CORE
*CALL
	CustomEvalResult()

*DESC
Not yet implemented


*SOURCE org/mathpiper/builtin/procedures/core/CustomEvalResult.java
==========
*CMD CustomEvalStop --- Not yet implemented
*CORE
*CALL
	CustomEvalStop()

*DESC
Not yet implemented


*SOURCE org/mathpiper/builtin/procedures/core/CustomEvalStop.java
==========
*CMD DebugFile --- Can't call this procedure in Non debug version
*CORE
*CALL
	DebugFile()

*DESC
Can't call this procedure in non-debug version


*SOURCE org/mathpiper/builtin/procedures/core/DebugFile.java
==========
*CMD Decide --- used to make decisions
*CORE
*CALL
	Decide(pred, then)
	Decide(pred, then, else)

*PARMS

{pred} -- predicate to test

{then} -- expression to evaluate if "pred" is {True}

{else} -- expression to evaluate if "pred" is {False}

*DESC

This command implements a branch point. The predicate "pred" is
evaluated, which should result in either {True} or {False}. In the first case, the expression "then" is
evaluated and returned. If the predicate yields {False}, the expression "else" (if present) is evaluated and
returned. If there is no "else" branch (i.e. if the first calling
sequence is used), the {Decide} expression returns {False}.

*E.G.

The sign function is defined to be 1 if its argument is positive and
-1 if its argument is negative. A possible implementation is

In> mysign(x) := Decide (PositiveReal?(x), 1, -1);
Result: True;

In> mysign(Pi);
Result: 1;

In> mysign(-2.5);
Result: -1;
Note that this will give incorrect results, if "x" cannot be
numerically approximated.

In> mysign(_a);
Result: -1;
Hence a better implementation would be

In> mysign(_x)_Number?(NM(x)) --> Decide \
	  (PositiveReal?(x), 1, -1);
Result: True;

*SOURCE org/mathpiper/builtin/procedures/core/Decide.java
==========
*CMD Decimal? --- test to see if a number is a decimal
*CORE
*CALL
	Decimal?(expr)

*PARMS

{expr} -- expression to test

*DESC

This function tests whether "expr" is a decimal number. There are two kinds
of numbers, integers (e.g. 6) and decimals (e.g. -2.75 or 6.0).
*E.G.

In> Decimal?(3.25);
Result: True;

In> Decimal?(6);
Result: False;

In> Decimal?(1/2);
Result: False;

In> Decimal?(3.2/10);
Result: True;

*SEE String?, Atom?, Integer?, PositiveNumber?, NegativeNumber?, Number?

*SOURCE org/mathpiper/builtin/procedures/core/Decimal_.java
==========
*CMD DefaultDirectory --- add directory to path for MathPiper scripts
*CORE
*CALL
	DefaultDirectory(path)

*PARMS

{path} -- a string containing a full path where MathPiper script files reside

*DESC

When loading files, MathPiper is also allowed to
look in the folder "path". {path} will be prepended
to the file name before trying to load the file.
This means that "path" should end with a forward slash (under Unix-like
operating systems).

MathPiper car tries to load a file from the current
directory, and otherwise it tries to load from
directories defined with this function, in the
order they are defined. Note there will be at least one directory
specified at start-up time, defined during compilation. This
is the directory MathPiper searches for the initialization scripts
and standard scripts.

MathPiper allows you to configure a few things at startup. The file
{~/.mathpiperrc} is written in the MathPiper language and
will be executed when MapthPiper is run. This function
can be useful in the {~/.MathPiperrc} file.

*E.G.

In> DefaultDirectory("/home/user/myscripts/");
Result: True;


*SOURCE org/mathpiper/builtin/procedures/core/DefaultDirectory.java
==========
*CMD DefaultTokenizer --- select the default syntax tokenizer for parsing the input
*CORE
*CALL
	DefaultTokenizer()

*DESC

A "tokenizer" is an internal routine in the kernel that parses the input into MathPiper expressions.
This affects all input typed in by a user at the prompt and also the input redirected from files or strings using {PipeFromFile} and {FromString} and read using {Read} or {ParseMathPiperToken}.

The MathPiper environment currently supports some experimental tokenizers for
various syntaxes. {DefaultTokenizer} switches to the tokenizer used for
default MathPiper syntax.
Note that setting the tokenizer is a global side effect.
One typically needs
to switch back to the default tokenizer when finished reading the special syntax.

Care needs to be taken when kernel errors are raised during a non-default tokenizer operation (as with any global change in the environment).
Errors need to be
caught with the {TrapError} function. The error handler code should re-instate
the default tokenizer,
or else the user will be unable to continue the session
(everything a user types will be parsed using a non-default tokenizer).


*E.G. notest

In>


*SEE XmlExplodeTag, ParseMathPiperToken, PipeFromFile, PipeFromString, XmlTokenizer

*SOURCE org/mathpiper/builtin/procedures/core/DefaultTokenizer.java
==========
*CMD DefinedConstant? --- test for a defined constant
*STD
*CALL
        DefinedConstant?(expression)

*PARMS

{expression} -- expression to test

*DESC

This procedure tests if the argument is a defined constant.

*E.G.

In> DefinedConstant?(All)
Result: True

*SEE Constant?, UnderscoreConstant?

*SOURCE org/mathpiper/builtin/procedures/core/DefinedConstant_.java
==========
*CMD Delete --- delete an element from a list
*CORE
*CALL
	Delete(list, n)

*PARMS

{list} -- list from which an element should be removed

{n} -- index of the element to remove

*DESC

This command deletes the n-th element from "list". The first
parameter should be a list, while "n" should be a positive integer
less than or equal to the length of "list". The entry with index
"n" is removed (the first entry has index 1), and the resulting list
is returned.

*EXAMPLES
In> Delete([_a,_b,_c,[1,2,3],_e,_f], 4) 
Result: [_a,_b,_c,_e,_f]

*SEE Delete!, Insert, Replace

*SOURCE org/mathpiper/builtin/procedures/core/Delete.java
==========
*CMD Delete! --- delete an element destructively from a list
*CORE
*CALL
	Delete!(list, n)

*PARMS

{list} -- list from which an element should be removed

{n} -- index of the element to remove

*DESC

This is the destructive counterpart of {Delete}. This
command yields the same result as the corresponding call to
{Delete}, but the original list is modified. So if a
variable is bound to "list", it will now be bound to the list with
the n-th entry removed.

Destructive commands run faster than their nondestructive counterparts
because the latter copy the list before they alter it.

*E.G.

In> lst := [_a,_b,_c,_d,_e,_f];
Result: [_a,_b,_c,_d,_e,_f]

In> Delete(lst, 4);
Result: [_a,_b,_c,_e,_f]

In> lst;
Result: [_a,_b,_c,_d,_e,_f]

In> Delete!(lst, 4);
Result: [_a,_b,_c,_e,_f]

In> lst;
Result: [_a,_b,_c,_e,_f]

*SEE Delete, Insert!, Replace!

*SOURCE org/mathpiper/builtin/procedures/core/Delete__.java
==========
*CMD DigitsToBits --- calculates the number of bits needed to represent an x digit integer
*CORE
*CALL
    DigitsToBits(digitsLength,base)
    
*PARMS

{digitsLength} -- length of integer to translate into minimum required bits

{base} -- base of number in question

*DESC

The procedure {DigitsToBits} calculates the
minimum required number of bits required to
represent any integer with a length of {digitsLength} in
a base of {base}. 

*EXAMPLES
In> DigitsToBits(1, 10) 
Result: 4

In> DigitsToBits(2,10) 
Result: 7

In> DigitsToBits(2,16) 
Result: 8

*SEE DigitsToBits


*SOURCE org/mathpiper/builtin/procedures/core/DigitsToBits.java
==========
*CMD DivideN --- divide two numbers (arbitrary-precision math function)
*CORE
*CALL
	DivideN(x,y)

*DESC

This command performs the calculation of an elementary mathematical
function.  The arguments <i>must</i> be numbers.  The reason for the
postfix {N} is that the library needs to define equivalent non-numerical
functions for symbolic computations, such as {Exp}, {Sin}, etc.

Note that all xxxN functions accept integers as well as floating-point numbers.
The resulting values may be integers or floats.  If the mathematical result is an
exact integer, then the integer is returned.  For example, {Sqrt(25)} returns
the integer {5}, and {Power(2,3)} returns the integer {8}.  In such cases, the
integer result is returned even if the calculation requires more digits than set by
{BuiltinPrecisionSet}.  However, when the result is mathematically not an integer,
the functions return a floating-point result which is correct only to the current precision.

*E.G.
In>
Result:


*SOURCE org/mathpiper/builtin/procedures/core/Divide.java
==========
*CMD Until --- loop while a condition is met

*CALL
        DoWhile(pred) body

*PARMS

{pred} -- predicate deciding whether to stop

{body} -- expression to loop over

*DESC

Keep on evaluating "body" until "pred" becomes {False}. More precisely, {DoWhile} first
evaluates the expression "body". Then the predicate "pred" is
evaluated, which should yield either {True} or {False}. In the former case, the expressions "body"
and "pred" are again evaluated and this continues as long as
"pred" is {True}. As soon as "pred" yields {False}, the loop terminates and {DoWhile} returns {True}.

The main difference with {While} is that {DoWhile} always evaluates the body at 
least once, but {While} may not evaluate the body at all.
{DoWhile}
command can be compared to the {do ... while}
construct in the programming language C.

*E.G.

/%mathpiper
x := 1;

DoWhile(x <? 5)
{
   Echo(x); 
   x++;
};
/%/mathpiper

    /%output,sequence="4",timestamp="2013-09-16 22:36:36.156",preserve="false"
      Result: True
      
      Side Effects:
      1 
      2 
      3 
      4 
      
.   /%/output

*SEE While, For, ForEach, Break, Continue

*SOURCE org/mathpiper/builtin/procedures/core/DoWhile.java
==========
*CMD DumpNumber --- prints the implementation details of a number
*CORE
*CALL
	DumpNumber(x)

*PARMS
 * 
{x} -- an integer or decimal number.


*DESC

This function prints the implementation details of an integer or decimal number.

*E.G.
In> DumpNumber(4)
Result> [["type","BigInteger"],["value",4]]

In> DumpNumber(3.2)
Result> [["type","BigDecimal"],["value",3.2],["precision",2],["unscaledValue",32],["scale",1]]

In> DumpNumber(3.2)["precision"]
Result> 2


*SOURCE org/mathpiper/builtin/procedures/core/DumpNumber.java
==========
*CMD EditDistance --- calculates the edit distance between two strings
*CORE
*CALL
	EditDistance(s1, s2)

*PARMS
 {s1} - a string
 {s2} - a string

*DESC
This procedure calculates the edit distance between two strings.

*E.G.
In> EditDistance("Hello", "hello")
Result: 1


*SOURCE org/mathpiper/builtin/procedures/core/EditDistance.java
==========
*CMD Equal? --- check equality
*CORE
*CALL
	Equal?(a,b)

*DESC
Compares evaluated {a} and {b} recursively
(stepping into expressions). So "Equal?(a,b)" returns
"True" if the expressions would be printed exactly
the same, and "False" otherwise.

*SEE GreaterThan?, LessThan?, StringCompareNatural

*SOURCE org/mathpiper/builtin/procedures/core/Equal_.java
==========
*CMD Equivales? ==? --- logical equivalence
*CORE
*CALL
	a1 ==? a2
	Equivales?(a1, a2)

*PARMS

{a}1, {a}2 -- boolean values (may evaluate to {True} or {False})

*DESC

This function implements the truth table for equivalence:

{True} ==? {True} returns {True}.

{True} ==? {False} returns {False}.

{False} ==? {True} returns {False}.

{False} ==? {False} returns {True}.

*E.G.

In> True ==? False
Result: False

*SEE And?, Or?, Not?, Implies?

*SOURCE org/mathpiper/builtin/procedures/core/Equivales_.java
==========
*CMD Eval --- force evaluation of expression
*CORE
*CALL
	Eval(expr)

*PARMS

{expr} -- expression to evaluate

*DESC

This function explicitly requests an evaluation of the expression
"expr", and returns the result of this evaluation.

In the examples below, the variable {a} is bound to {x},
and {x} is bound to 5. Hence evaluating {a} will give {x}. Only when an extra
evaluation of {a} is requested, the value 5 is
returned.

Note that the behavior would be different if we had exchanged the
assignments. If the assignment {a := x} were given
while {x} had the value 5, the variable {a} would also get the value 5 because the assignment
operator {:=} evaluates the right-hand side.

*E.G.

In> a := x;
Result: x;

In> x := 5;
Result: 5;

In> a;
Result: x;

In> Eval(a);
Result: 5;



*SEE Hold, HoldArgument, :=

*SOURCE org/mathpiper/builtin/procedures/core/Eval.java
==========
*CMD ExceptionCatch --- catches exceptions
*CORE
*CALL
	ExceptionCatch(expression, exceptionType, exceptionHandler)

*PARMS

{expression} -- expression to evaluate (causing potential error)

{exceptionType} -- a string that holds a ; separated list of exception types to catch

{exceptionHandler} -- expression which is evaluated to handle the exception

*DESC
ExceptionCatch evaluates its argument {expression} and returns the
result of evaluating {expression}. If an exception is thrown,
{errorHandler} is evaluated, returning its return value instead. If {exceptionType}
is "", then all exceptions are caught. If {exceptionType} is "FOO", then only exceptions
of type "FOO" will be caught. If {exceptionType} is "FOO;BAR", then only exceptions
of type "FOO" and type "BAR" will be caught. 

{ExceptionGet} can be used to obtain information about the caught exception.


 
*E.G.

In> ExceptionCatch(Check(1 =? 2, "", "Throwing a test exception."), "", "This string is returned if an exception is thrown.");
Result: "This string is returned if an exception is thrown."




/%mathpiper,title="Example of how to use ExceptionCatch and ExceptionGet in test code (long version)."
{
	Local(exception);
	
	exception := False;
	
	ExceptionCatch(Check(1 =? 2, "", "Throwing a test exception."), "", exception := True);
	
	Verify(exception, True);

};
/%/mathpiper

    /%output,sequence="8",timestamp="2014-10-09 17:15:18.472",preserve="false"
      Result: True
.   /%/output





/%mathpiper,title="Example of how to use ExceptionCatch and ExceptionGet in test code (short version)."

//ExceptionGet returns False if there is no exception or an association list if there is.
Verify( ExceptionCatch(Check(1 =? 2, "", "Throwing a test exception."), "", ExceptionGet()) =? False, False);

/%/mathpiper

    /%output,preserve="false"
      Result: True
.   /%/output





/%mathpiper,title="Example of how to handle a caught exception."

TestFunction(x) :=
{

    Check(Integer?(x), "The argument must be an integer.");

};



caughtException := ExceptionCatch(TestFunction(1.2), "", ExceptionGet());

Echo(caughtException);

NewLine();

Echo("Type: ", caughtException["type"]);

NewLine();

Echo("Message: ", caughtException["message"]);


/%/mathpiper

    /%output,sequence="11",timestamp="2014-10-09 17:19:05.509",preserve="false"
      Result: True
      
      Side Effects:
      [["type","Unspecified"],["message","Argument Error: The argument must be an integer. "],["exceptionObject",class org.mathpiper.exceptions.EvaluationException]] 
      
      Type: Unspecified
      
      Message: Argument Error: The argument must be an integer. 
      
.   /%/output

*SEE Check, ExceptionThrow, ExceptionGet


*SOURCE org/mathpiper/builtin/procedures/core/ExceptionCatch.java
==========
*CMD ExceptionGet --- returns the exception object which was thrown.
*CORE
*CALL
	ExceptionGet()

*DESC

ExceptionGet is designed to be used in the {exceptionHandler} argument of {ExceptionCatch} and it
 returns an association list which contains information about the caught exception.  If {ExceptionGet} is
 evaluated outside of {ExceptionCatch}, it always returns {False};
{ExceptionCatch} and {ExceptionGet} are used in combination to write
an exception handler.

*E.G.

In> ExceptionGet()
Result: False


 

In> ExceptionCatch(Check(1 =? 2, "Throwing a test exception."), Echo(ExceptionGet()))
Result: True
Side Effects:
[["type","Unspecified"],["message","Test Error: Throwing a test exception. "],["exceptionObject",class org.mathpiper.exceptions.EvaluationException]]

*SEE Check, ExceptionThrow, ExceptionCatch


*SOURCE org/mathpiper/builtin/procedures/core/ExceptionGet.java
==========
*CMD ExceptionThrow --- throw an exception of a given type
*CORE
*CALL
	ExceptionThrow("type", "exceptionMessage")

*PARMS

{"type"} -- a string that contains the type of the expression

{"exceptionMessage"} -- string which holds the exception message

*DESC
The current operation is stopped and an exception will be thrown.

Exceptions that are thrown by this function can be caught by the {ExceptionCatch} function.



*E.G.

In> ExceptionThrowThrow("EXAMPLE", "This is an example exception.")
Result: Exception
Exception: The argument must be an integer.


*SEE ExceptionCatch, ExceptionGet, Check


*SOURCE org/mathpiper/builtin/procedures/core/ExceptionThrow.java
==========
*CMD FilterSideEffects --- remove side effect output

*CALL
    FilterSideEffects() body

*PARMS

{body} -- expression to be evaluated

*DESC

The expressions in "body" are evaluated and any side effects
that are produced by these expressions is removed.

*EXAMPLES
In> FilterSideEffects() {Echo("Hello"); 3;} 
Result: 3


*SOURCE org/mathpiper/builtin/procedures/core/FilterSideEffects.java
==========
*CMD FindProcedure --- find the library file where a procedure is defined
*CORE
*CALL
	FindProcedure(procedure)

*PARMS

{procedure} -- string, the name of a procedure

*DESC

This procedure is useful for quickly finding the file where a standard library
procedure is defined. It is likely to only be useful for developers. The
procedure {FindProcedure} scans the {.def} files that were loaded at start-up.
This means that procedures that are not listed in {.def} files will not be found with {FindProcedure}.

*E.G.

In> FindProcedure("Sum")
Result: "sums.rep/code.ys";

In> FindProcedure("Integrate")
Result: "integrate.rep/code.ys";


*SOURCE org/mathpiper/builtin/procedures/core/FindProcedure.java
==========
*CMD First --- the first element of a list
*CORE
*CALL
	First(list)

*PARMS

{list} -- a list

*DESC

This function returns the first element of a list. If it is applied to
a general expression, it returns the first operand. An error is
returned if "list" is an atom.

*EXAMPLES
In> First([_a,_b,_c]) 
Result: _a

In> f(a,b,c) := [a,b,c] 
Result: True

In> First(f(_a,3,4)) 
Result: _a

*SEE Rest, Length

*SOURCE org/mathpiper/builtin/procedures/core/First.java
==========
*CMD FlatCopy --- copy the top level of a list
*CORE
*CALL
	FlatCopy(list)

*PARMS

{list} -- list to be copied

*DESC

A copy of "list" is made and returned. The list is not recursed
into, only the car level is copied. This is useful in combination
with the destructive commands that actually modify lists in place (for
efficiency).

*EXAMPLES
The following shows a possible way to define a command that reverses a

list nondestructively.

In> lst := '[_a,_b,_c,_d,_e] 
Result: [_a,_b,_c,_d,_e]

In> Reverse!(FlatCopy(lst)) 
Result: [_e,_d,_c,_b,_a]

In> lst 
Result: [_a,_b,_c,_d,_e]

*SEE

*SOURCE org/mathpiper/builtin/procedures/core/FlatCopy.java
==========
 *CMD FloorN --- largest integer not larger than xx (arbitrary-precision math function)
 *CORE
 *CALL
    FloorN(xx)

 *DESC

This command performs the calculation of an elementary mathematical
function.  The arguments <i>must</i> be numbers.  The reason for the
postfix {N} is that the library needs to define equivalent non-numerical
functions for symbolic computations, such as {Exp}, {Sin}, etc.

Note that all xxxN functions accept integers as well as floating-point numbers.
The resulting values may be integers or floats.  If the mathematical result is an
exact integer, then the integer is returned.  For example, {Sqrt(25)} returns
the integer {5}, and {Power(2,3)} returns the integer {8}.  In such cases, the
integer result is returned even if the calculation requires more digits than set by
{BuiltinPrecisionSet}.  However, when the result is mathematically not an integer,
the functions return a floating-point result which is correct only to the current precision.

*E.G.
In>
Result>

*SEE CeilN


*SOURCE org/mathpiper/builtin/procedures/core/Floor.java
==========
*CMD For --- C-style [for] loop
*STD
*CALL
        For(init, pred, incr) body

*PARMS

{init} -- expression for performing the initialization

{pred} -- predicate deciding whether to continue the loop

{incr} -- expression to increment the counter

{body} -- expression to loop over

*DESC

This commands implements a C style {for} loop. First
of all, the expression "init" is evaluated. Then the predicate
"pred" is evaluated, which should return {True} or
{False}. Next the loop is executed as long as the
predicate yields {True}. One traversal of the loop
consists of the subsequent evaluations of "body", "incr", and
"pred". Finally, the value {True} is returned.

This command is most often used in a form such as {For(i := 1, i <=? 10, i++) body}, which evaluates {body} with
{i} subsequently set to 1, 2, 3, 4, 5, 6, 7, 8, 9,
and 10.

The expression {For(init, pred, incr) body} is
equivalent to {init; While(pred) {body; incr;}}.

*E.G. notest

In> For(i := 1, i <=? 10, i++) Echo([i, i^2]);
Result: True
Side Effects:
[1,1] 
[2,4] 
[3,9] 
[4,16] 
[5,25] 
[6,36] 
[7,49] 
[8,64] 
[9,81] 
[10,100] 
Result: True;

*SEE While, DoWhile, ForEach, Break, Continue

*SOURCE org/mathpiper/builtin/procedures/core/For.java
==========
*CMD Freeze(expression) --- freezes the evaluation of an expression

*CALL
        Freeze(expression)

*PARMS

{expression} -- expression to freeze

*DESC

The expression that is passed to {Freeze} is returned unevaluated. This procedure is different from the 
{Hold} procedure in that it holds the expression that is its argument permanently.

*E.G.
In> Freeze(2 + 2)
Result: Freeze(2 + 2)

*SEE '', ', Hold

*SOURCE org/mathpiper/builtin/procedures/core/Freeze.java
==========
*CMD ''expression --- freezes the evaluation of an expression

*CALL
        ''expression

*PARMS

{expression} -- expression to freeze

*DESC

The expression that is passed to {''} is returned unevaluated. The {''} freeze operator 
is different than the {'} operator in that {''} holds the expression that is its argument 
permanently. The {''} operator has a very low precedence so that it can often be used 
without needing to place parentheses around the expression
to be frozen.

*E.G.
In> x := 3
Result: 3

In> ''x
Result: ''x

In> ''2+2
Result: ''2 + 2

*SEE Freeze, ', Hold

*SOURCE org/mathpiper/builtin/procedures/core/Freeze.java
==========
*CMD FromBase --- conversion of a number from non-decimal base to decimal base
*CORE
*CALL
	FromBase(base,"string")

*PARMS

{base} -- integer, base to convert to/from

{number} -- integer, number to write out in a different base

{"string"} -- string representing a number in a different base

*DESC

In MathPiper, all numbers are written in decimal notation (base 10).


{FromBase} converts an integer, written as a string in base
{base}, to base 10. {ToBase} converts {number},
written in base 10, to base {base}.

*REM where is this p-adic capability? - sw
These functions use the p-adic expansion capabilities of the built-in
arbitrary precision math libraries.

Non-integer arguments are not supported.

*EXAMPLES
Write the binary number {111111} as a decimal number:

In> FromBase(2,"111111") 
Result: 63

*SEE ToBase, PAdicExpand

*SOURCE org/mathpiper/builtin/procedures/core/FromBase.java
==========
*CMD GcdN --- Greatest Common Divisor (arbitrary-precision math function)
*CORE
*CALL
	GcdN(n,m)

*DESC

This command performs the calculation of an elementary mathematical
function.  The arguments <i>must</i> be numbers.  The reason for the
postfix {N} is that the library needs to define equivalent non-numerical
functions for symbolic computations, such as {Exp}, {Sin}, etc.

Note that all xxxN functions accept integers as well as floating-point numbers.
The resulting values may be integers or floats.  If the mathematical result is an
exact integer, then the integer is returned.  For example, {Sqrt(25)} returns
the integer {5}, and {Power(2,3)} returns the integer {8}.  In such cases, the
integer result is returned even if the calculation requires more digits than set by
{BuiltinPrecisionSet}.  However, when the result is mathematically not an integer,
the functions return a floating-point result which is correct only to the current precision.

*EXAMPLES
GcdN(55,10) -> 5

*SEE Gcd, GaussianGcd


*SOURCE org/mathpiper/builtin/procedures/core/Gcd.java
==========
*CMD GenericTypeName --- get type name
*CORE
*CALL
	GenericTypeName(object)

*DESC
Returns a string representation of
the name of a generic object.

*E.G.

In> GenericTypeName(ArrayCreate(10,1))
Result: "Array";


*SOURCE org/mathpiper/builtin/procedures/core/GenericTypeName.java
==========
*CMD Generic? --- check for generic object
*CORE
*CALL
	Generic?(object)

*DESC
Returns {True} if an object is of a generic object type.


*SOURCE org/mathpiper/builtin/procedures/core/Generic_.java
==========
*CMD GetExactBitsN --- manipulate precision of floating-point numbers
*CORE
*CALL
	GetExactBitsN(x)

*PARMS
{x} -- an expression evaluating to a floating-point number


*DESC
Each floating-point number in MathPiper has an internal precision counter that stores the number of exact bits in the mantissa.
The number of exact bits is automatically updated after each arithmetic operation to reflect the gain or loss of precision due to round-off.
The procedures {GetExactBitsN} queries the precision flags of individual number objects.

{GetExactBitsN(x)} returns an integer number $n$ such that {x} represents a real number in the interval [$x*(1-2^{-n})$, $x*(1+2^{-n})$] if $x!=0$ and in the interval [$-2^(-n)$, $2^(-n)$] if $x=0$.
The integer $n$ is always nonnegative unless {x} is zero (a "floating zero").
A floating zero can have a negative value of the number $n$ of exact bits.

This function is only meaningful for floating-point numbers.
(All integers are always exact.)
For integer {x}, the function {GetExactBitsN} returns the bit count of {x}.

*REM FIXME - these examples currently do not work because of bugs

*E.G.
The default precision of 10 decimals corresponds to 33 bits:

In> GetExactBitsN(1000.123)
Result: 33;

In> x:=SetExactBits(10., 20)
Result: 10.;

In> GetExactBitsN(x)
Result: 20;
Prepare a "floating zero" representing an interval [-4, 4]:

In> x:=SetExactBits(0., -2)
Result: 0.;

In> x=0
Result: True;

*SEE BuiltinPrecisionSet, BuiltinPrecisionGet, SetExactBitsN

*SOURCE org/mathpiper/builtin/procedures/core/GetExactBits.java
==========
*CMD GreaterThan? --- comparison predicate
*CORE
*CALL
	GreaterThan?(a,b)

*PARMS
{a}, {b} -- decimal numbers or strings
*DESC
Compare decimal numbers or strings (lexicographically).

*E.G.
In> GreaterThan?(1,1)
Result: False;

In> GreaterThan?("b","a")
Result: True;

*SEE LessThan?, Equal?, StringCompareNatural

*SOURCE org/mathpiper/builtin/procedures/core/GreaterThan_.java
==========
*CMD HashMapContainsKey --- checks if a key is in the given hash map

*CALL
	HashMapContainsKey?(hashMap, key)

*PARMS

{hashMap} -- a hash map
{key} -- an atom

*DESC
This procedure checks if a key is in the given hash map.

*SEE HashMapCreate


*SOURCE org/mathpiper/builtin/procedures/core/HashMapContainsKey_.java
==========
*CMD HashMapCreate --- creates a hash map

*CALL
	HashMapCreate()

*DESC
This procedure creates a hash map.

*EXAMPLES
In> hashMap := HashMapCreate() 
Result: class java.util.HashMap

In> HashMapContainsKey?(hashMap, "aa") 
Result: False

In> HashMapGet(hashMap, "aa") 
Result: Null

In> HashMapPut(hashMap, "aa", 3) 
Result: True

In> HashMapContainsKey?(hashMap, "aa") 
Result: True

In> HashMapKeys(hashMap) 
Result: ["aa"]

In> HashMapValues(hashMap) 
Result: [3]

In> HashMapGet(hashMap, "aa") 
Result: 3

In> HashMapRemove(hashMap, "aa") 
Result: 3

In> HashMapKeys(hashMap) 
Result: []

In> HashMapValues(hashMap) 
Result: []

In> HashMapPut(hashMap, 'bb, 4) 
Result: True

In> HashMapKeys(hashMap) 
Result: [bb]

In> HashMapGet(hashMap, 'bb) 
Result: 4

In> HashMapValues(hashMap) 
Result: [4]

In> HashMapRemove(hashMap, 'bb) 
Result: 4

In> HashMapKeys(hashMap) 
Result: []

In> HashMapValues(hashMap) 
Result: []

*SEE HashMapGet, HashMapPut, HashMapRemove, HashMapKeys, HashMapValues, HashMapContainsKey?


*SOURCE org/mathpiper/builtin/procedures/core/HashMapCreate.java
==========
*CMD HashMapGet --- returns the value that is associated with the given key in the given hash map

*CALL
	HashMapGet(hashMap, key)

*PARMS

{hashMap} -- a hash map
{key} -- an atom

*DESC
This procedure returns the value that is associated with the given key in the given hash map.

*SEE HashMapCreate


*SOURCE org/mathpiper/builtin/procedures/core/HashMapGet.java
==========
*CMD HashMapKeys --- return the given hash map's keys

*CALL
	HashMapKeys(hashMap)

*PARMS

{hashMap} -- a hash map

*DESC
This procedure returns the given hash map's keys in a list.

*SEE HashMapCreate


*SOURCE org/mathpiper/builtin/procedures/core/HashMapKeys.java
==========
*CMD HashMapPut --- associates the given key with the given value in the given hash map

*CALL
	HashMapPut(hashMap, key, value)

*PARMS

{hashMap} -- a hash map
{key} -- an atom
{value} -- a value

*DESC
This procedure associates the given key with the given value in the given hash map.

*SEE HashMapCreate


*SOURCE org/mathpiper/builtin/procedures/core/HashMapPut.java
==========
*CMD HashMapRemove --- remove the mapping for the given key from the given hash map

*CALL
	HashMapRemove(hashMap, key)

*PARMS

{hashMap} -- a hash map
{key} -- an atom

*DESC
This procedure removes the mapping for the given key from the given hash map if it is present.

*SEE HashMapCreate


*SOURCE org/mathpiper/builtin/procedures/core/HashMapRemove.java
==========
*CMD HashMapValues --- return the given hash map's values

*CALL
	HashMapValues(hashMap)

*PARMS

{hashMap} -- a hash map

*DESC
This procedure returns the given hash map's values in a list.

*SEE HashMapCreate


*SOURCE org/mathpiper/builtin/procedures/core/HashMapValues.java
==========
*CMD HistorySize --- set size of history file
*CORE
*CALL
	HistorySize(n)

*PARMS

{n} -- number of lines to store in history file

*DESC

When exiting, MathPiper saves the command line history to a
file {~/.MathPiper_history}. By default it will
save the last 1024 lines. The default can be
overridden with this function. Passing -1 tells the system to save <i>all</i>
lines.

MathPiper allows you to configure a few things at startup. The file
{~/.mathpiperrc} is written in the MathPiper language and
will be executed when MapthPiper is run. This function
can be useful in the {~/.MathPiperrc} file.

*E.G.

In> HistorySize(200)
Result: True;

In> quit

*SEE quit

*SOURCE org/mathpiper/builtin/procedures/core/HistorySize.java
==========
*CMD Hold --- keep expression unevaluated
*CORE
*CALL
	Hold(expression)

*PARMS

{expression} -- expression to keep unevaluated

*DESC

The expression that is passed to {Hold} is returned unevaluated. This is useful to
prevent the evaluation of a certain expression in a context in which
evaluation normally takes place.

The procedure {ListToProcedure()} also leaves its result unevaluated.
Both functions stop the process of evaluation (no more rules will be applied).

*EXAMPLES
Echo([Hold(1+1), "=", 1+1]) -> True

Side Effects: 
[1+1,"=",2]

x := 3 -> 3

Hold(x) -> 'x

Hold(2+2) -> '(2+2)

*SEE ', '', Freeze, Eval, HoldArgument, ListToProcedure

*SOURCE org/mathpiper/builtin/procedures/core/Hold.java
==========
*CMD ' expression --- holds the evaluation of an expression
*STD
*CALL
        ' expression

*PARMS

{expression} -- expression to hold

*DESC

This operator is used as a shortcut for the Hold procedure.

*EXAMPLES
x := 3 -> 3

'x -> 'x

'(2+2) -> '(2+2)

*SEE Hold, '', Freeze

*SOURCE org/mathpiper/builtin/procedures/core/Hold.java
==========
*CMD HoldArgument --- mark argument as not evaluated
*CORE
*CALL
	HoldArgument("operator","parameter")

*PARMS

{"operator"} -- string, name of a function

{parameter} -- string, name of parameter

*DESC
Specify that parameter should
not be evaluated before used. This will be
declared for all arities of "operator", at the moment
this procedure is called, so it is best called
after all {Rulebase} calls for this operator.

Note that defining rules with the {-->} operator can also result
in a rulebase with the implied arity being defined. Therefore,
{HoldArgument} should be placed after all rule definitions if all possible
rulebases are not defined by {Rulebase} procedures.


*SEE RulebaseHoldArguments, HoldArgumentNumber, RulebaseArgumentsList

*SOURCE org/mathpiper/builtin/procedures/core/HoldArgument.java
==========
*CMD If --- used to make decisions

*CALL
    If(predicate)body

*PARMS

{predicate} -- predicate to test

{body} -- expression to evaluate if the predicate is true

*DESC

The If() function evaluates the "predicate" expression that
is passed to it as an argument, and then it looks at the value that the
expression returns. If this value is True, the body of the If() function is
executed. If the predicate expression evaluates to False, the body is not
executed.

*E.G.
/%mathpiper

number := 6;

If(number >? 5)
{
    Echo(number, "is greater than 5.");
};

Echo("End of program.");

/%/mathpiper

    /%output,preserve="false"
      Result: True
      
      Side Effects:
      6 is greater than 5.
      End of program.
   /%/output

*SEE Else, Decide

*SOURCE org/mathpiper/builtin/procedures/core/If.java
==========
*CMD Implies? --- logical implication
*CORE
*CALL
	a1 ->? a2
	Implies?(a1, a2)

*PARMS

{a}1, {a}2 -- boolean values (may evaluate to {True} or {False})

*DESC

This function implements the truth table for implication:

{True} ->? {True} returns {True}.

{True} ->? {False} returns {False}.

{False} ->? {True} returns {True}.

{False} ->? {False} returns {True}.

*E.G.

In> True ->? True
Result: True;

*SEE And?, Or?, Not?, Equivales?

*SOURCE org/mathpiper/builtin/procedures/core/Implies_.java
==========
*CMD !? --- logical negation
*SEE Not?

*SOURCE org/mathpiper/builtin/procedures/core/Implies_.java
==========
*CMD Infix --- define procedure syntax (infix operator)
*CORE
*CALL
	Infix("op")
	Infix("op", precedence)

*PARMS

{"op"} -- string, the name of a procedure

{precedence} -- nonnegative integer (evaluated)

*DESC

Declares a special syntax for the procedure to be parsed as an  infix operator.

"Infix" procedures must have two arguments and are syntactically placed between their arguments.
Names of infix procedures can be arbitrary, although for reasons of readability they are usually made of non-alphabetic characters.

Function name can be any string but meaningful usage and readability would
require it to be either made up entirely of letters or entirely of non-letter
characters (such as "+", ":" etc.).
Precedence is optional (will be set to 0 by default).

*E.G.
In> Infix("###", 5)
Result: True;

In> '(_a ### _b)
Result: _a ### _b

*SEE Bodied?, PrecedenceGet, Bodied, Postfix, Prefix

*SOURCE org/mathpiper/builtin/procedures/core/Infix.java
==========
*CMD Infix? --- check for procedure syntax
*CORE
*CALL
	Infix?("op")

*PARMS

{"op"} -- string, the name of a procedure

*DESC

Check whether the procedure with given name {"op"} has been declared as a
"bodied", infix, postfix, or prefix operator, and  return {True} or {False}.

*E.G.

In> Infix?("+");
Result: True;

*SEE Bodied, PrecedenceGet,Bodied?,Postfix?,Prefix?

*SOURCE org/mathpiper/builtin/procedures/core/Infix_.java
==========
*CMD Insert --- insert an element into a list
*CORE
*CALL
	Insert(list, n, expr)

*PARMS

{list} -- list in which "expr" should be inserted

{n} -- index at which to insert

{expr} -- expression to insert in "list"

*DESC

The expression "expr" is inserted just before the n-th entry in
"list". The first parameter "list" should be a list, while "n"
should be a positive integer less than or equal to the length of
"list" plus one. The expression "expr" is placed between the
entries in "list" with entries "n-1" and "n". There are two
border line cases: if "n" is 1, the expression "expr" is placed in
front of the list (just as by the {:} operator); if "n"
equals the length of "list" plus one, the expression "expr" is
placed at the end of the list (just as by {Append}). In any
case, the resulting list is returned.

*EXAMPLES
In> Insert([_a,_b,_c,_d], 4, _x) 
Result: [_a,_b,_c,_x,_d]

In> Insert([_a,_b,_c,_d], 5, _x) 
Result: [_a,_b,_c,_d,_x]

In> Insert([_a,_b,_c,_d], 1, _x) 
Result: [_x,_a,_b,_c,_d]

*SEE Insert!, :, Append, Delete, Remove

*SOURCE org/mathpiper/builtin/procedures/core/Insert.java
==========
*CMD Insert! --- insert an element destructively into a list
*CORE
*CALL
	Insert!(list, n, expr)

*PARMS

{list} -- list in which "expr" should be inserted

{n} -- index at which to insert

{expr} -- expression to insert in "list"

*DESC

This is the destructive counterpart of {Insert}. This
command yields the same result as the corresponding call to
{Insert}, but the original list is modified. So if a
variable is bound to "list", it will now be bound to the list with
the expression "expr" inserted.

Destructive commands run faster than their nondestructive counterparts
because the latter copy the list before they alter it.

*E.G.

In> lst := [_a,_b,_c,_d];
Result: [_a,_b,_c,_d];

In> Insert(lst, 2, _x);
Result: [_a,_x,_b,_c,_d];

In> lst;
Result: [a,b,c,d];

In> Insert!(lst, 2, _x);
Result: [_a,_x,_b,_c,_d];

In> lst;
Result: [_a,_x,_b,_c,_d];

*SEE Insert, Delete!, Replace!

*SOURCE org/mathpiper/builtin/procedures/core/Insert__.java
==========
*CMD Integer? --- test to see if a number is an integer
*CORE
*CALL
	Integer?(expr)

*PARMS

{expr} -- expression to test

*DESC

This function tests whether "expr" is an integer number. There are two kinds
of numbers, integers (e.g. 6) and decimals (e.g. -2.75 or 6.0).
*E.G.

In> Integer?(6);
Result: True;

In> Integer?(3.25);
Result: False;

In> Integer?(1/2);
Result: False;

In> Integer?(3.2/10);
Result: False;

*SEE String?, Atom?, Integer?, Decimal?, PositiveNumber?, NegativeNumber?, Number?

*SOURCE org/mathpiper/builtin/procedures/core/Integer_.java
==========
*CMD LeftPrecedenceGet --- get operator precedence
*CORE
*CALL
	LeftPrecedenceGet("op")

*PARMS

{"op"} -- string, the name of a function

*DESC

Returns the precedence of the function named "op" which should have been declared as a bodied function or an infix, postfix, or prefix operator. Generates an error message if the string str does not represent a type of function that can have precedence.

For infix operators, right precedence can differ from left precedence. Bodied functions and prefix operators cannot have left precedence, while postfix operators cannot have right precedence; for these operators, there is only one value of precedence.

*E.G.
In> LeftPrecedenceGet("++")
Result: 5;

*SEE LeftPrecedenceGet,LeftPrecedenceSet,RightPrecedenceSet,RightAssociativeSet,OperatorsGet,OperatorSpacesSet,LeftSpacesGet,RightSpacesGet

*SOURCE org/mathpiper/builtin/procedures/core/LeftPrecedenceGet.java
==========
*CMD LeftPrecedenceSet --- set operator precedence
*CORE
*CALL
	LeftPrecedenceSet("op",precedence)

*PARMS

{"op"} -- string, the name of a function

{precedence} -- nonnegative integer

*DESC

{"op"} should be an infix operator. This function call tells the
infix expression printer to bracket the left  hand side of
the expression if its precedence is larger than precedence.

This functionality was required in order to display expressions like {a-(b-c)}
correctly. Thus, {a+b+c} is the same as {a+(b+c)}, but {a-(b-c)} is not
the same as {a-b-c}.

Note that the left precedence of an infix operator does not affect the way MathPiper 
interprets expressions typed by the user. You cannot make MathPiper parse {a-b-c} as 
{a-(b-c)} unless you declare the operator "{-}" to be right-associative.

*SEE LeftPrecedenceGet,RightPrecedenceGet,RightPrecedenceSet,RightAssociativeSet,OperatorsGet,OperatorSpacesSet,LeftSpacesGet,RightSpacesGet

*SOURCE org/mathpiper/builtin/procedures/core/LeftPrecedenceSet.java
==========
*CMD LeftSpacesGet --- return the number of spaces that are placed to the left of an operator when it is unparsed
*CALL
    LeftSpacesGet(operatorName, operatorType)

*PARMS

{operatorName} -- string, the name of an operator
{operatorType} -- "Prefix", "Infix", or "Postfix"

*DESC
This procedure returns the number of spaces that are placed to the left of an operator when it is unparsed.

*EXAMPLES
In> LeftSpacesGet("+", "Infix") 
Result: " "

*SEE RightSpacesGet,LeftPrecedenceGet,LeftPrecedenceSet,RightPrecedenceSet,RightAssociativeSet,OperatorsGet,OperatorSpacesSet

*SOURCE org/mathpiper/builtin/procedures/core/LeftSpacesGet.java
==========
*CMD Length --- the length of a list or string
*CORE
*CALL
	Length(object)

*PARMS

{object} -- a list, array or string

*DESC

Length returns the length of a list.
This function also works on strings and arrays.

*EXAMPLES
In> Length([_a,_b,_c]) 
Result: 3

In> Length("abcdef") 
Result: 6

*SEE First, Rest, Nth, Count

*SOURCE org/mathpiper/builtin/procedures/core/Length.java
==========
*CMD LessThan? --- comparison predicate
*CORE
*CALL
	LessThan?(a,b)

*PARMS
{a}, {b} -- decimal numbers or strings
*DESC
Compare decimal numbers or strings (lexicographically).

*E.G.
In> LessThan?(1,1)
Result: False;

In> LessThan?("a","b")
Result: True;

*SEE GreaterThan?, Equal?, StringCompareNatural

*SOURCE org/mathpiper/builtin/procedures/core/LessThan_.java
==========
*CMD LibraryLock --- unlock and lock the script library
*CALL
	LibraryLock(predicate)

*PARMS
{predicate} - True or False

*DESC
By default the script library is locked and it cannot be changed. Unlocking the library
enables the changing and retracting of library functions and rules. Locking the library prevents
the changing and retracting of library functions and rules.

*E.G.
In> Echo()
Result: True
Side Effects:



In> Echo() := 3
Result: Exception
Exception: The procedure <Echo> is a library procedure, and library procedures cannot be redefined.  Starting at index 7.

In> LibraryLock(False)
Result: True
Side Effects:
The library is unlocked.


In> Echo() := 3
Result: True

In> Echo()
Result: 3

In> LibraryLock(True)
Result: True
Side Effects:
The library is locked.


In> Echo() := 3
Result: Exception
Exception: The procedure <Echo> is a library procedure, and library procedures cannot be redefined.  Starting at index 7.

*SEE PipeToFile, PipeFromString, ParseMathPiper, ParseMathPiperToken

*SOURCE org/mathpiper/builtin/procedures/core/LibraryLock.java
==========
 *CMD List --- construct a list
 *CORE
 *CALL
List(expr1, expr2, ...)

 *PARMS

{expr1}, {expr2} -- expressions making up the list

 *DESC

A list is constructed whose first entry is "expr1", the second entry
is "expr2", and so on. This command is equivalent to the expression
"[expr1, expr2, ...]".

 *E.G.

In> List();
Result: [];

In> List(a,b);
Result: [a,b];

In> List(a,[1,2],d);
Result: [a,[1,2],d];

 *SEE ListToProcedure, ProcedureToList

*SOURCE org/mathpiper/builtin/procedures/core/List.java
==========
*CMD ListToProcedure --- convert a list to a procedure
*CORE
*CALL
	ListToProcedure(list)

*PARMS

{list} -- list to be converted

*DESC

This command converts a list to a procedure. The car
entry of "list" is treated as a procedure atom, and the following entries
are the arguments to this procedure. So the procedure referred to in the
car element of "list" is applied to the other elements.

Note that "list" is evaluated before the procedure application is
formed, but the resulting expression is left unevaluated. The procedures 
{ListToProcedure()} and {Hold()} both stop the process of evaluation.

*EXAMPLES
In> ListToProcedure('[Cos, x]) 
Result: Cos(x)

In> ListToProcedure('[f]) 
Result: f()

In> ListToProcedure('[Taylor,x,0,5,Cos(x)]) 
Result: Taylor(x,0,5)Cos(x)

*SEE List, ProcedureToList, Hold

*SOURCE org/mathpiper/builtin/procedures/core/ListToProcedure.java
==========
*CMD ListToString --- converts a list into a string
*STD
*CALL
    
    ListToString(list)
    ListToString(list, separator)

*PARMS

{list} -- a list to be converted into a string
{separator} -- a string that is inserted between the list elements

*DESC
This function converts each of the elementes in a list into a 
string and then concatenates these strings into a single string.

*E.G.
In> ListToString([1,2,3])
Result: "123"

In> ListToString([1,2,3], ":")
Result: "1:2:3"

*SEE StringToList

*SOURCE org/mathpiper/builtin/procedures/core/ListToStringInternal.java
==========
*CMD List? --- test for a list
*CORE
*CALL
	List?(expr)

*PARMS

{expr} -- expression to test

*DESC

This function tests whether "expr" is a list. A list is a sequence
between square brackets, e.g. {[2, 3, 5]}.

*E.G.

In> List?([2,3,5]);
Result: True;

In> List?(2+3+5);
Result: False;

*SEE Procedure?

*SOURCE org/mathpiper/builtin/procedures/core/List_.java
==========
*CMD LoadLibraryProcedure --- load a procedure from the library.
*CORE
*CALL
	LoadLibraryProcedure(string)

*PARMS

{string} -- a string which contains a procedure name

*DESC

Loads a procedure from the library.


*SOURCE org/mathpiper/builtin/procedures/core/LoadLibraryProcedure.java
==========
*CMD LoadScript --- evaluate all expressions that are in a string
*CORE
*CALL
	LoadScript(string)

*PARMS

{string} -- a string that contains MathPiper code

*DESC

All MathPiper expressions in the string are read and
evaluated. {LoadScript} always returns {True}.

*SEE LoadScriptFile

*SOURCE org/mathpiper/builtin/procedures/core/LoadScript.java
==========
*CMD Local --- declare new local variables
*CORE
*CALL
	Local(var, ...)

*PARMS

{var} -- name of variable to be declared as local

*DESC

All variables in the argument list are declared as local
variables. The arguments are not evaluated. The value True is
returned.

By default, all variables in MathPiper are global. This means that the
variable has the same value everywhere. But sometimes it is useful to
have a private copy of some variable, either to prevent the outside
world from changing it or to prevent accidental changes to the outside
world. This can be achieved by declaring the variable local. Now only
expressions within the {Sequence} block (or its
syntactic equivalent, the {[  ]} block) can access
and change it. Functions called within this block cannot access the
local copy unless this is specifically allowed with {UnFence}.

In the first block below, {a} is not declared local and
hence defaults to be a global variable. Indeed, changing the variable
inside the block also changes the value of {a}
outside the block. However, in the second block {a}
is defined to be local and now the value outside the block stays the
same, even though {a} is assigned the value 5 inside
the block.

*E.G.

In> a := 3;
Result: 3;

In> {a := 4; a;};
Result: 4;

In> a;
Result: 4;

In> {Local(a); a := 5; a;};
Result: 5;

In> a;
Result: 4;


*SEE LocalSymbols, Sequence, UnFence

*SOURCE org/mathpiper/builtin/procedures/core/Local.java
==========
*CMD MacroLocal --- define rules in procedures
*CORE
*DESC

This procedure has the same effect as its non-macro counterpart, except
that its arguments are evaluated before the required action is performed.
This is useful in macro-like procedures or in procedures that need to define new
rules based on parameters.

Make sure that the arguments of {Macro}... commands evaluate to expressions that would normally be used in the non-macro version!

*SEE Assign, Unassign, Local, RulebaseHoldArguments, RuleHoldArguments, /`, MacroAssign, MacroUnassign, MacroRulebaseHoldArguments, MacroRulebaseListedHoldArguments, RuleEvaluateArguments

*SOURCE org/mathpiper/builtin/procedures/core/Local.java
==========
*CMD LocalSymbols --- create unique local symbols with given prefix
*STD
*CALL
	LocalSymbols(var1, var2, ...) body

*PARMS

{var1}, {var2}, ... -- atoms, symbols to be made local

{body} -- expression to execute

*DESC

Given the symbols passed as the first arguments to LocalSymbols a set of local
symbols will be created, and creates unique ones for them, typically of the
form {\$<symbol><number>}, where {symbol} was the symbol entered by the user,
and {number} is a unique number. This scheme was used to ensure that a generated
symbol can not accidentally be entered by a user.

This is useful in cases where a guaranteed free variable is needed,
for example, in the macro-like functions ({For}, {While}, etc.).

*E.G. notest

In> LocalSymbols(a,b)a+b
Result: \$a6+\$b6;

*SEE UniqueConstant

*SOURCE org/mathpiper/builtin/procedures/core/LocalSymbols.java
==========
*CMD Log10 --- double-precision math function
*CORE
*CALL
	Log10D(x)

*PARMS
{x} -- a number

*DESC
A double precision version of the log base 10 function.

*SEE Ln

*E.G.
In> Log10D(7)
Result: 0.8450980400


*SOURCE org/mathpiper/builtin/procedures/core/Log10D.java
==========
*CMD MacroAssign --- define rules in procedures
*CORE
*DESC

This procedure has the same effect as its non-macro counterpart, except
that its arguments are evaluated before the required action is performed.
This is useful in macro-like procedures or in procedures that need to define new
rules based on parameters.

Make sure that the arguments of {Macro}... commands evaluate to expressions that would normally be used in the non-macro version!

*SEE Assign, Unassign, Local, RulebaseHoldArguments, RuleHoldArguments, /`, MacroUnassign, MacroLocal, MacroRulebaseHoldArguments, MacroRulebaseListedHoldArguments, RuleEvaluateArguments

*SOURCE org/mathpiper/builtin/procedures/core/MacroAssign.java
==========
*CMD MacroRulebaseHoldArguments --- define a procedure as a macro
*CORE
*CALL
	MacroRulebaseHoldArguments(name,params)

*PARMS

{name} -- string, name of a procedure

{params} -- list of arguments

*DESC

{MacroRulebaseHoldArguments} is similar to {RulebaseHoldArguments}, with the difference that it declares a macro,
instead of a procedure.
After this call, rules can be defined for the procedure "{name}", but their interpretation will be different.

With the usual procedures, the evaluation model is that of the <i>applicative-order model of
substitution</i>, meaning that first the arguments are evaluated, and then the procedure
is applied to the result of evaluating these arguments. The procedure is entered, and the
code inside the procedure can not access local variables outside of its own local variables.

With macros, the evaluation model is that of the <i>normal-order model of substitution</i>,
meaning that all occurrences of variables in an expression are first substituted into the
body of the macro, and only then is the resulting expression evaluated <i>in its
calling environment</i>. This is important, because then in principle a macro body
can access the local variables from the calling environment, whereas procedures can not do that.

As an example, suppose there is a procedure {square}, which squares its argument, and a procedure
{add}, which adds its arguments. Suppose the definitions of these procedures are:

	add(x,y) --> x+y;
and
	square(x) --> x*x;
In applicative-order mode (the usual way procedures are evaluated), in the following expression
	add(square(2),square(3))
first the arguments to {add} get evaluated. So, first {square(2)} is evaluated.
To evaluate this, first {2} is evaluated, but this evaluates to itself. Then
the {square} procedure is applied to it, {2*2}, which returns 4. The same
is done for {square(3)}, resulting in {9}. Only then, after evaluating these two
arguments, {add} is applied to them, which is equivalent to
	add(4,9)
resulting in calling {4+9}, which in turn results in {13}.

In contrast, when {add} is a macro, the arguments to {add} are first
expanded. So
	add(square(2),square(3))
first expands to
	square(2) + square(3)
and then this expression is evaluated, as if the user had written it directly.
In other words, {square(2)} is not evaluated before the macro has been fully expanded.


Macros are useful for customizing syntax, and compilers can potentially
greatly optimize macros, as they can be inlined in the calling environment,
and optimized accordingly.

There are disadvantages, however. In interpreted mode, macros are slower,
as the requirement for substitution means that a new expression to be evaluated
has to be created on the fly. Also, when one of the parameters to the macro
occur more than once in the body of the macro, it is evaluated multiple times.

When defining transformation rules for macros, the variables to be substituted
need to be preceded by the {@} operator, similar to the back-quoting mechanism.
Apart from that, the two are similar, and all transformation rules can also be
applied to macros.

Macros can co-exist with procedures with the same name but different arity.
For instance, one can have a procedure {foo(a,b)}
with two arguments, and a macro {foo(a,b,c)} with three arguments.


*E.G.

The following example defines a macro {myfor}, and shows one use, referencing
a variable {a} from the calling environment.

In> MacroRulebaseHoldArguments("myfor",[init,pred,inc,body])
Result: True;

In> myfor(_init,_pred,_inc,_body)-->[@init;While(@pred)[@body;@inc;];True;];
Result: True;

In> a:=10
Result: 10;

In> myfor(i:=1,i<10,i++,Echo(a*i))
	10
	20
	30
	40
	50
	60
	70
	80
	90
Result: True;

In> i
Result: 10;

*SEE RulebaseHoldArguments, /`, MacroRulebaseListedHoldArguments

*SOURCE org/mathpiper/builtin/procedures/core/MacroRulebaseHoldArguments.java
==========
*CMD MacroRulebaseListedHoldArguments --- define macro with variable number of arguments
*CORE
*CALL
	MacroRulebaseListedHoldArguments("name", params)

*PARMS

{"name"} -- string, name of function

{params} -- list of arguments to function

*DESC

This does the same as {MacroRulebaseHoldArguments} (define a macro), but with a variable
number of arguments, similar to {RulebaseListedHoldArguments}.

*SEE RulebaseHoldArguments, RulebaseListedHoldArguments, /`, MacroRulebaseHoldArguments

*SOURCE org/mathpiper/builtin/procedures/core/MacroRulebaseListedHoldArguments.java
==========
*CMD MaxEvalDepth --- set the maximum evaluation depth
*CORE
*CALL
	MaxEvalDepth(n)

*PARMS

{n} -- new maximum evaluation depth

*DESC

Use this command to set the maximum evaluation depth to the integer
"n". The default value is 1000. The procedure {MaxEvalDepth} returns {True}.

The point of having a maximum evaluation depth is to catch any
infinite recursion. For example, after the definition {f(x) := f(x)}, evaluating the expression {f(x)} would call {f(x)}, which would
call {f(x)}, etc. The interpreter will halt if
the maximum evaluation depth is reached and an error message will be printed. Indirect recursion, e.g.
the pair of definitions {f(x) := g(x)} and {g(x) := f(x)}, will also be caught.

An example of an infinite recursion, caught because the maximum
evaluation depth is reached.

In> f(x) := f(x)
Result: True;

In> f(x)
	Error on line 1 in file [CommandLine]
	Max evaluation stack depth reached.
	Please use MaxEvalDepth to increase the stack
	size as needed.

However, a long calculation may cause the maximum evaluation depth to
be reached without the presence of infinite recursion. The procedure {MaxEvalDepth} is meant for these cases.

In> 10 ## g(0) --> 1;
Result: True;

In> 20 ## g(n_PositiveInteger?) --> 2 * g(n-1);
Result: True;

In> g(1001);
	Error on line 1 in file [CommandLine]
	Max evaluation stack depth reached.
	Please use MaxEvalDepth to increase the stack
	size as needed.

In> MaxEvalDepth(10000);
Result: True;

In> g(1001);
Result: 21430172143725346418968500981200036211228096234
	1106721488750077674070210224987224498639675763139171
	6255189345835106293650374290571384628087196915514939
	7149607869135549648461970842149210124742283755908364
	3060929499671638825347975351183310878921541258291423
	92955373084335320859663305248773674411336138752;

*SOURCE org/mathpiper/builtin/procedures/core/MaxEvalDepth.java
==========
 *CMD MetaClear --- set the metadata for a value or an unbound variable
 *CORE
 *CALL
MetaSet(value_or_unbound_variable)

 *PARMS

{value_or_unbound_variable} -- a value or an unbound variable


 *DESC

Clears a value's metadata.  MetaClear returns the given value or unbound variable
as a result after it has had metadata added to it.

*E.G.
In> MetaClear(_b)
Result: _b


*SEE MetaGet, MetaSet, MetaKeys, MetaValues, Unassign

*SOURCE org/mathpiper/builtin/procedures/core/MetaClear.java
==========
*CMD MetaEntries --- returns the metadata values for a value or an unbound variable
*CORE
*CALL
MetaEntries(value_or_unbound_variable)

*PARMS

{value_or_unbound_variable} -- a value or an unbound variable

*DESC

todo:tk: check how well this procedure works on unbound variables.

Returns the metadata values for a value or an unbound variable.  The metadata is
held in an association list.



 *SEE MetaGet, MetaSet, MetaClear, MetaKeys, Unassign

*SOURCE org/mathpiper/builtin/procedures/core/MetaEntries.java
==========
*CMD MetaGet --- returns the metadata for a value or an unbound variable
*CORE
*CALL
MetaGet(value_or_unbound_variable, key_string)

*PARMS

{value_or_unbound_variable} -- a value or an unbound variable

{key_string} -- a string which is the key for the given value


*DESC

Returns the metadata for a value or an unbound variables.  The metadata is
held in an associative list.



*SEE MetaSet, MetaClear, MetaKeys, MetaValues, Unassign

*SOURCE org/mathpiper/builtin/procedures/core/MetaGet.java
==========
*CMD MetaKeys --- returns the metadata keys for a value or an unbound variable
*CORE
*CALL
MetaKeys(value_or_unbound_variable)

*PARMS

{value_or_unbound_variable} -- a value or an unbound variable

*DESC
Returns the metadata keys for a value or an unbound variables.  The metadata is
held in an associative list.

*SEE MetaGet, MetaSet, MetaClear, MetaValues, Unassign

*SOURCE org/mathpiper/builtin/procedures/core/MetaKeys.java
==========
 *CMD MetaSet --- set the metadata for a value or an unbound variable
 *CORE
 *CALL
MetaSet(value_or_unbound_variable, key_string, value)

 *PARMS

{value_or_unbound_variable} -- a value or an unbound variable

{key_string} -- a string which will be the key for the given value

{value} -- a value such as a string, symbolic atom, or list

 *DESC

Adds metadata to values and unbound variables.  The metadata is
held in an associative list.  MetaSet returns the given value or unbound variable
as a result after it has had metadata added to it.

*E.G.
In> a := MetaSet(_b,"TAG","DATA")
Result: _b

In> a
Result: _b

In> MetaKeys(a)
Result: [startIndex,endIndex,sourceName,lineNumber,"TAG"]

In> MetaValues(a)
Result: [13,15,USER:USER,1,"DATA"]

In> MetaGet(a,"TAG")
Result: "DATA"

In> a := MetaSet(3,"TAG","DATA")
Result: 3

In> a
Result: 3

In> MetaKeys(a)
Result: [startIndex,endIndex,sourceName,lineNumber,"TAG"]

In> MetaValues(a)
Result: [13,14,USER:USER,1,"DATA"]

In> MetaGet(a,"TAG")
Result: "DATA"

In>  f(x) := MetaSet(x^2,"TAG","DATA")
Result: True

In> f(_x)
Result: _x^2

In> MetaKeys(f(_x))
Result: ["TAG"]

In> MetaValues(f(_x))
Result: ["DATA"]

In> MetaGet(f(_x),"TAG")
Result: "DATA"


*SEE MetaClear, MetaGet, MetaKeys, MetaValues, Unassign

*SOURCE org/mathpiper/builtin/procedures/core/MetaSet.java
==========
*CMD MetaToObject --- Converts a meta-level expression into an object-level expression.

*CALL
	MetaToObject(expr)

*PARMS

{expr} -- expression to convert

*DESC

Converts a meta-level expression into an object-level expression. This is done by removing underscore
characters from all constant names that are in the expression.

*E.G.
In> MetaToObject(_a+_b)
Result: a+b

*SEE ObjectToMeta

*SOURCE org/mathpiper/builtin/procedures/core/MetaToObject.java
==========
*CMD MetaValues --- returns the metadata values for a value or an unbound variable
*CORE
*CALL
MetaValues(value_or_unbound_variable)

*PARMS


{value_or_unbound_variable} -- a value or an unbound variable


*DESC

Returns the metadata values for a value or an unbound variable.  The metadata is
held in an associative list.



*SEE MetaGet, MetaSet, MetaKeys, Unassign

*SOURCE org/mathpiper/builtin/procedures/core/MetaValues.java
==========
*CMD ModuloN --- remainder of division or x modulo y (arbitrary-precision math function)
*CORE
*CALL
	ModuloN(x,y) ()

*DESC

This command performs the calculation of an elementary mathematical
function.  The arguments <i>must</i> be numbers.  The reason for the
postfix {N} is that the library needs to define equivalent non-numerical
functions for symbolic computations, such as {Exp}, {Sin}, etc.

Note that all xxxN functions accept integers as well as floating-point numbers.
The resulting values may be integers or floats.  If the mathematical result is an
exact integer, then the integer is returned.  For example, {Sqrt(25)} returns
the integer {5}, and {Power(2,3)} returns the integer {8}.  In such cases, the
integer result is returned even if the calculation requires more digits than set by
{BuiltinPrecisionSet}.  However, when the result is mathematically not an integer,
the functions return a floating-point result which is correct only to the current precision.

*E.G.
In> Modulo(2,3)
Result: 2


*SOURCE org/mathpiper/builtin/procedures/core/Modulo.java
==========
*CMD MultiplyN --- multiply two numbers (arbitrary-precision math function)
*CORE
*CALL
	MultiplyN(x,y)

*DESC

This command performs the calculation of an elementary mathematical
function.  The arguments <i>must</i> be numbers.  The reason for the
postfix {N} is that the library needs to define equivalent non-numerical
functions for symbolic computations, such as {Exp}, {Sin}, etc.

Note that all xxxN functions accept integers as well as floating-point numbers.
The resulting values may be integers or floats.  If the mathematical result is an
exact integer, then the integer is returned.  For example, {Sqrt(25)} returns
the integer {5}, and {Power(2,3)} returns the integer {8}.  In such cases, the
integer result is returned even if the calculation requires more digits than set by
{BuiltinPrecisionSet}.  However, when the result is mathematically not an integer,
the functions return a floating-point result which is correct only to the current precision.

*E.G.
In>
Result:


*SOURCE org/mathpiper/builtin/procedures/core/Multiply.java
==========
*CMD Not? --- logical negation
*CORE
*CALL
	!? expr
        Not?(expr)

*PARMS

{expr} -- a boolean expression

*DESC

Not?(expr) returns the logical negation of the argument expr. If {expr} is
{False} it returns {True}, and if {expr} is {True}, {Not?(expr_} returns {False}.
If the argument is neither {True} nor {False}, it returns the entire
expression with evaluated arguments. In the standard scripts Not? is also declared as an
infix operator, so you can write {!? expr}.

*E.G.

In> !? True
Result: False;

In> !? False
Result: True;

In> !?(_a)
Result: !?(_a);

*SEE And?, Or?, Implies?, Equivales?

*SOURCE org/mathpiper/builtin/procedures/core/Not_.java
==========
*CMD !? --- logical negation
*SEE Not?

*SOURCE org/mathpiper/builtin/procedures/core/Not_.java
==========
*CMD NotationDecimal --- convert a number to decimal notation

*CALL
	NotationDecimal(number)

*PARMS

{number} -- a number

*DESC
This procedure converts a number to decimal notation. Its main use is
to convert numbers that are in scientific notation (such as 2e3) to
decimal notation.

*EXAMPLES
In> NotationDecimal(2e3) 
Result: 2000


*SOURCE org/mathpiper/builtin/procedures/core/NotationDecimal.java
==========
*CMD Number? --- test for a number
*CORE
*CALL
	Number?(expr)

*PARMS

{expr} -- expression to test

*DESC

This function tests whether "expr" is a number. There are two kinds
of numbers, integers (e.g. 6) and reals (e.g. -2.75 or 6.0). Note that a
complex number is represented by the {Complex}
function, so {Number?} will return {False}.  The value {False} will be returned
for all expressions which are lists, but the user should be especially aware of expression
lists which might appear to be numbers, such as those returned by Hold(-1) (see below).
 

*E.G.
In> Number?(6);
Result: True;

In> Number?(3.25);
Result: True;

In> Number?(I);
Result: False;

In> Number?(-1)
Result: True

In> UnparseLisp(-1)
Result: -1
Side Effects:
-1

In> Hold(-1)
Result: -1

In> Number?(Hold(-1))
Result: False

In> UnparseLisp(Hold(-1))
Result: -1
Side Effects:
(- 1 )

In> Number?("rock");
Result: False;

*SEE Atom?, String?, Integer?, Decimal?, PositiveNumber?, NegativeNumber?, Complex?

*SOURCE org/mathpiper/builtin/procedures/core/Number_.java
==========
*CMD ObjectToMeta --- Converts an object-level expression into a meta-level expression.
*CALL
	ObjectToMeta(expr)

*PARMS

{expr} -- expression to convert

*DESC

Converts an object-level expression into a meta-level expression. This is done by prepending an underscore
character to all variable names in the expression.

*E.G.
In> ObjectToMeta('(a+b))
Result: _a+_b

*SEE MetaToObject

*SOURCE org/mathpiper/builtin/procedures/core/ObjectToMeta.java
==========
*CMD OperatorSpacesSet --- specify the spaces that are on each side of an operator when it is printed

*CALL
	OperatorSpacesSet(operator, type, spaceBefore, spaceAfter);

*PARMS

{operator} -- string, the name of an operator
{type} -- "Prefix", "Infix" or "Postfix"
{spaceBefore} -- a string that contains zero or more spaces
{spaceAfter} -- a string that contains zero or more spaces

*DESC

This procedure specifies the number of spaces that are on each side of
an operator when it is printed.

*EXAMPLES
In> Infix("foo", 20) 
Result: True

In> 1 foo 2 
Result: 1 foo 2

In> OperatorSpacesSet("foo", "Infix", "", "  ") 
Result: True

In> 1 foo 2 
Result: 1foo  2

*SEE LeftSpacesGet,RightSpacesGet,LeftPrecedenceGet,RightPrecedenceGet,LeftPrecedenceSet,RightPrecedenceSet,RightAssociativeSet,OperatorsGet

*SOURCE org/mathpiper/builtin/procedures/core/OperatorSpacesSet.java
==========
*CMD Operator? --- test for an operator

*CALL
	Operator?(expr)

*PARMS

{expr} -- expression to test

*DESC

This procedure tests whether "expr" is an operator.

*EXAMPLES
In> Operator?("<?") 
Result: True

In> Operator?('(<?)) 
Result: True

In> Operator?("For") 
Result: False

*SEE OperatorsGet,Procedure?

*SOURCE org/mathpiper/builtin/procedures/core/Operator_.java
==========
*CMD OperatorsGet --- returns a list of all currently defined operators

*CALL
	OperatorsGet()

*DESC
This procedure returns a list of all the currently defined operators sorted by
precedence (high to low) then by name.

*E.G.
In> OperatorsGet()
Result: ["'","@","/`",":*:","`","++","--",":","<<",">>","∠","^","+","-",".","/","X","bin","hex","o","*","***","+","-","~~","||","!==","!=?","<=>","<=?","<>","<?","==","=?",">=?",">?","@@","!?","..","/@","&?","|?","AddTo","#","->?","==?","Where","''","::","/``","##","-->","->","/:","/::","+:=","-:=",":=","Else"]

*SEE Operator?,LeftPrecedenceGet,RightPrecedenceGet,LeftPrecedenceSet,RightPrecedenceSet,RightAssociativeSet,OperatorSpacesSet,LeftSpacesGet,RightSpacesGet

*SOURCE org/mathpiper/builtin/procedures/core/OperatorsGet.java
==========
*CMD Or? |? --- logical disjunction
*CORE
*CALL
	a1 |? a2
	Or?(a1, a2, a3, ..., aN)

*PARMS

{a}1, ..., {a}N -- boolean expressions (may evaluate to {True} or {False})

*DESC

This function returns {True} if an argument is encountered
that is true (scanning from left to right). The
{Or?} operation is "lazy", i.e. it returns {True} as soon as a {True} argument
is found (from left to right). If an argument other than {True} or
{False} is encountered, an unevaluated {Or?} expression is returned with all
arguments that didn't evaluate to {True} or {False} yet.
 {And(...)} and {Or?(...)} do also exist, defined in the script
library. You can redefine them as infix operators yourself, so you have the
choice of precedence. In the standard scripts they are in fact declared as
infix operators, so you can write {expr1 |? expr}.

*E.G.

In> True |? False
Result: True;

In> False |? _a
Result: (_a);

In> Or?(False, _a ,_b, True)
Result: True;

*SEE And?, Not?, Implies?, Equivales?

*SOURCE org/mathpiper/builtin/procedures/core/Or_.java
==========
*CMD |? --- logical disjunction
*SEE Or?

*SOURCE org/mathpiper/builtin/procedures/core/Or_.java
==========
*CMD ParseLisp --- parse expressions in LISP syntax
*CORE
*CALL
	ParseLisp()

*DESC

The procedure {ParseLisp} parses an expression in the LISP syntax from the current input, and returns
it unevaluated. When the end of an input file is encountered, the
special token atom {EndOfFile} is returned.

The MathPiper expression {a+b} is written in the LISP syntax as {(+ a b)}. The advantage of this syntax is that it is
less ambiguous than the infix operator grammar that MathPiper uses by
default.

*E.G. notest

In> PipeFromString("(+ a b)") ParseLisp();
Result: a+b;


In> PipeFromString("(List (Sin _x) (- (Cos Pi)))") ParseLisp();
Result: [Sin(_x),-Cos(Pi)];

In> PipeFromString("(List (Sin _x) (- (Cos (/ 1 4))))") ParseLisp();
Result: [Sin(_x),-Cos(1/4)]

*SEE PipeFromFile, PipeFromString, ParseMathPiper, ParseMathPiperToken, UnparseLisp, ParseLispListed

*SOURCE org/mathpiper/builtin/procedures/core/ParseLisp.java
==========
*CMD ParseLispListed --- parse expressions in LISP syntax
*CORE
*CALL
	ParseLispListed()

*DESC

The procedure {ParseLispListed} reads a LISP expression and returns
it in a list, instead of the form usual to MathPiper (expressions).
The result can be thought of as applying {ProcedureToList} to {ParseLisp}.
The procedure {ParseLispListed} is more useful for reading arbitrary LISP expressions, because the
first object in a list can be itself a list (this is never the case for MathPiper expressions where 
the first object in a list is always a function atom).

*E.G. notest

In> PipeFromString("(+ a b)")ParseLispListed()
Result: [+,a,b];

*SEE PipeFromFile, PipeFromString, ParseMathPiper, ParseMathPiperToken, UnparseLisp, ParseLisp

*SOURCE org/mathpiper/builtin/procedures/core/ParseLispListed.java
==========
*CMD ParseMathPiper --- parse expressions in MathPiper syntax from the current input
*CORE
*CALL
	ParseMathPiper()

*DESC

The procedure {ParseMathPiper} parses an expression in the MathPiper syntax from the current input, and returns
it unevaluated. When the end of an input file is encountered, the
special token atom {EndOfFile} is returned.


*E.G. notest

In> PipeFromString("2+5;") ParseMathPiper();
Result: 2+5;

In> PipeFromString("") ParseMathPiper();
Result: EndOfFile;

*SEE PipeFromFile, PipeFromString, ParseMathPiperToken, UnparseLisp, ParseLispListed

*SOURCE org/mathpiper/builtin/procedures/core/ParseMathPiper.java
==========
*CMD ParseMathPiperToken --- read a token from current input
*CORE
*CALL
	ParseMathPiperToken()

*DESC

Read a token from the current input, and return it unevaluated.
The returned object is a MathPiper atom (not a string).
When
the end of an input file is encountered, the token atom {EndOfFile} is returned.

A token is for computer languages what a word is for human languages:
it is the smallest unit in which a command can be divided, so that the
semantics (that is the meaning) of the command is in some sense a
combination of the semantics of the tokens. Hence {a := foo} consists of three tokens, namely {a}, {:=}, and {foo}.

The parsing of the string depends on the syntax of the language.
The part of the kernel that does the parsing is the "tokenizer".
MathPiper can parse its own syntax (the default tokenizer) or it can be instructed to parse XML or C++ syntax using the directives {DefaultTokenizer} or {XmlTokenizer}.
Setting a tokenizer is a global action that affects all {ParseMathPiperToken} calls.

*E.G. notest

In> PipeFromString("a := Sin(x)") While((tok := ParseMathPiperToken()) !=? EndOfFile) Echo(tok);
	a
	:=
	Sin
	(
	x
	)
Result: True;

We can read some junk too:

In> PipeFromString("-$3")ParseMathPiperToken();
Result: -$;

The result is an atom with the string representation {-$}.
MathPiper assumes that {-$} is an operator symbol yet to be defined.
The "{3}" will be in the next token.
(The results will be different if a non-default tokenizer is selected.)


*SEE PipeFromFile, PipeFromString, ParseMathPiper, ParseLisp, DefaultTokenizer

*SOURCE org/mathpiper/builtin/procedures/core/ParseMathPiperToken.java
==========
*CMD ParserGet --- get the name of the current parser

*CORE

*CALL
	ParserGet()

*DESC

{ParserGet()} returns the current parser, or it returns
an empty string if the default parser is used.



*E.G.

In> ParserGet()
Result: ""

*SEE ParseMathPiper, ParseLisp, UnparserSet, UnparserGet, ParserSet

*SOURCE org/mathpiper/builtin/procedures/core/ParserGet.java
==========
*CMD ParserSet --- set the current parser

*CORE

*CALL
	ParserSet(parser)
	ParserSet()

*PARMS

{parser} -- a string containing the name of a function that can parse an expression from current input.


*DESC

This function sets the current parser that will parse in the input on
the command line. This can be reset to the default parser with {ParserSet()} 
(when no argument is given, the system returns to the default).

Some examples of parsers are: {ParseLisp}.


*E.G.

In> ParserSet("ParseLisp")
Result: True

In> (+ 1 (* 2 3))
Result: 7

In> (ParserSet "ParseMathPiper")
Result: True




In> Taylor(x,0,5)Sin(x)
Result: x-x^3/6+x^5/120

In> ParserSet("ParseLisp")
Result: True

In> (Taylor x 0 5 (Sin x))
Result: x-x^3/6+x^5/120

In> (ParserSet "ParseMathPiper")
Result: True

*SEE ParseMathPiper, ParseLisp, UnparserSet, UnparserGet, ParserGet

*SOURCE org/mathpiper/builtin/procedures/core/ParserSet.java
==========
*CMD PatchString --- insert the result of evaluating code into a string 
*CORE
*CALL
	PatchString(string)

*PARMS

{string} -- a string to patch

*DESC

This procedure evaluates code that is between delimiters {? and ?} in 
a string and replaces the code (along with its delimiters) with the 
result of the evaluation

*E.G.
In> PatchString("Two plus three is {?Write(2+3);?} ");
Result: "Two plus three is 5 ";


*SOURCE org/mathpiper/builtin/procedures/core/PatchString.java
==========
*CMD PipeFromString --- connect current input to a string
*CORE
*CALL
	PipeFromString(str) body;

*PARMS

{str} -- a string containing the text to parse

{body} -- expression to be evaluated

*DESC

The commands in "body" are executed, but everything that is read
from the current input is now read from the string "str". The
result of "body" is returned.

*E.G.

In> PipeFromString("2+5; this is never read") res := ParseMathPiper();
Result: 2+5;

In> PipeFromString("2+5; this is never read") res := Eval(ParseMathPiper());
Result: 7;

*SEE PipeToString, PipeFromFile, ParseMathPiper, ParseMathPiperToken

*SOURCE org/mathpiper/builtin/procedures/core/PipeFromString.java
==========
*CMD PipeToStdout --- select initial output stream for output
*CORE
*CALL
	PipeToStdout() body

*PARMS

{body} -- expression to be evaluated

*DESC

When using {PipeToString} or {PipeToFile}, it might happen that something needs to be
written to the standard default initial output (typically the screen). {PipeToStdout} can be used to select this stream.

*E.G.

In> PipeToString() {Echo("aaaa"); PipeToStdout() Echo("bbbb");};
	bbbb
Result: "aaaa
	"

*SEE PipeToString, PipeToFile

*SOURCE org/mathpiper/builtin/procedures/core/PipeToStdout.java
==========
*CMD PipeToString --- connect current output to a string
*CORE
*CALL
	PipeToString() body

*PARMS

{body} -- expression to be evaluated

*DESC

The commands in "body" are executed. Everything that is printed on
the current output, by {Echo} for instance, is
collected in a string and this string is returned.

*E.G.

In> str := PipeToString() {WriteString("The square of 8 is "); Write(8^2);};
Result: "The square of 8 is  64";

*SEE PipeFromFile, PipeFromString, Echo, Write, WriteString

*SOURCE org/mathpiper/builtin/procedures/core/PipeToString.java
==========
*CMD Postfix --- define procedure syntax (postfix operator)
*CORE
*CALL
	Postfix("op")
	Postfix("op", precedence)

*PARMS

{"op"} -- string, the name of a procedure

{precedence} -- nonnegative integer (evaluated)

*DESC

Declares a special syntax for the procedure to be parsed as a bodied, infix, postfix,
or prefix operator.

"Postfix" procedures must have one argument and are syntactically placed after their argument.

Function name can be any string but meaningful usage and readability would
require it to be either made up entirely of letters or entirely of non-letter
characters (such as "+", ":" etc.).
Precedence is optional (will be set to 0 by default).

*E.G.
In> todo

*SEE Bodied?, PrecedenceGet, Bodied, Infix, Prefix

*SOURCE org/mathpiper/builtin/procedures/core/Postfix.java
==========
*CMD Postfix? --- check for procedure syntax
*CORE
*CALL
	Postfix?("op")

*PARMS

{"op"} -- string, the name of a procedure

*DESC

Check whether the procedure with given name {"op"} has been declared as a
"bodied", infix, postfix, or prefix operator, and  return {True} or {False}.

*E.G.

In> Postfix?("++");
Result: True;

*SEE Bodied, PrecedenceGet,Bodied?,Infix?,Prefix?

*SOURCE org/mathpiper/builtin/procedures/core/Postfix_.java
==========
*CMD PrecedenceGet --- get operator precedence
*CORE
*CALL
	PrecedenceGet("op")

*PARMS

{"op"} -- string, the name of a function

*DESC

Returns the precedence of the function named "op" which should have been declared as a bodied function or an infix, postfix, or prefix operator. Generates an error message if the string str does not represent a type of function that can have precedence.

For infix operators, right precedence can differ from left precedence. Bodied functions and prefix operators cannot have left precedence, while postfix operators cannot have right precedence; for these operators, there is only one value of precedence.

*E.G.
In> PrecedenceGet("+")
Result: 6;

*SEE LeftPrecedenceGet,RightPrecedenceGet,LeftPrecedenceSet,RightPrecedenceSet,RightAssociativeSet

*SOURCE org/mathpiper/builtin/procedures/core/PrecedenceGet.java
==========
*CMD Prefix --- define procedure syntax (prefix operator)
*CORE
*CALL
	Prefix("op")
	Prefix("op", precedence)

*PARMS

{"op"} -- string, the name of a procedure

{precedence} -- nonnegative integer (evaluated)

*DESC

"Prefix" procedures must have one argument and are syntactically placed before their argument.

Function name can be any string but meaningful usage and readability would
require it to be either made up entirely of letters or entirely of non-letter
characters (such as "+", ":" etc.).
Precedence is optional (will be set to 0 by default).

*E.G.
In> YY x := x+1;
	CommandLine(1) : Error parsing expression

In> Prefix("YY", 2)
Result: True;

In> YY x := x+1;
Result: True;

In> YY YY 2*3
Result: 12;

Note that, due to a current parser limitation, a procedure atom that is declared prefix cannot be used by itself as an argument.

In> YY
	CommandLine(1) : Error parsing expression

*SEE Bodied?, PrecedenceGet, Bodied, Infix, Postfix

*SOURCE org/mathpiper/builtin/procedures/core/Prefix.java
==========
*CMD Prefix? --- check for procedure syntax
*CORE
*CALL
	Prefix?("op")

*PARMS

{"op"} -- string, the name of a procedure

*DESC

Check whether the procedure with given name {"op"} has been declared as a
"bodied", infix, postfix, or prefix operator, and  return {True} or {False}.

*E.G.

In> Prefix?("-")
Result: True

*SEE Bodied, PrecedenceGet,Bodied?,Infix?,Postfix?

*SOURCE org/mathpiper/builtin/procedures/core/Prefix_.java
==========
*CMD Prepend! --- nondestructively prepend an expression to a list

*CALL
        Prepend(list, expr)

*PARMS

{list} -- list to prepend "expr" to

{expr} -- expression to prepend to the list

*DESC

This procedure makes a copy of {list}, and prepends a value to
the copy of the list without changing the original list.

*E.G.

In> lst := [_a,_b,_c,_d];
Result: [_a,_b,_c,_d]

In> Prepend(lst, 1);
Result: [1,_a,_b,_c,_d]

In> lst;
Result: [_a,_b,_c,_d]

*SEE Prepend!, Append!

*SOURCE org/mathpiper/builtin/procedures/core/Prepend.java
==========
*CMD Prepend! --- destructively prepend an expression to a list

*CALL
        Prepend!(list, expr)

*PARMS

{list} -- list to prepend "expr" to

{expr} -- expression to prepend to the list

*DESC

This procedure prepends a value to a list.

Destructive commands run faster than their nondestructive counterparts
because the latter copy the list before they alter it.

*E.G.

In> lst := [_a,_b,_c,_d];
Result: [_a,_b,_c,_d]

In> Prepend!(lst, 1);
Result: [1,_a,_b,_c,_d]

In> lst;
Result: [1,_a,_b,_c,_d]

*SEE Prepend, Append!

*SOURCE org/mathpiper/builtin/procedures/core/Prepend__.java
==========
*CMD ProcedureToList --- convert a procedure to a list
*CORE
*CALL
	ProcedureToList(expr)

*PARMS

{expr} -- expression to be converted

*DESC
Source: ProcedureToList.java
The parameter "expr" is expected to be a compound object, i.e. not
an atom. It is evaluated and then converted to a list. The car entry
in the list is the top-level operator in the evaluated expression and
the other entries are the arguments to this operator. Finally, the
list is returned.

*EXAMPLES
In> ProcedureToList(Cos('x)) 
Result: [Cos,x]

In> ProcedureToList(3*_a) 
Result: [*,3,_a]

*SEE List, ListToProcedure, Atom?

*SOURCE org/mathpiper/builtin/procedures/core/ProcedureToList.java
==========
*CMD Procedure? --- test for a composite object
*CORE
*CALL
	Procedure?(expr)

*PARMS

{expr} -- expression to test

*DESC

This procedure tests whether "expr" is a composite object, i.e. not an
atom. This includes not only obvious procedures such as {f(x)}, but also expressions such as {x+5} and lists.

*E.G.

In> Procedure?(x+5);
Result: True;

In> Procedure?(x);
Result: False;

*SEE Atom?, List?, Type, Operator?

*SOURCE org/mathpiper/builtin/procedures/core/Procedure_.java
==========
*CMD Profile --- measure the time taken by an evaluation

*CALL
	Profile() expr
*PARMS
{expr} -- any expression

*DESC
The procedure {Profile() expr} evaluates the expression {expr} and returns a Java
HashMap that contains the names of all the procedures that were called
during the evaluation along with the amount of time each procedure took
in nanoseconds.

The procedure also prints the names of all of the procedures with their elapsed
times in milliseconds.

Note: each procedure's elapsed time is the combined time for all instances of
that procedure that were called.

*E.G.
In> Profile() 2 * 3
Result: class java.util.HashMap
Side Effects:
Sequence 8901
:= 1878
Eval 1678
Decide 1438
/` 1415
MacroAssign 1259
ApplyFast 810
MacroSubstituteApply 751
LocalSymbols 631
Factor 612
ForEach 574
While 566
Insert! 456
List 427
If 408
JavaCall 404
MacroMapArgs 374
ListToProcedure 372
Concat 367
ReduceToMathPiper 361
MacroMapSingle 360
/: 294
MapSingle 256
RulebaseEvaluateArguments 225
=? 130
Assign 114
Nth 113
And? 103
CheckParametersMadeLocal 102
LocPredicate 100
Equal? 95
Check 92
Not? 70
Apply 67
Else 67
MathPiperToReduce 64
!? 64
&? 49
+ 48
Length 48
JavaAccess 46
ToString 46
PatternsCompile 36
List? 32
Atom? 31
Procedure? 30
PatternCompile 23
Number? 22
First 17
--> 16
Hold 15
DefinePattern 14
Local 14
Rest 13
Or? 11
JavaNew 11
String? 11
Unholdable 10
' 8
ProcedureToList 7
MacroLocal 7
!=? 6
ToAtom 6
$HandleFactor17 5
Generic? 5
Procedure 5
Integer? 5
GreaterThan? 4
Type 4
Association 4
TemplateProcedure 3
JavaToValue 3
|? 3
MathNth 3
RuleEvaluateArguments 2
Reverse! 2
MakeVector 2
Lambda 2
<=? 1
BuiltinAssociation 1
TreeProcess 1
>=? 1
StringTrim 1
StringSubstring 1
<? 1
StringEndsWith? 1
- 1
PatternCreate 0
Boolean? 0
PipeFromString 0
LessThan? 0
AddN 0
Macro 0
* 0
RulePatternEvaluateArguments 0
RulebaseDefined 0
Append! 0
HoldArgument 0
UnFence 0
ExceptionCatch 0
HasProcedure? 0
RulebaseHoldArguments 0
ParseMathPiper 0
ConcatStrings 0
RuleHoldArguments 0
Retract 0
SubtractN 0
-> 0
UnderscoreConstant? 0
Variable? 0
DefinedConstant? 0
MultiplyN 0
MacroRulebaseHoldArguments 0
FlatCopy 0

*SEE Trace, TraceSome, TraceExcept


*SOURCE org/mathpiper/builtin/procedures/core/Profile.java
==========
*CMD PromptShown? --- test for the MathPiper prompt option
*CORE
*CALL
	PromptShown?()

*DESC
Returns {False} if MathPiper has been started with the option to suppress the prompt, and {True} otherwise.


*SOURCE org/mathpiper/builtin/procedures/core/PromptShown_.java
==========
*CMD QuotientN --- integer division result is an integer (arbitrary-precision math function)
*CORE
*CALL
	QuotientN(x,y)

*DESC

This command performs the calculation of an elementary mathematical
function.  The arguments <i>must</i> be numbers.  The reason for the
postfix {N} is that the library needs to define equivalent non-numerical
functions for symbolic computations, such as {Exp}, {Sin}, etc.

Note that all xxxN functions accept integers as well as floating-point numbers.
The resulting values may be integers or floats.  If the mathematical result is an
exact integer, then the integer is returned.  For example, {Sqrt(25)} returns
the integer {5}, and {Power(2,3)} returns the integer {8}.  In such cases, the
integer result is returned even if the calculation requires more digits than set by
{BuiltinPrecisionSet}.  However, when the result is mathematically not an integer,
the functions return a floating-point result which is correct only to the current precision.

*E.G.
In>
Result:


*SOURCE org/mathpiper/builtin/procedures/core/Quotient.java
==========
*CMD Replace --- replace an entry in a list

*CORE

*CALL
	Replace(list, n, expr)

*PARMS

{list} -- list of which an entry should be replaced

{n} -- index of entry to replace

{expr} -- expression to replace the n-th entry with

*DESC

The n-th entry of "list" is replaced by the expression
"expr". This is equivalent to calling {Delete} and
{Insert} in sequence. To be precise, the expression
{Replace(list, n, expr)} has the same result as the
expression {Insert(Delete(list, n), n, expr)}.

*E.G.

In> Replace('[a,b,c,d,e,f], 4, 'x);
Result: [a,b,c,x,e,f];

*SEE Delete, Insert, Replace!

*SOURCE org/mathpiper/builtin/procedures/core/Replace.java
==========
*CMD Replace! --- replace an entry destructively in a list

*CORE

*CALL
	Replace!(list, n, expr)

*PARMS

{list} -- list of which an entry should be replaced

{n} -- index of entry to replace

{expr} -- expression to replace the n-th entry with

*DESC

This is the destructive counterpart of {Replace}. This
command yields the same result as the corresponding call to
{Replace}, but the original list is modified. So if a
variable is bound to "list", it will now be bound to the list with
the expression "expr" inserted.

Destructive commands run faster than their nondestructive counterparts
because the latter copy the list before they alter it.

*E.G.

In> lst := [_a,_b,_c,_d,_e,_f];
Result: [_a,_b,_c,_d,_e,_f];

In> Replace(lst, 4, _x);
Result: [_a,_b,_c,_x,_e,_f];

In> lst;
Result: [_a,_b,_c,_d,_e,_f];

In> Replace!(lst, 4, _x);
Result: [_a,_b,_c,_x,_e,_f];

In> lst;
Result: [_a,_b,_c,_x,_e,_f];

*SEE Replace, Delete!, Insert!

*SOURCE org/mathpiper/builtin/procedures/core/Replace__.java
==========
*CMD Rest --- returns a list without its car element
*CORE
*CALL
	Rest(list)

*PARMS

{list} -- a list

*DESC

This function returns "list" without its car element.

*EXAMPLES
In> Rest('[a,b,c]) 
Result: [b,c]

*SEE First, Length

*SOURCE org/mathpiper/builtin/procedures/core/Rest.java
==========
*CMD Retract --- delete rules for a procedure
*CORE
*CALL
	Retract("procedure",arity)

*PARMS
{"procedure"} -- string, name of procedure

{arity} -- positive integer or All

*DESC

Remove a rulebase for the procedure named {"procedure"} with the specific {arity}, if it exists. This will make
MathPiper forget all rules defined for a given procedure with the given arity. Rules for procedures with
the same name but different arities are not affected unless the All constant is used.  If All is used for the
arity, then all arities of the rulebase are removed.

Assignment {:=} of a procedure automatically does a single arity retract to the procedure being (re)defined.

*SEE RulebaseArgumentsList, RulebaseHoldArguments, :=

*SOURCE org/mathpiper/builtin/procedures/core/Retract.java
==========
*CMD Reverse! --- reverse a list destructively
*CORE
*CALL
	Reverse!(list)

*PARMS

{list} -- list to reverse

*DESC

This command reverses "list" in place, so that the original is
destroyed. This means that any variable bound to "list" will now have
an undefined content, and should not be used any more.
The reversed list is returned.

Destructive commands are faster than their nondestructive
counterparts. {Reverse} is the non-destructive version of
this function.

*EXAMPLES
In> lst := '[a,b,c,13,19] 
Result: [a,b,c,13,19]

In> revlst := Reverse!(lst) 
Result: [19,13,c,b,a]

Notice that the original list has been destroyed.

In> lst 
Result: [a]

*SEE FlatCopy, Reverse

*SOURCE org/mathpiper/builtin/procedures/core/Reverse__.java
==========
*CMD RightAssociativeSet --- declare associativity
*CORE
*CALL
	RightAssociativeSet("op")

*PARMS

{"op"} -- string, the name of a function

*DESC
This makes the operator right-associative. For example:
	RightAssociativeSet("*")
would make multiplication right-associative. Take care not to abuse this
function, because the reverse, making an infix operator left-associative, is
not implemented. (All infix operators are by default left-associative until
they are declared to be right-associative.)

*SEE LeftPrecedenceGet,RightPrecedenceGet,LeftPrecedenceSet,RightPrecedenceSet,OperatorsGet,OperatorSpacesSet,LeftSpacesGet,RightSpacesGet

*SOURCE org/mathpiper/builtin/procedures/core/RightAssociativeSet.java
==========
*CMD RightPrecedenceGet --- get operator precedence
*CORE
*CALL
	RightPrecedenceGet("op")

*PARMS

{"op"} -- string, the name of a function

*DESC

Returns the precedence of the function named "op" which should have been declared as a bodied function or an infix, postfix, or prefix operator. Generates an error message if the string str does not represent a type of function that can have precedence.

For infix operators, right precedence can differ from left precedence. Bodied functions and prefix operators cannot have left precedence, while postfix operators cannot have right precedence; for these operators, there is only one value of precedence.

*E.G.
In> RightPrecedenceGet("+")
Result: 70

*SEE LeftPrecedenceGet,LeftPrecedenceSet,RightPrecedenceSet,RightAssociativeSet,OperatorsGet,OperatorSpacesSet,LeftSpacesGet,RightSpacesGet

*SOURCE org/mathpiper/builtin/procedures/core/RightPrecedenceGet.java
==========
*CMD RightPrecedenceSet --- set operator precedence
*CORE
*CALL
	RightPrecedenceSet("op",precedence)

*PARMS

{"op"} -- string, the name of a function

{precedence} -- nonnegative integer

*DESC

{"op"} should be an infix operator. This function call tells the
infix expression printer to bracket the right hand side of
the expression if its precedence is larger than precedence.

This functionality was required in order to display expressions like {a-(b-c)}
correctly. Thus, {a+b+c} is the same as {a+(b+c)}, but {a-(b-c)} is not
the same as {a-b-c}.

Note that the right precedence of an infix operator does not affect the way MathPiper 
interprets expressions typed by the user. You cannot make MathPiper parse {a-b-c} as 
{a-(b-c)} unless you declare the operator "{-}" to be right-associative.

*SEE LeftPrecedenceGet,RightPrecedenceGet,LeftPrecedenceSet,RightAssociativeSet,OperatorsGet,OperatorSpacesSet,LeftSpacesGet,RightSpacesGet

*SOURCE org/mathpiper/builtin/procedures/core/RightPrecedenceSet.java
==========
*CMD RightSpacesGet --- return the number of spaces that are placed to the right of an operator when it is unparsed
*CALL
    RightSpacesGet(operatorName, operatorType)

*PARMS

{operatorName} -- string, the name of an operator
{operatorType} -- "Prefix", "Infix", or "Postfix"

*DESC
This procedure returns the number of spaces that are placed to the right of an operator when it is unparsed.

*EXAMPLES
In> RightSpacesGet("+", "Infix") 
Result: " "

In> RightSpacesGet("+", "Prefix") 
Result: ""

*SEE LeftSpacesGet,LeftPrecedenceGet,LeftPrecedenceSet,RightPrecedenceSet,RightAssociativeSet,OperatorsGet,OperatorSpacesSet

*SOURCE org/mathpiper/builtin/procedures/core/RightSpacesGet.java
==========
*CMD RoundToN --- rounds a decimal number to a given precision
*CORE
*CALL
	RoundToN(decimalNumber, precision)

*PARMS
{decimalNumber} -- a decimal number to be rounded
{precision} -- precision to round the number to

*DESC

This command rounds a decimal number to a given precision.

*E.G.
In> RoundToN(7.57809824,2)
Result> 7.6


*SOURCE org/mathpiper/builtin/procedures/core/RoundToN.java
==========
*CMD RuleEvaluateArguments --- define rules in procedures
*CORE
*DESC

This procedure has the same effect as its non-macro counterpart, except
that its arguments are evaluated before the required action is performed.
This is useful in macro-like procedures or in procedures that need to define new
rules based on parameters.

Make sure that the arguments of {Macro}... commands evaluate to expressions that would normally be used in the non-macro version!

*SEE Assign, Unassign, Local, RulebaseHoldArguments, RuleHoldArguments, /`, MacroAssign, MacroUnassign, MacroLocal, MacroRulebaseHoldArguments, MacroRulebaseListedHoldArguments

*SOURCE org/mathpiper/builtin/procedures/core/RuleEvaluateArguments.java
==========
*CMD RuleHoldArguments --- define a rewrite rule
*CORE
*CALL
	RuleHoldArguments("operator", arity, precedence, predicate) body
*PARMS

{"operator"} -- string, name of function

{arity}, {precedence} -- integers

{predicate} -- function returning boolean

{body} -- expression, body of rule

*DESC

Define a rule for the function "operator" with
"arity", "precedence", "predicate" and
"body". The "precedence" goes from low to high: rules with low precedence will be applied first.

The arity for a rules database equals the number of arguments. Different
rules databases can be built for functions with the same name but with
a different number of arguments.

Rules with a low precedence value will be tried before rules with a high value, so
a rule with precedence 0 will be tried before a rule with precedence 1.

*SOURCE org/mathpiper/builtin/procedures/core/RuleHoldArguments.java
==========
*CMD RulePatternEvaluateArguments --- defines a rule which uses a pattern as its predicate

*CALL
	RulePatternEvaluateArguments("operator", arity, precedence, pattern) body
*PARMS

{"operator"} -- string, name of function

{arity}, {precedence} -- integers

{pattern} -- a pattern object

{body} -- expression, body of rule

*DESC
This function defines a rule which uses a pattern as its predicate.

*SEE RulePatternHoldArguments

*SOURCE org/mathpiper/builtin/procedures/core/RulePatternEvaluateArguments.java
==========
*CMD RulePatternHoldArguments --- defines a rule which uses a pattern as its predicate
 
*CALL
	RulePatternHoldArguments("operator", arity, precedence, pattern) body
*PARMS

{"operator"} -- string, name of function

{arity}, {precedence} -- integers

{pattern} -- a pattern object

{body} -- expression, body of rule

*DESC
This function defines a rule which uses a pattern as its predicate.

*SEE RulePatternEvaluateArguments

*SOURCE org/mathpiper/builtin/procedures/core/RulePatternHoldArguments.java
==========
*CMD RulebaseArgumentsList --- obtain list of arguments
*CORE
*CALL
	RulebaseArgumentsList("operator", arity)

*PARMS
{"operator"} -- string, name of function

{arity} -- integer

*DESC

Returns a list of atoms, symbolic parameters specified in the {Rulebase} call
for the function named {"operator"} with the specific {arity}.

*SEE RulebaseHoldArguments, HoldArgumentNumber, HoldArgument

*SOURCE org/mathpiper/builtin/procedures/core/RulebaseArgumentsList.java
==========
*CMD RulebaseDefined --- predicate procedure which indicates whether or not a rulebase is defined.
*CORE
*CALL
    RulebaseDefined(name)

*PARMS

{name} -- string, name of rulebase

*DESC
This is a predicate procedure which indicates whether or not a rulebase is defined.


*SOURCE org/mathpiper/builtin/procedures/core/RulebaseDefined.java
==========
*CMD RulebaseDump --- prints the rules in a rulebase if the rulebase exists
*CALL
    RulebaseDump("string")

 *PARMS
 {"string"} -- a string which contains the name of the rulebase

*DESC
This function prints information about each rule in a rulebase if the rulebase exists.


*SOURCE org/mathpiper/builtin/procedures/core/RulebaseDump.java
==========
*CMD RulebaseEvaluateArguments --- define rules in procedures
*CORE
*DESC

This procedure has the same effect as its non-macro counterpart, except
that its arguments are evaluated before the required action is performed.
This is useful in macro-like procedures or in procedures that need to define new
rules based on parameters.

Make sure that the arguments of {Macro}... commands evaluate to expressions that would normally be used in the non-macro version!

*SEE Assign, Unassign, Local, RulebaseHoldArguments, RuleHoldArguments, /`, MacroAssign, MacroUnassign, MacroLocal, RulebaseListedEvaluateArguments, RuleEvaluateArguments

*SOURCE org/mathpiper/builtin/procedures/core/RulebaseEvaluateArguments.java
==========
*CMD RulebaseHoldArguments --- define procedure with a fixed number of arguments
*CORE
*CALL
	RulebaseHoldArguments(name,params)

*PARMS

{name} -- string, name of procedure

{params} -- list of arguments to procedure

*DESC
Define a new rules table entry for a
procedure "name", with {params} as the parameter list. Name can be
either a string or simple atom.

In the context of the transformation rule declaration facilities
this is a useful procedure in that it allows the stating of argument
names that can he used with HoldArgument.

Functions can be overloaded: the same procedure can be defined
with different number of arguments.


*SEE MacroRulebaseHoldArguments, RulebaseListedHoldArguments, MacroRulebaseListedHoldArguments, HoldArgument, Retract

*SOURCE org/mathpiper/builtin/procedures/core/RulebaseHoldArguments.java
==========
*CMD RulebaseListedEvaluateArguments --- define rules in procedures
*CORE
*DESC

This procedure has the same effect as its non-macro counterpart, except
that its arguments are evaluated before the required action is performed.
This is useful in macro-like procedures or in procedures that need to define new
rules based on parameters.

Make sure that the arguments of {Macro}... commands evaluate to expressions that would normally be used in the non-macro version!

*SEE Assign, Unassign, Local, RulebaseHoldArguments, RuleHoldArguments, /`, MacroAssign, MacroUnassign, MacroLocal, MacroRulebaseHoldArguments, RuleEvaluateArguments

*SOURCE org/mathpiper/builtin/procedures/core/RulebaseListedEvaluateArguments.java
==========
*CMD RulebaseListedHoldArguments --- define procedure with variable number of arguments
*CORE
*CALL
	RulebaseListedHoldArguments("name", params)

*PARMS

{"name"} -- string, name of procedure

{params} -- list of arguments to procedure

*DESC

The command {RulebaseListedHoldArguments} defines a new procedure. It essentially works the
same way as {RulebaseHoldArguments}, except that it declares a new procedure with a variable
number of arguments. The list of parameters {params} determines the smallest
number of arguments that the new procedure will accept. If the number of
arguments passed to the new procedure is larger than the number of parameters in
{params}, then the last argument actually passed to the new procedure will be a
list containing all the remaining arguments.

A procedure defined using {RulebaseListedHoldArguments} will appear to have the arity equal
to the number of parameters in the {param} list, and it can accept any number
of arguments greater or equal than that. As a consequence, it will be impossible to define a 
new procedure with the same name and with a greater arity.

The procedure body will know that the procedure is passed more arguments than the
length of the {param} list, because the last argument will then be a list. The
rest then works like a {Rulebase}-defined procedure with a fixed number of
arguments. Transformation rules can be defined for the new procedure as usual.


*E.G.

The definitions

    RulebaseListedHoldArguments("f",["a", "b", "c"]);
    10 ## f(_a,_b,[_c,_d]) --> Echo(["four args",a,b,c,d]);
    20 ## f(_a,_b,c_List?) --> Echo(["more than four args",a,b,c]);
    30 ## f(_a,_b,_c) --> Echo(["three args",a,b,c]);
	
give the following interaction:
In> Function() f(_a); Function() f(_a,_b);

In> f(_A) 
Result: f(_A);

In> f(_A,_B) 
Result: f(_A,_B);

In> f(_A,_B,_C)
Result: True;
Side Effects:
three args _A _B _C

In> f(_A,_B,_C,_D)
Result: True
Side Effects:
four args _A _B _C _D

In> f(_A,_B,_C,_D,_E)
Result: True
Side Effects:
more than four args _A _B [_C,_D,_E]

In> f(_A,_B,_C,_D,_E,_E)
Result: True
Side Effects:
more than four args _A _B [_C,_D,_E,_E]

The procedure {f} now appears to occupy all arities greater than 3:

In> RulebaseHoldArguments("f", {x,y,z,t});
	CommandLine(1) : Rule base with this arity already defined


*SEE RulebaseHoldArguments, Retract, Echo

*SOURCE org/mathpiper/builtin/procedures/core/RulebaseListedHoldArguments.java
==========
*CMD SecD --- double-precision math function
*CORE
*CALL
	SecD(x)

*PARMS
{x} -- a number

*DESC
A double precision version of the Sec function.


*EXAMPLES
In> SecD(.7) 
Result: 1.30745926

In> SecD(-1.2) 
Result: 2.759703601
*SEE SinD, CosD, TanD, CscD, CotD, ArcSinD, ArcCosD, ArcTanD, ArcCscD, ArcSecD, ArcCotD

*SOURCE org/mathpiper/builtin/procedures/core/SecD.java
==========
*CMD Secure --- guard the host OS
*CORE
*CALL
	Secure(body)

*PARMS

{body} -- expression

*DESC

{Secure} evaluates {body} in a "safe" environment, where files cannot be opened
and system calls are not allowed. This can help protect the system
when e.g. a script is sent over the Internet to be evaluated on a remote computer,
which is potentially unsafe.


*SOURCE org/mathpiper/builtin/procedures/core/Secure.java
==========
*CMD Sequence --- block of expressions
*CORE
*CALL
	Sequence(expression1, expression2, ...)

*PARMS

{expression1}, {expression2} -- expressions

*DESC

The {Sequence} and the {&#123; ... &#125;} construct have the same effect: they evaluate all
arguments in order and return the result of the last evaluated expression.

{Sequence(_a,_b);} is the same as typing {&#123;_a;_b;&#125;} and is very useful for writing out
procedure bodies. The {&#123; ... &#125;} construct is a syntactically nicer version of the
{Sequence} call; it is converted into {Sequence(...)} during the parsing stage.

*SEE {, }

*SOURCE org/mathpiper/builtin/procedures/core/Sequence.java
==========
*CMD SetExactBitsN --- manipulate precision of floating-point numbers
*CORE
*CALL
	SetExactBitsN(x,bits)

*PARMS
{x} -- an expression evaluating to a floating-point number

{bits} -- integer, number of bits

*DESC
Each floating-point number in MathPiper has an internal precision counter that 
stores the number of exact bits in the mantissa. The number of exact bits is 
automatically updated after each arithmetic operation to reflect the gain or 
loss of precision due to round-off.
The procedure {SetExactBitsN} sets the precision flags of individual number objects.

This function is only meaningful for floating-point numbers.
(All integers are always exact.)
For integer {x}, the function {SetExactBitsN} returns the unmodified integer {x}.

*REM FIXME - these examples currently do not work because of bugs

*E.G.
The default precision of 10 decimals corresponds to 33 bits:

In> GetExactBitsN(1000.123)
Result: 33

In> x:=SetExactBitsN(10., 20)
Result: 10.

In> GetExactBitsN(x)
Result: 20
Prepare a "floating zero" representing an interval [-4, 4]:

In> x:=SetExactBitsN(0., -2)
Result: 0.

In> x=0
Result: True

*SEE BuiltinPrecisionSet, BuiltinPrecisionGet, GetExactBitsN

*SOURCE org/mathpiper/builtin/procedures/core/SetExactBits.java
==========
*CMD ShiftLeft --- built-in bitwise shift left operation
*CORE
*CALL
	ShiftLeft(expr,bits)

*DESC

Shift bits to the left.

*SEE ShiftRight

*SOURCE org/mathpiper/builtin/procedures/core/ShiftLeft.java
==========
*CMD ShiftRight --- built-in bitwise shift right operation
*CORE
*CALL
	ShiftRight(expr,bits)

*DESC

Shift bits to the right.

*SEE ShiftLeft

*SOURCE org/mathpiper/builtin/procedures/core/ShiftRight.java
==========
*CMD SinD --- double-precision math function
*CORE
*CALL
	SinD(x)

*PARMS
{x} -- a number

*DESC
A double precision version of the Sin function.


*EXAMPLES
In> SinD(.7) 
Result: 0.6442176872

In> SinD(-1.2) 
Result: -0.932039086
*SEE CosD, TanD, CscD, SecD, CotD, ArcSinD, ArcCosD, ArcTanD, ArcCscD, ArcSecD, ArcCotD

*SOURCE org/mathpiper/builtin/procedures/core/SinD.java
==========
*CMD SqrtD --- double-precision math function
*CORE
*CALL
	SinD(x)

*PARMS
{x} -- a number

*DESC
A numerical version of the Sqrt function. The reason for the postfix {D} is the library needs 
to define equivalent non-numerical functions for symbolic computations, such as {Sin}.


*E.G.
In> SinD(.7)
Result: 0.6442176872


*SOURCE org/mathpiper/builtin/procedures/core/SqrtD.java
==========
*CMD StackTrace --- shows the current state of the user procedure stack and the built in procedure stack
*CALL
    StackTrace()

*DESC
This procedure shows the current state of the user procedure stack and the built in procedure stack.

It is currently somewhat difficult to follow the stack traces at points where user procedures call built in
procedures and vice versa because there are no clear markers which indicate where control leave one stack
and enters the other.  However, even with this difficulty, the StackTrace procedure has still been proven
to be a useful debugging tool.

*E.G.
/%mathpiper
TestFunction() :=
[
    index := 1;
    While(index < 10)
    [
        If(index = 5, StackTrace());

        index++;
    ];

];
/%/mathpiper


In> TestFunction()
Result: True
Side Effects:


========================================= Start Of Built In Function Stack Trace
0: Sequence
   1: -> TestFunction()
-----------------------------------------
2: Sequence
   3: -> index:=1
   4: -> While(index<10)[
    If(index=5,StackTrace());
    index++;
]

-----------------------------------------
5: index<10
-----------------------------------------
6: [
    If(index=5,StackTrace());
    index++;
]

-----------------------------------------
7: Sequence
   8: -> If(index=5,StackTrace())
   9: -> index++
-----------------------------------------
10: index=5
-----------------------------------------
11: {StackTrace()}
-----------------------------------------
12: StackTrace
========================================= End Of Built In Function Stack Trace

****** THE PROBLEM IS EITHER IMMEDIATELY ABOVE THIS LINE OR IMMEDIATELY BELOW THIS LINE ******

========================================= Start Of User Function Stack Trace
0: Sequence
-----------------------------------------
1: Sequence
-----------------------------------------
2: TestFunction
-----------------------------------------
3: Sequence
-----------------------------------------
4: <START>
========================================= End Of User Function Stack Trace

*SEE StackTraceOn, StackTraceOff, TraceSome, TraceExcept, TraceOn, TraceOff

*SOURCE org/mathpiper/builtin/procedures/core/StackTrace.java
==========
*CMD StackTraceOff --- clears the flag which will show a stack trace when an exception is thrown
*CALL
    StackTraceOff()

*DESC
This function clears the flag which will show the current state of the user function stack and the built in function stack
when an exception is thrown.

See the StackTraceOn function for more information.

*SEE StackTrace, StackTraceOn, TraceSome, TraceExcept, TraceOn, TraceOff

*SOURCE org/mathpiper/builtin/procedures/core/StackTraceOff.java
==========
*CMD StackTraceOn --- sets the flag which will show a stack trace when an exception is thrown
*CALL
    StackTraceOn()

*DESC
This function sets the flag which will show the current state of the user function stack and the built in function stack
when an exception is thrown.

It is currently somewhat difficult to follow the stack traces at points where user procedures call built in
functions and vice versa because there are no clear markers which indicate where control leave one stack
and enters the other.  However, even with this difficulty, the StackTrace function has still been proven
to be a useful debugging tool.

*E.G.
/%mathpiper

TestFunction() :=
[
    LessThan?(Complex(1,1),3);
];


StackTraceOn();

TestFunction();

StackTraceOff();

/%/mathpiper

    /%error,preserve="false"
      Result: In function "LessThan?" :
      bad argument number 1(counting from 1) :
      The first argument must be a non-complex decimal number or a string.
      The offending argument Complex(1,1) evaluated to Complex(1,1)


      ========================================= Start Of Built In Function Stack Trace
      0: LoadScript
         1: -> "/tmp/mathpiperide917565545585604790.mpw_tmp"
      -----------------------------------------
      2: Sequence
         3: -> LessThan?(Complex(1,1),3)
      -----------------------------------------
      4: LessThan?
         5: -> Complex(1,1)
         6: -> 3
      ========================================= End Of Built In Function Stack Trace

      ****** THE PROBLEM IS EITHER IMMEDIATELY ABOVE THIS LINE OR IMMEDIATELY BELOW THIS LINE ******

      ========================================= Start Of User Function Stack Trace
      0: Sequence
      -----------------------------------------
      1: TestFunction
      -----------------------------------------
      2: <START>
      ========================================= End Of User Function Stack Trace

       In function: TestFunction, Error near line 14

      Side Effects:
      Stack tracing is on.

.   /%/error

*SEE StackTrace, StackTraceOff, TraceSome, TraceExcept, TraceOn, TraceOff

*SOURCE org/mathpiper/builtin/procedures/core/StackTraceOn.java
==========
*CMD State --- return a list which contains the names and values of the global variables

*CALL 
 
 State()
 State(ShowProtected:True)
 State(ShowAll:True)
 


*DESC 
Return a list which contains the values of all the global variables.

*E.G. 

In> a := 1; b := 2; c := 3;
Result> 3

In> State()
Result> [a:1,b:2,c:3]


*SOURCE org/mathpiper/builtin/procedures/core/State.java
==========
*CMD StringCompareNatural --- compares strings naturally instead of lexicographically

*CALL
	StringCompareNatural(string1, string2)

*PARMS
{string1}, {string2} -- strings

*DESC
Compare strings naturally instead of lexicographically. Lexicongraphic
comparison considers "a10" to be less than "a2", while natural comparison
considers "a2" to be less than "a10". Leading zeros immediately before
numbers in a string are ignored.

{String1 < String2} returns a negative number

{String1 = String2} returns 0

{String1 > String2} returns a positive number

*EXAMPLES
In> StringCompareNatural("a", "a") 
Result: 0

In> StringCompareNatural("a", "b") 
Result: -1

In> StringCompareNatural("b", "a") 
Result: 1

In> LessThan?("a2", "a10") 
Result: False

In> StringCompareNatural("a2", "a10") 
Result: -1

*SEE LessThan?, GreaterThan?, Equal?

*SOURCE org/mathpiper/builtin/procedures/core/StringCompareNatural.java
==========
*CMD StringMidGet --- retrieve a substring
*CORE
*CALL
	StringMidGet(index,length,string)

*PARMS

{index} -- index of substring to get

{length} -- length of substring to get

{string} -- string to get substring from

*DESC

{StringMidGet} returns a part of a string. Substrings can also be
accessed using the {[]} operator.

*E.G.

In> StringMidGet(3,2,"abcdef")
Result: "cd";

In> "abcdefg"[2 .. 4]
Result: "bcd";

*SEE StringMidSet, Length

*SOURCE org/mathpiper/builtin/procedures/core/StringMidGet.java
==========
*CMD StringMidSet --- change a substring
*CORE
*CALL
	StringMidSet(index,substring,string)

*PARMS

{index} -- index of substring to get

{substring} -- substring to store

{string} -- string to store substring in.

*DESC

Set (change) a part of a string. It leaves the original alone, returning
a new changed copy.

*E.G.

In> StringMidSet(3,"XY","abcdef")
Result: "abXYef";

*SEE StringMidGet, Length

*SOURCE org/mathpiper/builtin/procedures/core/StringMidSet.java
==========
*CMD StringToUnicode --- returns the unicode value of the character in a single character string
*CORE
*CALL
	StringToUnicode(s)

*PARMS
 {s} - a single character string

*DESC
This function returns the unicode value of the character in a single character string.

*E.G.
In> StringToUnicode("A")
Result> 65


*SOURCE org/mathpiper/builtin/procedures/core/StringToUnicode.java
==========
*CMD String? --- test for an string
*CORE
*CALL
	String?(expr)

*PARMS

{expr} -- expression to test

*DESC

This function tests whether "expr" is a string. A string is a text
within quotes, e.g. {"rock"}.

*E.G.

In> String?("rock");
Result: True;

In> String?(rock);
Result: False;

*SEE Atom?, Number?

*SOURCE org/mathpiper/builtin/procedures/core/String_.java
==========
*CMD Substitute --- perform a substitution
*CORE
*CALL
	Substitute(from, to) expr

*PARMS

{from} -- expression to be substituted

{to} -- expression to substitute for "from"

{expr} -- expression in which the substitution takes place

*DESC

This function substitutes every occurrence of "from" in "expr" by
"to". This is a syntactical substitution: only places where "from"
occurs as a subexpression are affected.

Below, the explanation for the last result is that the expression {a+b+c} is internally 
stored as {(a+b)+c}. Hence {a+b} is a subexpression, but {b+c} is not.

*E.G.

In> Substitute(_x, Sin(_y)) _x^2+_x+1;
Result: Sin(_y)^2+Sin(_y)+1;

In> Substitute(ToAtom("+"), ToAtom("-")) _a+_b
Result: _a-_b

In> Substitute(ToAtom("And?"), ToAtom("+")) _x And? _y
Result: _x+_y

In> Substitute(_a+_b, _x) _a+_b+_c;
Result: _x+_c;

In> Substitute(_b+_c, _x) _a+_b+_c;
Result: _a+_b+_c;

Workaround:
In> tmp := Substitute(_c,_x-_b)  _a+_b+_c;
Result: _a+_b+_x-_b

In> tmp
Result: _a+_b+_x-_b

In> Expand(tmp)
Result: _a+_x

*SEE WithValue, /:, Where

*SOURCE org/mathpiper/builtin/procedures/core/Substitute.java
==========
*CMD SubtractN --- subtract two numbers (arbitrary-precision math function)
*CORE
*CALL
	SubtractN(x,y)

*DESC

This command performs the calculation of an elementary mathematical
function.  The arguments <i>must</i> be numbers.  The reason for the
postfix {N} is that the library needs to define equivalent non-numerical
functions for symbolic computations, such as {Exp}, {Sin}, etc.

Note that all xxxN functions accept integers as well as floating-point numbers.
The resulting values may be integers or floats.  If the mathematical result is an
exact integer, then the integer is returned.  For example, {Sqrt(25)} returns
the integer {5}, and {Power(2,3)} returns the integer {8}.  In such cases, the
integer result is returned even if the calculation requires more digits than set by
{BuiltinPrecisionSet}.  However, when the result is mathematically not an integer,
the functions return a floating-point result which is correct only to the current precision.

*E.G.
In>
Result:


*SOURCE org/mathpiper/builtin/procedures/core/Subtract.java
==========
*CMD Symbols --- declare variables to be symbols that evaluate to themselves
*CORE
*CALL
	Symbols(var, ...)

*PARMS

{var} -- name of variable to be declared a symbol

*DESC

When unassigned variables are evaluated, an exception is thrown.
It is useful for various procedures such as {Solve} and {SolveSteps}
to accept expressions that contain variables which evaluate to themselves
to represent unspecified values instead of using underscore constants
for this purpose.

Each variable that is passed to this procedure is assigned itself
as a value. This is equivalent to evaluating {var := 'var} for
each of these variables.

*E.G.

In> Unassign(a)
Result: True

In> a
Result: Exception
Exception: Error: The variable <a> does not have a value assigned to it. Starting at index 0.

In> Symbols(a)
Result: True

In> a
Result: a

In> Unassign(a)
Result: True

In> a
Result: Exception
Exception: Error: The variable <a> does not have a value assigned to it. Starting at index 0.


In> Symbols(a,b,c,x)
Result: True

In> a*x^2 + b*x + c
Result: (a*x^2 + b*x) + c


*SEE Unassign

*SOURCE org/mathpiper/builtin/procedures/core/Symbols.java
==========
*CMD SysOut --- similar to the Write procedure, except a copy of the output is also sent to Java's System.out stream
*CALL
    SysOut()

*DESC
If a procedure prints side effect output, the output is not displayed until the procedure returns.  If a procedure
throws an exception, the output may not be displayed at all.  Therefore, sometimes it is desireable to see
the output as it is printed instead of waiting until the procedure returns.  SysOut
is similar to the Write procedure, except it also sends a copy of its side effect output to Java's System.out
stream so that it can be viewed immediately.

*SEE Write

*SOURCE org/mathpiper/builtin/procedures/core/SysOut.java
==========
*CMD SystemTimer --- return the current time in nanoseconds
*CORE
*CALL
	SystemTimer()

*DESC
This function returns the current value of the system timer in milliseconds.

*E.G.
In> SystemTimer()
Result: 1624308347733;

*SEE Time, EchoTime


*SOURCE org/mathpiper/builtin/procedures/core/SystemTimer.java
==========
*CMD TanD --- double-precision math function
*CORE
*CALL
	TanD(x)

*PARMS
{x} -- a number

*DESC
A double precision version of the Tan function.


*EXAMPLES
In> TanD(.7) 
Result: 0.8422883805

In> TanD(-1.2) 
Result: -2.572151622
*SEE SinD, CosD, CscD, SecD, CotD, ArcSinD, ArcCosD, ArcTanD, ArcCscD, ArcSecD, ArcCotD

*SOURCE org/mathpiper/builtin/procedures/core/TanD.java
==========
*CMD Time --- measure the time taken by an evaluation
*CORE
*CALL
	Time() expr
*PARMS
{expr} -- any expression
*DESC
The procedure {Time() expr} evaluates the expression {expr} and returns the time needed for the evaluation.
The result is returned as a floating-point number of seconds.
The value of the expression {expr} is lost.

The result is the "user time" as reported by the OS, not the real ("wall clock") time.
Therefore, any CPU-intensive processes running alongside MathPiper will not significantly affect the result of {Time}.

*E.G.
In> Time() Simplify((a*b)/(b*a))
Result: 0.09;

*SEE EchoTime, SystemTimer


*SOURCE org/mathpiper/builtin/procedures/core/Time.java
==========
*CMD ToAtom --- convert string to atom
*CORE
*CALL
	ToAtom("string")

*PARMS

{"string"} -- a string

*DESC

Returns an atom with the string representation given
as the evaluated argument. Example: {ToAtom("foo");} returns
{foo}.


*E.G.

In> ToAtom("a")
Result: a;

*SEE ToString

*SOURCE org/mathpiper/builtin/procedures/core/ToAtom.java
==========
*CMD ToBase --- conversion of a number in decimal base to non-decimal base
*CORE
*CALL
	ToBase(base, number)

*PARMS

{base} -- integer, base to convert to/from

{number} -- integer, number to write out in a different base

{"string"} -- string representing a number in a different base

*DESC

In MathPiper, all numbers are written in decimal notation (base 10).
The two functions {FromBase}, {ToBase} convert numbers between base 10 and a different base.
Numbers in non-decimal notation are represented by strings.


*REM where is this p-adic capability? - sw
These functions use the p-adic expansion capabilities of the built-in
arbitrary precision math libraries.

Non-integer arguments are not supported.

*EXAMPLES
Write the (decimal) number {255} in hexadecimal notation:

In> ToBase(16,255) 
Result: "ff"

*SEE FromBase, PAdicExpand

*SOURCE org/mathpiper/builtin/procedures/core/ToBase.java
==========
*CMD ToString --- convert atom to string
*CORE
*CALL
	ToString(expression)

*PARMS

{expression} -- an expression

*DESC

This function converts a MathPiper expression into a string. If the expression is already a string,
it is returned unchanged.

*E.G.
In> ToString(a)
Result: "a";

In> ToString(x^2)
Result> "x^2"

*SEE ToAtom

*SOURCE org/mathpiper/builtin/procedures/core/ToString.java
==========
*CMD TraceExcept --- trace all the procedures but the given procedures an expression
*CORE
*CALL
	TraceExcept("procedure_name,procedure_name,procedure_name,...") expression

*PARMS

{"procedure_name,procedure_name,procedure_name,..."} -- a string which contains the names of procedures not to trace separated by commas.

{expression} -- an expression to trace.

*DESC

Outputs a trace of all the procedures which are evaluated in the given expression except those which are listed in the given string.  An empty
procedure list string means trace all of the procedures which are evaluated in the given expression.


*E.G.

In> TraceExcept("") 2+3-6 //An empty procedure list means trace all procedures.
Result> True
Side Effects>
Enter<**** user rulebase>{(-,2+3-6);
    Enter<**** user rulebase>{(+,2+3);
        Arg(2->2);
        Arg(3->3);
        Enter<builtin>{(Number?,Number?(x));
            Arg(x->2);
        Leave<builtin>}(Number?(x)->True);
        Enter<builtin>{(Number?,Number?(y));
            Arg(y->3);
        Leave<builtin>}(Number?(y)->True);
        **** Rule in procedure (+) matched: Precedence: 50, Parameters: arg1<hold=false>, arg2<hold=false>, Predicates: (Pattern) Number?(x), Number?(y), True,     Variables: x, y,    Types: Variable, Variable, Body: AddN(x,y)
        Enter<builtin>{(AddN,AddN(x,y));
            Arg(x->2);
            Arg(y->3);
        Leave<builtin>}(AddN(x,y)->5);
    Leave<**** user rulebase>}(2+3->5);
    Arg(2+3->5);
    Arg(6->6);
    Enter<builtin>{(List?,List?($x8));
        Arg($x8->5);
    Leave<builtin>}(List?($x8)->False);
    Enter<builtin>{(Number?,Number?(x));
        Arg(x->5);
    Leave<builtin>}(Number?(x)->True);
    Enter<builtin>{(Number?,Number?(y));
        Arg(y->6);
    Leave<builtin>}(Number?(y)->True);
    **** Rule in procedure (-) matched: Precedence: 50, Parameters: arg1<hold=false>, arg2<hold=false>, Predicates: (Pattern) Number?(x), Number?(y), True,     Variables: x, y,    Types: Variable, Variable, Body: SubtractN(x,y)
    Enter<builtin>{(SubtractN,SubtractN(x,y));
        Arg(x->5);
        Arg(y->6);
    Leave<builtin>}(SubtractN(x,y)->-1);
Leave<**** user rulebase>}(2+3-6->-1);


In> TraceExcept("List?, Number?") 2+3-6
Result> True
Side Effects>
Enter<**** user rulebase>{(-,2+3-6);
    Enter<**** user rulebase>{(+,2+3);
        Arg(2->2);
        Arg(3->3);
        **** Rule in procedure (+) matched: Precedence: 50, Parameters: arg1<hold=false>, arg2<hold=false>, Predicates: (Pattern) Number?(x), Number?(y), True,     Variables: x, y,    Types: Variable, Variable, Body: AddN(x,y)
        Enter<builtin>{(AddN,AddN(x,y));
            Arg(x->2);
            Arg(y->3);
        Leave<builtin>}(AddN(x,y)->5);
    Leave<**** user rulebase>}(2+3->5);
    Arg(2+3->5);
    Arg(6->6);
    **** Rule in procedure (-) matched: Precedence: 50, Parameters: arg1<hold=false>, arg2<hold=false>, Predicates: (Pattern) Number?(x), Number?(y), True,     Variables: x, y,    Types: Variable, Variable, Body: SubtractN(x,y)
    Enter<builtin>{(SubtractN,SubtractN(x,y));
        Arg(x->5);
        Arg(y->6);
    Leave<builtin>}(SubtractN(x,y)->-1);
Leave<**** user rulebase>}(2+3-6->-1);


 *SEE TraceSome, StackTrace, StackTraceOn, StackTraceOff, TraceOff, Profile


*SOURCE org/mathpiper/builtin/procedures/core/TraceExcept.java
==========
*CMD TraceOff --- disables a complete trace of all the procedures that are called when an expression is evaluated
*CALL
    TraceOff()

*DESC
This procedure disables a complete trace of all the procedures that are called when an expression is evaluated.

See TraceOn for more information.

*SEE StackTrace, StackTraceOn, StackTraceOff, TraceSome, TraceExcept, TraceOn, Profile

*SOURCE org/mathpiper/builtin/procedures/core/TraceOff.java
==========
*CMD TraceOn --- enables a complete trace of all the procedures that are called when an expression is evaluated
*CALL
    TraceOn()

*DESC
This procedure enables a complete trace of all the procedures that are called when an expression is evaluated.
The tracing output can become very long, very quickly so this form of complete tracing is only useful
for tracing relatively simple expressions.  TraceSome and TraceExcept can be used as an alternative to reduce
the amount of tracing output that is generated.

The first time a procedure is called during a MathPiper session, it needs to be loaded
and converted into Lisp code.  If tracing is enabled when procedures are being loaded, the loading code
will also be traced.  This loading code can be caused to not appear in the trace by simply evaluating the
expression to be traced once with tracing off and then evaluating it again with tracing on.

In the example below, the {output} attribute of the {%mathpiper} fold is set to {trace} so that the output
is placed into a {%mathpiper_trace} fold.  This will enable the trace output to be syntax highlighted.

*E.G.
/%mathpiper,output="trace"

TraceOn();

2 + 3;

TraceOff();

/%/mathpiper

    /%mathpiper_trace,preserve="false"
      Result: True

      Side Effects:
      Tracing is on.
          Enter<**** user rulebase>{(+, 2+3);
              Arg(arg1 ~> 2);
              Arg(arg2 ~> 3);
              Enter<builtin>{(Number?, Number?(x));
                  Arg(parameter1 ~> 2);
              Leave<builtin>}(Number?(x) ~> True,    Local variables: y ~> 3, x ~> 2, arg2 ~> 3, arg1 ~> 2, );
              Enter<builtin>{(Number?, Number?(y));
                  Arg(parameter1 ~> 3);
              Leave<builtin>}(Number?(y) ~> True,    Local variables: y ~> 3, x ~> 2, arg2 ~> 3, arg1 ~> 2, );
              **** Rule in procedure (+) matched: Precedence: 50, Parameters: arg1<hold=false>, arg2<hold=false>, Predicates: (Pattern) Number?(x), Number?(y), True,     Variables: x, y,     Types: Variable, Variable,    Body: AddN(x, y)
              Enter<builtin>{(AddN, AddN(x,y));
                  Arg(parameter1 ~> 2);
                  Arg(parameter2 ~> 3);
              Leave<builtin>}(AddN(x,y) ~> 5,    Local variables: y ~> 3, x ~> 2, arg2 ~> 3, arg1 ~> 2, );
          Leave<**** user rulebase>}(2+3 ~> 5,    Local variables: y ~> 3, x ~> 2, arg2 ~> 3, arg1 ~> 2, );
          Enter<builtin>{(TraceOff, TraceOff());
      Tracing is off.

.   /%/mathpiper_trace

*SEE StackTrace, StackTraceOn, StackTraceOff, TraceSome, TraceExcept, TraceOff, Profile

*SOURCE org/mathpiper/builtin/procedures/core/TraceOn.java
==========
*CMD TraceRule --- turn on tracing for a particular function
*CORE
*CALL
	TraceRule(template) expr

*PARMS

{template} -- template showing the operator to trace

{expr} -- expression to evaluate with tracing on

*DESC

The tracing facility is turned on for subexpressions of the form
"template", and the expression "expr" is evaluated. The template
"template" is an example of the function to trace on. Specifically, all
subexpressions with the same top-level operator and arity as "template"
are shown. The subexpressions are displayed before (indicated with {TrEnter}) and after ({TrLeave})
evaluation. In between, the arguments are shown before and after
evaluation ({TrArg}). Only functions defined in
scripts can be traced.

This is useful for tracing a function that is called from within
another function. This way you can see how your function behaves
in the environment it is used in.

*E.G. notest

In> TraceRule(x+y) 2+3*5+4;
	    TrEnter(2+3*5+4);
	      TrEnter(2+3*5);
	          TrArg(2, 2);
	          TrArg(3*5, 15);
	      TrLeave(2+3*5, 17);
	        TrArg(2+3*5, 17);
	        TrArg(4, 4);
	    TrLeave(2+3*5+4, 21);
Result: 21;

*SEE TraceStack, TraceExcept

*SOURCE org/mathpiper/builtin/procedures/core/TraceRule.java
==========
*CMD TraceSome --- trace the given procedures which are evaluated in the given expression
*CORE
*CALL
	TraceSome("procedure_name,procedure_name,procedure_name,...") expression

*PARMS

{"procedure_name,procedure_name,procedure_name,..."} -- a string which contains the names of procedures to trace separated by commas.

{expression} -- an expression to trace.

*DESC

Outputs a trace of the procedures which are listed in the given string and are evaluated in the given expression


*E.G.
In> TraceSome("Factors,FactorizeInt") Factor(8)
Result> True
Side Effects>
Enter<**** user rulebase>{(Factors,Factors(p));
    Arg(p->8);
    **** Rule in procedure (Factors) matched: Precedence: 10, Parameters: arg1<hold=false>, Predicates: (Pattern) Integer?(p), True,     Variables: p,    Types: Variable, Body: FactorizeInt(p)
    Enter<**** user rulebase>{(FactorizeInt,FactorizeInt(p));
        Arg(p->8);
        **** Rule in procedure (FactorizeInt) matched: Precedence: 3, Parameters: arg1<hold=false>, Predicates: (Pattern) Integer?(n), True,     Variables: n,    Types: Variable, Body: [    Local(small'powers);    n:=Abs(n);    If(Gcd(ProductPrimesTo257(),n)>1,small'powers:=TrialFactorize(n,257),small'powers:={n});    n:=small'powers[1];    If(n=1,Tail(small'powers),[        If(Verbose?(),Echo({"FactorizeInt: Info: remaining number ",n}));        SortFactorList(PollardCombineLists(Tail(small'powers),PollardRhoFactorize(n)));]);]
    Leave<**** user rulebase>}(FactorizeInt(p)->[[2,3]]);
Leave<**** user rulebase>}(Factors(p)->[[2,3]]);


*SEE TraceExcept, StackTrace, StackTraceOn, StackTraceOff, TraceOff, Profile


*SOURCE org/mathpiper/builtin/procedures/core/TraceSome.java
==========
*CMD TraceStack --- show calling stack after an error occurs
*CORE
*CALL
	TraceStack(expression)

*PARMS

{expression} -- an expression to evaluate

*DESC

TraceStack shows the calling stack after an error occurred.
It shows the last few items on the stack, not to flood the screen.
These are usually the only items of interest on the stack.
This is probably by far the most useful debugging function in
MathPiper. It shows the last few things it did just after an error
was generated somewhere.

For each stack frame, it shows if the function evaluated was a
built-in function or a user-defined function, and for the user-defined
function, the number of the rule it is trying whether it was evaluating
the pattern matcher of the rule, or the body code of the rule.

This functionality is not offered by default because it slows
down the evaluation code.

*E.G. notest

Here is an example of a function calling itself recursively,
causing MathPiper to flood its stack:

In> f(x):=f(Sin(x))
Result: True;

In> TraceStack(f(2))
	Debug> 982 :  f (Rule # 0 in body)
	Debug> 983 :  f (Rule # 0 in body)
	Debug> 984 :  f (Rule # 0 in body)
	Debug> 985 :  f (Rule # 0 in body)
	Debug> 986 :  f (Rule # 0 in body)
	Debug> 987 :  f (Rule # 0 in body)
	Debug> 988 :  f (Rule # 0 in body)
	Debug> 989 :  f (Rule # 0 in body)
	Debug> 990 :  f (Rule # 0 in body)
	Debug> 991 :  f (Rule # 0 in body)
	Debug> 992 :  f (Rule # 0 in body)
	Debug> 993 :  f (Rule # 0 in body)
	Debug> 994 :  f (Rule # 0 in body)
	Debug> 995 :  f (User function)
	Debug> 996 :  Sin (Rule # 0 in pattern)
	Debug> 997 :  List? (Internal function)
	Error on line 1 in file [CommandLine]
	Max evaluation stack depth reached.
	Please use MaxEvalDepth to increase the stack
	size as needed.

*SEE TraceExcept, TraceRule

*SOURCE org/mathpiper/builtin/procedures/core/TraceStack.java
==========
*CMD TreeProcess --- visit the nodes in a tree
*CORE
*CALL
	TreeProcess(expression,pattern,associationlist,options)

*PARMS

{expression} -- expression that will have its tree visited

{pattern} -- a pattern that matches on parts of the tree

{associationlist} -- an association list that contains an anonymous function that is called at each match

{Options:}

{Position} -- String: a match will only be checked at the specified position

*DESC

Visits a tree

*E.G.


*SOURCE org/mathpiper/builtin/procedures/core/TreeProcess.java
==========
*CMD Type --- return the type of an expression
*CORE
*CALL
	Type(expr)

*PARMS

{expr} -- expression to examine

*DESC

The type of the expression "expr" is represented as a string and
returned. So, if "expr" is a list, the string {"List"} is returned. In general, the top-level
operator of "expr" is returned. If the argument "expr" is an atom,
the result is the empty string {""}.

*E.G.

In> Type([1,'b,Pi]);
Result: "List";

In> Type('a * ('b + 'c));
Result: "*";

In> Type(123);
Result: "";

*SEE Atom?, ArgumentsCount

*SOURCE org/mathpiper/builtin/procedures/core/Type.java
==========
*CMD UnFence --- change local variable scope for a procedure
*CORE
*CALL
	UnFence("operator",arity)

*PARMS
{"operator"} -- string, name of procedure

{arity} -- positive integers

*DESC

When applied to a user procedure, the bodies
defined for the rules for "operator" with given
arity can see the local variables from the calling
procedure. This is useful for defining macro-like
procedures (looping and such).

The standard library procedures {For} and {ForEach} use {UnFence}.

*SOURCE org/mathpiper/builtin/procedures/core/UnFence.java
==========
*CMD Unassign --- undo an assignment
*CORE
*CALL
	Unassign(var, ...)

*PARMS

{var} -- name of variable to be unbound

*DESC

All assignments made to the variables listed as arguments are
undone. From now on, all these variables remain unevaluated (until a
subsequent assignment is made). Also unsets any metadata that may have
been set in an unbound variable.  If the constant 'All' is passed in
as the variable name, all global variables that don't start with a '?'
character are unassigned.

*E.G.
In> a := 5;
Result> 5;

In> a^2;
Result> 25;

In> Unassign(a);
Result> True;

In> a^2;
Result> a^2;

In> Unassign(All)
Result> True

*SEE Assign, :=

*SOURCE org/mathpiper/builtin/procedures/core/Unassign.java
==========
*CMD MacroUnassign --- define rules in procedures
*CORE
*DESC

This procedure has the same effect as its non-macro counterpart, except
that its arguments are evaluated before the required action is performed.
This is useful in macro-like procedures or in procedures that need to define new
rules based on parameters.

Make sure that the arguments of {Macro}... commands evaluate to expressions that would normally be used in the non-macro version!

*SEE Unassign

*SOURCE org/mathpiper/builtin/procedures/core/Unassign.java
==========
*CMD UnderscoreConstant? --- test for an underscore constant
*STD
*CALL
        UnderscoreConstant?(expression)

*PARMS

{expression} -- expression to test

*DESC

This procedure tests if the argument is an underscore constant.

*E.G.

In> UnderscoreConstant?(_x)
Result: True

*SEE Constant?,DefinedConstant?

*SOURCE org/mathpiper/builtin/procedures/core/UnderscoreConstant_.java
==========
*CMD UnicodeToString --- creates a single character string from the character's unicode value
*CORE
*CALL
	UnicodeToString(n)
 
*PARMS
 {n} - a unicode value

*DESC
This function creates a single character string from the character's unicode value.

*E.G.
In> UnicodeToString(65)
Result> "A"


*SOURCE org/mathpiper/builtin/procedures/core/UnicodeToString.java
==========
*CMD UnparseLisp --- print an expression in LISP-format
*CORE
*CALL
	UnparseLisp(expr)

*PARMS

{expr} -- expression to be printed in LISP-format

*DESC

Evaluates "expr", and prints it in LISP-format on the current
output. The evaluated expression is also
returned.

This can be useful if you want to study the internal representation of
a certain expression.

*E.G. notest

In> UnparseLisp(a+b+c);
Result: (a+b)+c
Side Effects:
(+ (+ a b) c)

In> UnparseLisp(2*I*b^2);
Result: Complex(0,2)*b^2
Side Effects:
(* (Complex 0 2) (^ b 2))

The first example shows how the expression {a+b+c} is
internally represented. In the second example, {2*I} is
first evaluated to {Complex(0,2)} before the expression
is printed.

*SEE ParseLisp

*SOURCE org/mathpiper/builtin/procedures/core/UnparseLisp.java
==========
*CMD UnparseMathPiper --- return an expression as a string in MathPiper format
*CALL
	UnparseMathPiper(expr)

*PARMS

{expr} -- expression to be unparsed to a string

{Options:}

{Parentheses} -- when True returns a fully parenthesized expression

*DESC

Unparses an expression to a string that is in MathPiper format.

*E.G.
In> UnparseMathPiper('(1 + 2))
Result: "1 + 2"

*SEE ParseMathPiper

*SOURCE org/mathpiper/builtin/procedures/core/UnparseMathPiper.java
==========
*CMD UnparserGet --- get the name of the current unparser

*CORE

*CALL
	UnparserGet()

*DESC

{UnparserGet()} returns the current unparser, or it returns
an empty string if the default unparser is used.


*E.G.

In> UnparserGet()
Result: ""

*SEE UnparseMath2D, Write, UnparseLatex, UnparseC, ParserSet, ParserGet, UnparserSet

*SOURCE org/mathpiper/builtin/procedures/core/UnparserGet.java
==========
*CMD UnparserSet --- set the current unparser

*CORE

*CALL
	UnparserSet(unparser)
	UnparserSet()

*PARMS

{unparser} -- a string containing the name of an unparser function


*DESC

This function sets the current unparser that outputs results in text form. 
This can be reset to the default printer with {UnparserSet()} 
(when no argument is given, the system returns to the default).

Some examples of unparsers are: {UnparseMath2D}, {UnparseLatex}, {Print}, {UnparseC} and {DefaultPrint}.


*E.G.

In> Taylor(x,0,5)Sin(x)
Result: (x-x^3/6)+x^5/120

In> UnparserSet("UnparseMath2D");
Result: True
Side Effects:

True


In> Taylor(x,0,5)Sin(x)
Result: True
Side Effects:

     3    5 
    x    x  
x - -- + ---
    6    120



In> UnparserSet();
Result: True

In> Taylor(x,0,5)Sin(x)
Result: (x-x^3/6)+x^5/120

*SEE UnparseMath2D, Write, UnparseLatex, UnparseC, ParserSet, ParserGet, UnparserGet

*SOURCE org/mathpiper/builtin/procedures/core/UnparserSet.java
==========
*CMD Until --- loop until a condition is met
*STD
*CALL
        Until(pred) body

*PARMS

{pred} -- predicate deciding whether to stop

{body} -- expression to loop over

*DESC

Keep on evaluating "body" until "pred" becomes {True}. More precisely, {Until} first
evaluates the expression "body". Then the predicate "pred" is
evaluated, which should yield either {True} or {False}. In the latter case, the expressions "body"
and "pred" are again evaluated and this continues as long as
"pred" is {False}. As soon as "pred" yields {True}, the loop terminates and {Until} returns {True}.

The main difference with {While} is that {Until} always evaluates the body at 
least once, but {While} may not evaluate the body at all. Besides, the
meaning of the predicate is reversed: {While} stops
if "pred" is {False} while {Until} stops if "pred" is {True}.
The command
{Until(pred) body;} is equivalent to {pred; While(!? pred) body;}. In fact, the
implementation of {Until} is based on the internal
command {While}. The {Until}
command can be compared to the {do ... while}
construct in the programming language C.

*E.G.

/%mathpiper
x := 1;

Until(x >=? 5)
{
   Echo(x); 
   x++;
};
/%/mathpiper

    /%output,sequence="4",timestamp="2013-09-16 22:36:36.156",preserve="false"
      Result: True
      
      Side Effects:
      1 
      2 
      3 
      4 
      
.   /%/output

*SEE While, For, ForEach, Break, Continue

*SOURCE org/mathpiper/builtin/procedures/core/Until.java
==========
*CMD Variable? --- test for a variable
*STD
*CALL
        Variable?(var)

*PARMS

{var} -- variable to test

*DESC

This procedure tests if the argument is a variable.

*E.G.

In> Unassign(x)
Result: True

In> Variable?(x)
Result: True

In> x := 3
Result: 3

In> Variable?(x)
Result: False

In> Variable?(Infinity)
Result: False

*SEE VarList, VarListAll, Constant?

*SOURCE org/mathpiper/builtin/procedures/core/Variable_.java
==========
*CMD Version --- show version of MathPiper
*CORE
*CALL
	Version()

*DESC

The procedure {Version()} returns a string representing the version of the currently running MathPiper interpreter.

*E.G. notest

In> Version()
Result: "1.0.48rev3";

In> LessThan?(Version(), "1.0.47")
Result: False;

In> GreaterThan?(Version(), "1.0.47")
Result: True;

The last two calls show that the {LessThan?} and {GreaterThan?}
functions can be used for comparing version numbers. This
method is only guaranteed, however, if the version is always expressed
in the form {d.d.dd} as above.

*SEE LessThan?, GreaterThan?

*SOURCE org/mathpiper/builtin/procedures/core/Version.java
==========
*CMD While --- loop while a condition is met
*CORE
*CALL
While(pred) body

*PARMS
{pred} -- predicate deciding whether to keep on looping

{body} -- expression to loop over

*DESC

Keep on evaluating "body" while "pred" evaluates to {True}. More precisely, {While}
evaluates the predicate "pred", which should evaluate to either {True} or {False}. 
If the result is {True}, the expression "body" is evaluated and then
the predicate "pred" is again evaluated. If it is still {True}, the expressions "body" and "pred" are again
evaluated and so on until "pred" evaluates to {False}. At that point, the loop terminates and {While}
returns {True}.

In particular, if "pred" immediately evaluates to {False}, the body is never executed. {While} 
is the fundamental looping construct on which all other loop commands are based. It is equivalent 
to the {while} command in the programming language C.

*E.G. notest

In> x := 0;
Result: 0

In> While (x ! <? 10^6) [ Echo([x, x!]); x++; ];
Result: True
Side Effects:
[0,1] 
[1,1] 
[2,2] 
[3,6] 
[4,24] 
[5,120] 
[6,720] 
[7,5040] 
[8,40320] 
[9,362880] 

*SEE DoWhile, For, ForEach, Break, Continue

*SOURCE org/mathpiper/builtin/procedures/core/While.java
==========
*CMD Write --- low-level printing routine
*CORE
*CALL
	Write(expr, ...)

*PARMS

{expr} -- expression to be printed

*DESC

The expression "expr" is evaluated and written to the current
output. Note that Write accept an arbitrary number of arguments, all
of which are written to the current output (see second
example). {Write} always returns {True}.

*E.G. notest

In> Write(1);
Result: True
Side Effects:
1

In> Write(1,2);
Result: True
Side Effects:
1 2

*SEE Echo, WriteString

*SOURCE org/mathpiper/builtin/procedures/core/Write.java
==========
*CMD WriteString --- low-level printing routine for strings
*CORE
*CALL
	WriteString(string)

*PARMS

{string} -- the string to be printed

*DESC

The expression "string" is evaluated and written to the current
output without quotation marks. The argument should be a
string. WriteString always returns True.

*E.G. notest

In> Write("Hello, world!");
Result: True
Side Effects:
"Hello, world!"

In> WriteString("Hello, world!");
Result: True
Side Effects:
Hello, world!

This example clearly shows the difference between Write and
WriteString.

*SEE Echo, Write

*SOURCE org/mathpiper/builtin/procedures/core/WriteString.java
==========
*CMD XmlExplodeTag --- convert XML strings to tag objects
*CORE
*CALL
	XmlExplodeTag(xmltext)
*PARMS

{xmltext} -- string containing some XML tokens

*DESC

{XmlExplodeTag} parses the car XML token in {xmltext}
and returns a MathPiper expression.

The following subset of XML syntax is supported currently:

*	{<TAG [options]>} -- an opening tag
*	{</TAG [options]>} -- a closing tag
*	{<TAG [options] />} -- an open/close tag
*	plain (non-tag) text

The tag options take the form {paramname="value"}.

If given an XML tag, {XmlExplodeTag} returns a structure of the form {XmlTag(name,params,type)}.
In the returned object,
{name} is the (capitalized) tag name, {params} is an assoc list with
the options (key fields capitalized), and type can be either "Open", "Close" or "OpenClose".

If given a plain text string, the same string is returned.


*E.G.
In> XmlExplodeTag("some plain text")
Result: "some plain text";

In> XmlExplodeTag("<a name=\"blah blah\" align=\"left\">")
Result: XmlTag("A",[["ALIGN","left"], ["NAME","blah blah"]],"Open");

In> XmlExplodeTag("</p>")
Result: XmlTag("P",[],"Close");

In> XmlExplodeTag("<br/>")
Result: XmlTag("BR",[],"OpenClose");

*SEE XmlTokenizer

*SOURCE org/mathpiper/builtin/procedures/core/XmlExplodeTag.java
==========
*CMD XmlTokenizer --- select an XML syntax tokenizer for parsing the input
*CORE
*CALL
	XmlTokenizer()

*DESC

A "tokenizer" is an internal routine in the kernel that parses the input into MathPiper expressions.
This affects all input typed in by a user at the prompt and also the input redirected from files or strings using {PipeFromFile} and {FromString} and read using {Read} or {ParseMathPiperToken}.

The MathPiper environment currently supports some experimental tokenizers for
various syntaxes. {XmlTokenizer} switches to an XML syntax.
Note that setting the tokenizer is a global side effect.
One typically needs
to switch back to the default tokenizer when finished reading the special syntax.

Care needs to be taken when kernel errors are raised during a non-default tokenizer operation (as with any global change in the environment).
Errors need to be
caught with the {TrapError} function. The error handler code should re-instate
the default tokenizer,
or else the user will be unable to continue the session
(everything a user types will be parsed using a non-default tokenizer).

When reading XML syntax, the supported formats are the same as those of {XmlExplodeTag}.
The parser does not validate anything in the XML input.
After an XML token has been read in, it can be converted into an
MathPiper expression with {XmlExplodeTag}.
Note that when reading XML, any plain text between tags is returned as one token.
Any malformed XML will be treated as plain text.


*SEE XmlExplodeTag, ParseMathPiperToken, PipeFromFile, PipeFromString, DefaultTokenizer

*SOURCE org/mathpiper/builtin/procedures/core/XmlTokenizer.java
==========
*CMD Eval --- evaluation an expression for a maximum amount of time
*CORE
*CALL
	Eval(expr, timeout)

*PARMS

{expr} -- expression to evaluate
{timeout} -- timeout time in milliseconds

*DESC
This function is the same as the Eval function, except it will throw an exception
if the timeout time is exceeded.

*E.G.
In> infiniteLoop := '(While(True) 3);
Result: While(True)3

In> EvalTimeout(infiniteLoop, 1000)
Result: Exception
Exception: Error: Evaluation timeout. Starting at index 9.



*SEE Eval

*SOURCE org/mathpiper/builtin/procedures/nongwtcore/EvalTimeout.java
==========
*CMD AskUser --- displays an input dialog to the user
*CORE
*CALL
	AskUser(message)

*PARMS

{message} -- a message (either a string or a javax.swing.JCompnent)) that indicates what kind of input to enter

*DESC

This function allows information to be obtained from the user in the
form of a string.  A GUI dialog box will be displayed which the user
can use to enter their input.  If the user selects the cancel button,
the Break() function will be executed.

*SEE TellUser

*SOURCE org/mathpiper/builtin/procedures/optional/AskUser.java
==========
 *CMD AskUser --- displays a dialog that contains a Java Component
 *CORE
 *CALL
 Assess(javaComponent)

 *PARMS

 {javaObject} -- a Java Component

 *DESC
Shows a Java Component to the user that has parts which
can be selected with the mouse.


*SOURCE org/mathpiper/builtin/procedures/optional/Assess.java
==========
*CMD AssessView --- display an assessment-related GUI

*CALL
    AssessView(javaComponent, option, option, option...)

*PARMS
{javaComponent} -- a java Component

{Options:}


*DESC
Display a Java Component.

 
*E.G.
In> 


*SOURCE org/mathpiper/builtin/procedures/optional/AssessView.java
==========
*CMD Delay --- delays execution of a program for a specified number of milliseconds
*CORE
*CALL
	Delay(ms)

 *PARMS
 {ms} -- the number of milliseconds to delay

*DESC

This function delays execution of a program for the specified number of milliseconds.
The delay can be terminated by pressing the "Halt Evaluation" button.

*E.G.
In> Delay(1000)
Result: True


*SOURCE org/mathpiper/builtin/procedures/optional/Delay.java
==========
 *CMD DemoGUI --- a GUI to control automated demonstrations of programs
 *CORE
 *CALL
 DemoGui(option, option, option...)

 *PARMS

 {Options:}

 {Title} -- the title of the window


 *DESC

 This GUI is used to control automated demonstrations of programs.



 *E.G.
 In> DemoGui()



*SOURCE org/mathpiper/builtin/procedures/optional/DemoGUI.java
==========
*CMD EnvironmentGet --- displays an input dialog to the user

*CALL
	EnvironmentGet()

*DESC

This function returns a reference to the current environment object.


*SOURCE org/mathpiper/builtin/procedures/optional/EnvironmentGet.java
==========
*CMD FScoreToProbability --- calculates the cumulative probability for a given f-score

*CALL

    FScoreToProbability(degreesOfFreedom1, degreesOfFreedom2, fScore)

*PARMS
{degreesOfFreedom1} -- integer, the first degree of freedom

{degreesOfFreedom2} -- integer, the second degree of freedom

{fScore} -- the fScore

*DESC
Calculates the cumulative probability for a given f-score.

*E.G.
In> FScoreToProbability(1,1,161.448)
Result> 0.9500000557



*SOURCE org/mathpiper/builtin/procedures/optional/FScoreToProbability.java
==========
 *CMD HistogramPrint --- prints a histogram

 *CALL
 HistogramPrint(data, binMinimum, binMaximum, numberOfBins)

 *PARMS
 {data} -- a list of decimal numbers
 {binMinumum} -- the minimum bin value 
 {binMaximum} -- the maximum bin value
 {numberOfBins} -- the number of bins

 *DESC
 Prints a horizontal histogram. Note: does not work correctly
yet for decimal numbers.

 *E.G.
 In> HistogramPrint(RandomIntegerList(20,1,7), 1, 7, 2)
 Result: True
 Side Effects:
     1-2     | **** | 7
     3-4     | ***  | 6
     5-6     | **   | 4
     7-8     | **   | 3
             | ----
 Scale       |  4 8


*SOURCE org/mathpiper/builtin/procedures/optional/HistogramPrint.java
==========
*CMD LatexView --- display an image from a file

*CALL
    ImageFromFileView(expression, option, option, option...)

*PARMS
{expression} -- a string that contains the path to the file

{Options:}

{Scale} -- a value that sets the initial size of the image

{Resizable} -- if set to True, a resizing slider is displayed

*DESC
Display an image from a file.

Options are entered using the : operator.
For example, here is how to set the {Resizable} option: {Resizable: True}.

Right click on the image to save it.
 
*E.G.
In> Show(ImageFromFileView("/home/afile.png"))
Result: java.awt.Component


*SEE Show

*SOURCE org/mathpiper/builtin/procedures/optional/ImageFromFileView.java
==========
*CMD IncompleteBeta --- the incomplete beta function
*CALL
    IncompleteBeta(a, b, x)

*PARMS
{a} -- the alpha parameter of the beta distribution

{b} -- the beta parameter of the beta distribution

{x} -- the integration end point

*DESC

The incomplete gamma function.

*E.G.
In> IncompleteGamma(2.5,3.6)
Result> 0.3188972206



*SOURCE org/mathpiper/builtin/procedures/optional/IncompleteBeta.java
==========
*CMD IncompleteGamma --- the incomplete gamma function
*CORE
*CALL
    IncompleteGamma(a, x)

*PARMS
{a} -- the parameter of the gamma distribution

{x} -- the integration end point

*DESC

The incomplete gamma function.

*E.G.
In> IncompleteBeta(.2,.2,.2)
Result> 0.3927221644



*SOURCE org/mathpiper/builtin/procedures/optional/IncompleteGamma.java
==========
*CMD IntegrateN --- Numerical integration

*CALL
	IntegrateN(expression, variable, lowValue, highValue)

 *PARMS
{expression} -- expression to integrate

{variable} -- atom, variable to integrate over

{lowerValue} -- lower value of definite integration

{higherValue} -- higher value of definite integration

{Options:}

 {todo} -- todo

*DESC

This procedure integrates the expression {expression} with respect to the
variable {variable}.


*SOURCE org/mathpiper/builtin/procedures/optional/IntegrateN.java
==========
*CMD JavaAccess --- calls a method on a Java object and converts the result into a MathPiper data structure
*CALL
    JavaAccess(javaObject, methodName, methodParameter1, methodParameter2, ...)

*PARMS
{javaObject} -- a Java object

{methodName} -- the name of a method to call on the Java object (it can be either a string or an atom)

{methodParameters} -- zero or more parameters which will be sent to the method

*DESC
This is a convenience function which can be used instead of using JavaCall and JavaToValue.

*E.G.
In> javaString := JavaNew("java.lang.String", "Hello")
Result: java.lang.String

In> JavaAccess(javaString, "charAt",1)
Result: e

*SEE JavaNew, JavaCall, JavaToValue

*SOURCE org/mathpiper/builtin/procedures/optional/JavaAccess.java
==========
*CMD JavaCall --- calls a method on a Java object and returns the result as a Java object
*CALL
    JavaCall(javaObject, methodName, methodParameter1, methodParameter2, ...)

*PARMS
{javaObject} -- a Java object

{methodName} -- the name of a method to call on the Java object (it can be either a string or an atom)

{methodParameters} -- zero or more parameters which will be sent to the method

*DESC
This function calls a method on {javaObject} and returns the result as a Java object.  The returned Java object
can be converted into a MathPiper data structure by passing it to JavaToValue, or in can be passed
to JavaCall or JavaAccess for further processing.

*E.G.
In> javaString := JavaNew("java.lang.String", "Hello")
Result: java.lang.String

In> javaString := JavaCall(javaString, "replace", "e", "o")
Result: java.lang.String

In> JavaToValue(javaString)
Result: Hollo

In> JavaAccess(javaString, "charAt", 0)
Result: H

*SEE JavaNew, JavaAccess, JavaToValue

*SOURCE org/mathpiper/builtin/procedures/optional/JavaCall.java
==========
*CMD JavaNew --- instantiates a Java object
*CALL
    JavaNew(fullyQualifiedClassName, constructorParameter1, constructorParameter2, ...)

*PARMS
{fullyQualifiedClassName} -- (string) the fully qualified name of a Java class

{constructorParameters} -- zero or more parameters which will be sent to the constructor

*DESC
This function instantiates a Java object and then returns it as a result.

*E.G.
In> javaString := JavaNew("java.lang.String", "Hello")
Result: java.lang.String

In> javaString := JavaAccess(javaString, "toUpperCase")
Result: HELLO

*SEE JavaCall, JavaAccess, JavaToValue

*SOURCE org/mathpiper/builtin/procedures/optional/JavaNew.java
==========
*CMD JavaToValue --- converts a Java object into a MathPiper data structure
*CALL
    JavaToValue(javaObject)

*PARMS
{javaObject} -- a Java object

*DESC
This function is used to convert a Java object into a MathPiper data structure.  It is typically 
used with JavaCall.

*E.G.
In> javaString := JavaNew("java.lang.String", "Hello")
Result: java.lang.String

In> JavaToValue(javaString)
Result: Hello

*SEE JavaCall, JavaAccess, JavaNew

*SOURCE org/mathpiper/builtin/procedures/optional/JavaToValue.java
==========
*CMD LatexView --- display rendered Latex code

*CALL
    LatexView(expression, option, option, option...)

*PARMS
{expression} -- an expression to display as an expression tree

{Options:}

{Scale} -- a value that sets the initial size of the expression

{Resizable} -- if set to True, a resizing slider is displayed

*DESC
Display rendered Latex code.  Note: backslashes must be escaped
with a backslash.

Options are entered using the : operator.
For example, here is how to set the {Resizable} option: {Resizable: True}.

Right click on the image to save it.
 
*E.G.
In> Show(LatexView("2\\sum_{i=1}^n a_i"))
Result: java.awt.Component


*SEE Show

*SOURCE org/mathpiper/builtin/procedures/optional/LatexView.java
==========
*CMD ListView --- display an expression in Lisp box diagram form

*CALL
    ListView(expression, option, option, option...)

*PARMS
{expression} -- an expression (which may be in string form) to display as an expression tree

{Options:}

{Scale} -- a value that sets the initial size of the tree

{Resizable} -- if set to True, a resizing slider is displayed

{IncludeExpression} -- if set to True, the algebraic form of the expression is included above the tree

{Lisp} -- if set to True, the expression must be a string that is in Lisp form

{Code} -- if set to True, the expression is rendered using code symbols instead of mathematical symbols


*DESC
Returns a Java GUI component that contains an expression rendered as a
LISP box diagram.

Options are entered using the : operator.
For example, here is how to disable {Resizable} option: {Resizable: False}.

Right click on the images that are displayed to save them.
 
*E.G.

In> Show(ListView( '(a*(b+c) == a*b + a*c)))
Result: java.awt.Component

In> Show(ListView( "a*(b+c) == a*b + a*c"))
Result: java.awt.Component

In> Show(ListView( "(+ 1 (* 2 3))", Lisp: True))
Result: java.awt.Component

In> Show(ListView( '(a*(b+c) == a*b + a*c),MetaData: True))
Result: class javax.swing.JFrame

*SEE Show

*SOURCE org/mathpiper/builtin/procedures/optional/ListView.java
==========
 *CMD LoadScriptFile --- evaluate MathPiper code that is in a file

 *CALL LoadScriptFile(fileName)

 *PARMS

 {fileName} -- a string that contains the path and name of a file that
 contains MathPiper code

 *DESC

 If the file is a .mpws file, all the code in %mathpiper folds that have a name attribute
 and a def attribute is evaluated. For other file types, all MathPiper code in the file
 is evaluated.
 {LoadScriptFile} always returns {True}.

 *SEE LoadScript 

*SOURCE org/mathpiper/builtin/procedures/optional/LoadScriptFile.java
==========
*CMD MacroExpand --- shows the expanded form of a macro
*CALL
    MacroExpand() macro

*PARMS
{macro} -- a macro to expand

*DESC
This function shows the expanded form of the Lisp-like macros that MathPiper supports.
Note: only back quoted macros are supported at this time.

*E.G.
//Assign the variable var to the atom Echo.
In> var := 'Echo;
Result: Echo

//Show the macro in expanded form.
In> MacroExpand()/`(@var(2,"Hello"))
Result: True
Side Effects:
Echo(2,"Hello")
2 Hello

//Execute the macro.
In> /`(@var(2,"Hello"))
Result: True
Side Effects:
2 Hello

*SEE /`

*SOURCE org/mathpiper/builtin/procedures/optional/MacroExpand.java
==========
*CMD MathParse ---  parse expressions that are in linear traditional format
*CALL
	MathParse(string)

*PARMS
{string} -- a string that contains a math expression


*DESC
This function parse expressions that are in linear traditional format

*E.G.
In> MathParse("2x + 3y")
Result: 2 * _x + 3 * _y


*SOURCE org/mathpiper/builtin/procedures/optional/MathParse.java
==========
*CMD MathView --- display rendered Latex code

*CALL
    MathView(expression, option, option, option...)

*PARMS
{expression} -- a mathematical expression to display

{Options:}

{Scale} -- a value that sets the initial size of the tree

{Resizable} -- if set to True, a resizing slider is displayed

*DESC
Display a mathematical expression

 
*E.G.
In> 


*SOURCE org/mathpiper/builtin/procedures/optional/MathView.java
==========
*CMD NormalDistributionValue --- returns a value from the normal distribution
*CALL
    NormalDistributionValue(mean, standardDeviation)

*PARMS
{mean} -- the mean of the distribution
{standardDeviation} -- the standard deviation of the distribution

*DESC
This function returns a value from the given normal distribution.

*E.G.
In> NormalDistributionValue(3,2)
Result> 5.440398494


*SOURCE org/mathpiper/builtin/procedures/optional/NormalDistributionValue.java
==========
*CMD OneTailAlphaToTScore --- convert a one-tail alpha to a t-score

*CALL

    OneTailAlphaToTScore(degreesOfFreedom, alpha)

*PARMS

{degreesOfFreedom} -- integer, the degrees of freedom

{alpha} -- the one tailed alpha value

*DESC

Calculates the t value for the given one tail alpha value and degrees of freedom.

*E.G.
In> OneTailAlphaToTScore(9,.025)
Result> 2.262157163



*SOURCE org/mathpiper/builtin/procedures/optional/OneTailAlphaToTScore.java
==========
*CMD ParseLatex --- parse LaTeX strings

*CALL
    ParseLatex(string)

*PARMS
{string} -- a string that contains a LaTeX expression

*DESC
Parses a string that contains a LaTeX expresion.
 
*E.G.
In> ParseLatex("2 \\times 2")
Result: 2*2


*SOURCE org/mathpiper/builtin/procedures/optional/ParseLatex.java
==========
*CMD PipeFromFile --- connect current input to a file
*CORE
*CALL
	PipeFromFile(name) body

*PARMS

{name} - string, the name of the file to read

{body} - expression to be evaluated

*DESC

The current input is connected to the file "name". Then the expression
"body" is evaluated. If some functions in "body" try to read
from current input, they will now read from the file "name". Finally, the
file is closed and the result of evaluating "body" is returned.

*E.G.

Suppose that the file foo contains

	2 + 5;

Then we can have the following dialogue:

In> PipeFromFile("foo") res := ParseMathPiper();
Result: 2+5;

In> PipeFromFile("foo") res := ParseMathPiperToken();
Result: 2;

*SEE PipeToFile, PipeFromString, ParseMathPiper, ParseMathPiperToken

*SOURCE org/mathpiper/builtin/procedures/optional/PipeFromFile.java
==========
*CMD PipeToFile --- connect current output to a file
*CORE
*CALL
	PipeToFile(name) body

*PARMS

{name} -- string, the name of the file to write the result to

{body} -- expression to be evaluated

*DESC

The current output is connected to the file "name". Then the expression
"body" is evaluated. Everything that the commands in "body" print
to the current output ends up in the file "name". Finally, the
file is closed and the result of evaluating "body" is returned.

If the file is opened again, the new information will be appended to the
existing information in the file.

*E.G.
In> PipeToFile("test2.txt") WriteString("Hello");
Result: True


*SEE PipeFromFile, PipeToString, Echo, Write, WriteString

*SOURCE org/mathpiper/builtin/procedures/optional/PipeToFile.java
==========
*CMD PlotterView --- display the MathPiper plotter

*CALL
    PlotterView(option, option, option...)

*PARMS

{Options:}

{Scale} -- a value that sets the initial size of the tree

{Resizable} -- if set to True, a resizing slider is displayed

*DESC
Display a the MathPiper plotter.

 
*E.G.
In> Show(PlotterView())
Result: class javax.swing.JFrame


*SOURCE org/mathpiper/builtin/procedures/optional/PlotterView.java
==========
*CMD Printf --- print a formatted string

*CALL
Printf(formatString, expr, ...)

*PARMS

{formatString} -- a string that contains format specifiers and literals
{expr} -- expressions that are associated with the format specifiers

*DESC
Print a formatted string. A description of formatted strings
is in the documentation for the {StringFormat} procedure, which is
linked to below.

*EXAMPLES
In> Printf("%d + %.3f == %f", 1, 2.2, 3.2) 
Result: True 
Side Effects: 
"1 + 2.200 == 3.200000"

*SEE StringFormat

*SOURCE org/mathpiper/builtin/procedures/optional/Printf.java
==========
*CMD ProbabilityToFScore --- calculates the f-score for a given cumulative probability

*CALL

    ProbabilityToFScore(degreesOfFreedom1, degreesOfFreedom2, probability)

*PARMS

{degreesOfFreedom1} -- integer, the first degree of freedom

{degreesOfFreedom2} -- integer, the second degree of freedom

{probability} -- the cumulative probability

*DESC
Calculates the calculates the f-score for a given cumulative probability.

*E.G.
In> ProbabilityToFScore(1,1,.95)
Result> 161.4476388



*SOURCE org/mathpiper/builtin/procedures/optional/ProbabilityToFScore.java
==========
 *CMD Show --- displays GUI components
 *CORE
 *CALL
 Show(component, option, option, option...)

 *PARMS

 {component} -- a Java GUI component

 {Options:}

 {Title} -- the title of the window


 *DESC

 Displays a GUI window that contains a Java GUI component. These GUI components 
 are usually returned from XXXView functions and charting functions.



 *E.G.
 In> Show(TreeView( '(a*(b+c) == a*b + a*c)))
 Result: class javax.swing.JFrame

 *SEE TreeView, LatexView


*SOURCE org/mathpiper/builtin/procedures/optional/Show.java
==========
*CMD SoundPlay --- plays a sound file
*CORE
*CALL
	SoundPlay(filePath)

*PARMS

{filePath} -- a string that contains path to a sound file

*DESC

This procedure plays a sound file.


*SOURCE org/mathpiper/builtin/procedures/optional/SoundPlay.java
==========
 *CMD StemAndLeaf --- prints a stem and leaf plot

 *CALL
 StemAndLeaf(data)

 *PARMS
 {data} -- a list of integers

 *DESC
 prints a stem and leaf plot.

 *E.G.
 In> StemAndLeaf(RandomIntegerList(100,1,50))
 Result: True
 Side Effects:
 0  | 1 1 1 2 3 3 4 5 5 5 6 6 6 7 8
 1  | 0 1 1 1 1 3 3 3 4 4 5 6 7 8 8 8 8
 2  | 0 0 1 1 2 2 3 3 3 3 4 4 5 5 5 6 6 6 6 6 6 8 8 9 9
 3  | 0 1 2 2 3 3 3 4 4 4 4 5 5 6 6 6 7 7 8 8 9
 4  | 0 1 2 2 2 3 3 3 4 4 5 5 6 6 8 8 9 9 9


*SOURCE org/mathpiper/builtin/procedures/optional/StemAndLeaf.java
==========
*CMD StringFormat --- format a string using format specifiers

*CALL
StringFormat(formatString, expr, ...)

*PARMS

{formatString} -- a string that contains format specifiers and literals
{expr} -- expressions that are associated with the format specifiers

*DESC
{Format String}

Composed of format specifiers and literals. Arguments are required only if there are format specifiers in the
format string. Format specifiers include flags, width specifiers, precision specifiers, and conversion characters in the following
sequence:

{% [flags] [width] [.precision] conversion-character}

(brackets indicate optional parameters)

{Flags}

|table
|-|left-justify (right-justify is the default)
|+|place a plus sign {+} or minus sign {-} sign to the left of a number
|0|zero-pad numbers (blank padding is the fefault)
|,|add commas to numbers that are greater than 1000
| |a space will place a minus sign to the left of a number if it is negative
|/table

{Width}

Specifies the field width for outputting the argument and represents the minimum number of characters to
be written to the output. Include space for expected commas and a decimal point in the determination of
the width for numerical values.

{Precision}

Used to restrict the output depending on the conversion. It specifies the number of digits of precision when
outputting floating-point values or the length of a substring to extract from a String. Numbers are rounded
to the specified precision.

{Conversion-Characters}

|table
|d|integer number
|f|decimal number
|s|String
|S|Upper case string
|h|hashcode
|n|newline
|/table

*EXAMPLES
In> StringFormat("%d + %.3f == %f", 1, 2.2, 3.2) 
Result: "1 + 2.200 == 3.200000"

*SEE Printf

*SOURCE org/mathpiper/builtin/procedures/optional/StringFormat.java
==========
*CMD StringTag --- Add parts of speech tags to the words in English sentences. 
*CALL
	StringTag(string)

*PARMS
{string} -- a string that contains English sentences


*DESC
This function accepts a string that contains English sentences, and it returns a list of strings that
contain words tagged with the following parts of speech tags:

|table
|"|quote|"
|#|Pound sign|#
|\$|Dollar sign|\$
|(|Left paren|(
|)|Right paren|)
|,|Comma|,
|.|Sent-final punct|. ! ?
|:|Mid-sent punctuation|: ;
|CC|Coordinating conjunction|and,but,or
|CD|Cardinal number|one,two
|DT|Determiner|the,some
|EX|Existential|there,there
|FW|Foreign word|mon,dieu
|IN|Preposition or subordinating conjunction|of,in,by
|JJ|Adjective|big	
|JJR|Adjective, comparative|bigger
|JJS|Adjective, superlative|biggest
|LS|List item marke|1,One
|MD|Modal|can,should
|NN|Noun, singular or mass|dog
|NNP|Proper noun, singular|Edinburgh
|NNPS|Proper noun, plural|Smiths
|NNS|Noun, plural|dogs
|PDT|Predeterminer|all,both
|POS|Possessive ending|'s
|PP|Personal pronoun|I,you,she
|PP\$|Possessive pronoun|my,one's
|PRP|Personal|pronoun
|PRP\$|Possessive|pronoun
|RB|Adverb|quickly
|RBR|Adverb, comparative|faster
|RBS|Adverb, superlative|fastest
|RP|Particle|up,off
|SYM|Symbol|+,%,&
|TO|'to'|to
|UH|Interjection|oh,oops
|VB|Verb, base form|eat
|VBD|Verb, past tense|ate
|VBG|Verb, gerund or present participle|eating	
|VBN|Verb, past participle|eaten
|VBP|Verb, non-3rd person singular present|eat
|VBZ|Verb, 3rd person singular present|eats
|WDT|Wh-determiner|which,that
|WP|Wh-pronoun|who,what	
|WP\$|Possessive wh-pronoun|whose
|WRB|Wh-adverb|how,where
|/table

*E.G.
In> StringTag("The dog barked.")
Result: [["The","DT"],["dog","NN"],["barked","VBD"],[".","."]]


*SOURCE org/mathpiper/builtin/procedures/optional/StringTag.java
==========
*CMD AskUser --- displays a message to the user in a dialog.
*CORE
*CALL
	TellUser(message)

*PARMS

{message} -- a message to display to the user

*DESC

This function allows a message to be displayed to the user.  The message will be
displayed in a GUI dialog box.

*SEE AskUser

*SOURCE org/mathpiper/builtin/procedures/optional/TellUser.java
==========
*CMD TextToSpeech --- converts text to an audio file
*CORE
*CALL
	TextToSpeech(text, ipAddress, soundFilePath)

*PARMS

{text} -- a string that contains text
{filePath} -- a path to a sound file
{ipAddress} -- a string that contains an IP address


*DESC

This procedure uses a server to convert text to an audio file.


*SOURCE org/mathpiper/builtin/procedures/optional/TextToSpeech.java
==========
 *CMD TreeView --- display an expression tree

 *CALL
 TreeView(expression, option, option, option...)

 *PARMS
 {expression} -- an expression (which may be in string form) to display as an expression tree

 {Options:}

 {Scale} -- a value that sets the initial size of the tree

 {Resizable} -- if set to True, a resizing slider is displayed

 {IncludeExpression} -- if set to True, the algebraic form of the expression is included above the tree

 {Lisp} -- if set to True, the expression must be a string that is in Lisp form

 {Code} -- if set to True, the expression is rendered using code symbols instead of mathematical symbols


 *DESC
 Returns a Java GUI component that contains an expression rendered as an
 expression tree.

 Options are entered using the : operator.
 For example, here is how to disable {Resizable} option: {Resizable: False}.

 Right click on the images that are displayed to save them.
 
 *E.G.

 In> Show(TreeView( '(_a*(_b+_c) == _a*_b + _a*_c)))
 Result: java.awt.Component

 In> Show(TreeView( "_a*(_b+_c) == _a*_b + _a*_c"))
 Result: java.awt.Component

 In> Show(TreeView( "(+ 1 (* 2 3))", Lisp: True))
 Result: java.awt.Component


 *SEE Show

*SOURCE org/mathpiper/builtin/procedures/optional/TreeView.java
==========
*CMD ViewHelp --- display the procedure help window
*CORE
*CALL
    ViewHelp()

*DESC

Displays the procedure help window.

*E.G.
The ViewXXX procedures all return a reference to the Java JFrame windows which they are displayed in.
This JFrame instance can be used to hide, show, and dispose of the window.

In> frame := ViewHelp()
Result: javax.swing.JFrame

In> JavaCall(frame, "hide")
Result: True

In> JavaCall(frame, "show")
Result: True

In> JavaCall(frame, "dispose")
Result: True


*SOURCE org/mathpiper/builtin/procedures/optional/ViewCircuitPiper.java
==========
*CMD ViewConsole --- show a color chooser dialog
*CORE
*CALL
    ViewColorChooser()

*DESC

Show a color chooser dialog.

*E.G.

In> ViewColorChooser()
Result: [200,52,123]


*SOURCE org/mathpiper/builtin/procedures/optional/ViewColorChooser.java
==========
*CMD ViewEnvironment --- show the console window
*CORE
*CALL
    ViewEnvironment()

*DESC

Shows the MathPiper environment.

*E.G.
The ViewXXX procedures all return a reference to the Java JFrame windows which they are displayed in.
This JFrame instance can be used to hide, show, and dispose of the window.

In> frame := ViewEnvironment()
Result: javax.swing.JFrame

In> JavaCall(frame, "hide")
Result: True

In> JavaCall(frame, "show")
Result: True

In> JavaCall(frame, "dispose")
Result: True


*SOURCE org/mathpiper/builtin/procedures/optional/ViewEnvironment.java
==========
*CMD ViewConsole --- show the console window
*CORE
*CALL
    ViewGraphicConsole()

*DESC

Shows the graphic console window.

*E.G.
The ViewXXX procedures all return a reference to the Java JFrame windows which they are displayed in.
This JFrame instance can be used to hide, show, and dispose of the window.

In> frame := ViewGraphicConsole()
Result: javax.swing.JFrame

In> JavaCall(frame, "hide")
Result: True

In> JavaCall(frame, "show")
Result: True

In> JavaCall(frame, "dispose")
Result: True


*SOURCE org/mathpiper/builtin/procedures/optional/ViewGraphicConsole.java
==========
*CMD ViewHelp --- display the procedure help window
*CORE
*CALL
    ViewHelp()

*DESC

Displays the procedure help window.

*E.G.
The ViewXXX procedures all return a reference to the Java JFrame windows which they are displayed in.
This JFrame instance can be used to hide, show, and dispose of the window.

In> frame := ViewHelp()
Result: javax.swing.JFrame

In> JavaCall(frame, "hide")
Result: True

In> JavaCall(frame, "show")
Result: True

In> JavaCall(frame, "dispose")
Result: True


*SOURCE org/mathpiper/builtin/procedures/optional/ViewHelp.java
==========
*CMD ViewHtml --- display rendered HTML code

*CALL
    ViewHtml(string)

*PARMS
{string} -- a string which contains HTML code

*DESC
Display rendered HTML code.

*E.G.
/%html
<html>
    <title>
    HTML Demo
    </title>

    <body>
        <h1>HTML demo 1.</h1>


        <h2>LaTeX math formulas can be placed into the HTML code.</h2>
        \$x_{j}\$

    </body>
</html>
/%/html



The ViewXXX procedures all return a reference to the Java JFrame windows which they are displayed in.
This JFrame instance can be used to hide, show, and dispose of the window.

In> frame := ViewHtml("<html><body>Hello</body></html>")
Result: javax.swing.JFrame

In> JavaCall(frame, "hide")
Result: True

In> JavaCall(frame, "show")
Result: True

In> JavaCall(frame, "dispose")
Result: True


*SOURCE org/mathpiper/builtin/procedures/optional/ViewHtml.java
==========
*CMD ViewList --- display an expression in Lisp box diagram form

*CALL
    ViewList(expression)

*PARMS
{expression} -- an expression to view

*DESC
Display an expression in Lisp box diagram form.

*E.G.
In> ViewList(x^2)

In> ViewList(2*x^3+14*x^2+24*x)

 

The ViewXXX procedures all return a reference to the Java JFrame windows which they are displayed in.
This JFrame instance can be used to hide, show, and dispose of the window.

In> frame := ViewList(x^2)
Result: javax.swing.JFrame

In> JavaCall(frame, "hide")
Result: True

In> JavaCall(frame, "show")
Result: True

In> JavaCall(frame, "dispose")
Result: True

*SEE UnparseLisp, ViewMath

*SOURCE org/mathpiper/builtin/procedures/optional/ViewList.java
==========
*CMD ViewMath --- display an expression in traditional form

*CALL
    ViewMath(expression)

*PARMS
{expression} -- an expression to view

*DESC
Display an expression in traditional form.

*E.G.
In> ViewMath(Expand((2*x)*(x+3)*(x+4)));

In> ViewMath(15*x^2 * Hold(Integrate(x,0,Infinity)Exp(-x^2)));


 
/%mathpiper

index := 1;

expressionsList := [];

While(index <= 9)
[
   expressionsList := Append(expressionsList, RandomPoly(x,3,1,10));

   index++;
];

matrix := Partition(expressionsList,3);

ViewMath(matrix);

/%/mathpiper
 
 
 
The ViewXXX procedures all return a reference to the Java JFrame windows which they are displayed in.
This JFrame instance can be used to hide, show, and dispose of the window.
 

In> frame := ViewMath(x^2)
Result: javax.swing.JFrame

In> JavaCall(frame, "hide")
Result: True

In> JavaCall(frame, "show")
Result: True

In> JavaCall(frame, "dispose")
Result: True

*SEE ViewList

*SOURCE org/mathpiper/builtin/procedures/optional/ViewMath.java
==========
*CMD ViewOscilloscope --- display the virtual oscilloscope
*CALL
    ViewOscilloscope()

*DESC

Displays the virtual oscilloscope.

*E.G.
The ViewXXX procedures all return a reference to the Java JFrame windows which they are displayed in.
This JFrame instance can be used to hide, show, and dispose of the window.

In> frame := ViewOscilloscope()
Result: javax.swing.JFrame

In> JavaCall(frame, "hide")
Result: True

In> JavaCall(frame, "show")
Result: True

In> JavaCall(frame, "dispose")
Result: True


*SOURCE org/mathpiper/builtin/procedures/optional/ViewOscilloscope.java
==========
*CMD BarChart --- displays a graphic bar chart
*CORE
*CALL
	BarChart([x_axis_list, y_axis_list], option, option, option...)
    BarChart([x_axis_list_1, y_axis_list_1, x_axis_list_2, y_axis_list_2,...], option, option, option...)

*PARMS

{x_axis_list} -- a list which contains the x axis values

{y_axis_list} -- a list which contains the y axis values that go with the x axis values

{title} -- the title of the scatter plot

{xAxisLabel} -- the label for the x axis

{yAxisLabel} -- the label for the y axis

{seriesTitle} -- the title for a single data series

{series<x>Title} -- the title for more than one series. <x> can be 1, 2, 3, etc.

*DESC

Creates either a single bar chart or multiple bar charts on the same plot. Options are entered using the : operator.
For example, here is how to set the {title} option: {title: "Example Title"}.

*E.G.
/%mathpiper,title=""

claim := 1 .. 40;
days := [48,41,35,36,37,26,36,46,35,47,35,34,36,42,43,36,56,32,46,30,37,43,17,26,28,27,45,33,22,27,16,22,33,30,24,23,22,30,31,17];
BarChart([claim, days], title: "Bar Chart", series1Title: "Series 1", xAxisLabel: "Claim", yAxisLabel: "Days");

/%/mathpiper


/%mathpiper,title=""

claim := 1 .. 40;
days1 := [48,41,35,36,37,26,36,46,35,47,35,34,36,42,43,36,56,32,46,30,37,43,17,26,28,27,45,33,22,27,16,22,33,30,24,23,22,30,31,17];
days2 := RandomIntegerList(Length(claim), 20, 50);
BarChart([claim, days1, claim, days2], title: "Bar Chart", series1Title: "Series 1", series2Title: "Series 2", xAxisLabel: "Claim", yAxisLabel: "Days");

/%/mathpiper

*SEE Show, LineChart, PieChart, Histogram, ScatterPlot, CumulativePlot

*SOURCE org/mathpiper/builtin/procedures/plugins/jfreechart/BarChart.java
==========
*CMD CumulativePlot --- displays a graphic cumulative plot
*CORE
*CALL
	CumulativePlot(list, option, option, option...)

*PARMS

{list} -- a list which contains the values

{numberOfBins} -- the number of bins in the histogram

{title} -- the title of the histogram

{xAxisLabel} -- the label for the x axis

{yAxisLabel} -- the label for the y axis

{seriesTitle} -- the title for a single data series


*DESC

Creates a cumulative plot. Options are entered using the : operator.
For example, here is how to set the {title} option: {title: "Example Title"}.

*E.G.
/%mathpiper,title=""

samples := [
438,413,444,468,445,472,474,454,455,449,
450,450,450,459,466,470,457,441,450,445,
487,430,446,450,456,433,455,459,423,455,
451,437,444,453,434,454,448,435,432,441,
452,465,466,473,471,464,478,446,459,464,
441,444,458,454,437,443,465,435,444,457,
444,471,471,458,459,449,462,460,445,437,
461,453,452,438,445,435,454,428,454,434,
432,431,455,447,454,435,425,449,449,452,
471,458,445,463,423,451,440,442,441,439
];

CumulativePlot(samples,numberOfBins: 10, title: "Cumulative Plot", xAxisLabel: "X Axis", yAxisLabel: "Y Axis", seriesTitle: "Series Title");

/%/mathpiper

*SEE Show, BarChart, LineChart, PieChart, Histogram, ScatterPlot

*SOURCE org/mathpiper/builtin/procedures/plugins/jfreechart/CumulativePlot.java
==========
*CMD Histogram --- displays a graphic histogram
*CORE
*CALL
	Histogram(list, option, option, option...)
    Histogram([list1, list2, list3...], option, option, option...)

*PARMS

{list} -- a list which contains the values

{binMinimum} -- the minimum bin value

{binMaximum} -- the maximum bin value

{numberOfBins} -- the number of bins in the histogram

{title} -- the title of the histogram

{xAxisLabel} -- the label for the x axis

{yAxisLabel} -- the label for the y axis

{seriesTitle} -- the title for a single data series

{series<x>Title} -- the title for more than one series. <x> can be 1, 2, 3, etc.

*DESC

Creates either a single histogram or multiple histograms on the same plot. Options are entered using the : operator.
For example, here is how to set the {title} option: {title: "Example Title"}.

*E.G.
/%mathpiper

Histogram([1.0, 1.1, 1.1, 1.2, 1.7, 2.2, 2.5, 4.0]);

/%/mathpiper


/%mathpiper

Histogram([1.0, 1.1, 1.1, 1.2, 1.7, 2.2, 2.5, 4.0, 4.2], seriesTitle: "Options Example", xAxisLabel: "X Axis", yAxisLabel: "Y Axis");

/%/mathpiper


/%mathpiper

Histogram([1.0, 1.1, 1.1, 1.2, 1.7, 2.2, 2.5, 4.0, 4.2], orientation: "horizontal");

/%/mathpiper


/%mathpiper,title=""

pileESamples := [16.375,16.375,17.125,16,14.375,17.25,16.625,16,17,17.25,17,15.875,16.625,16.125,17.125,16.875,16.375,16.375,16.875,17.125,17,16.75,17.25,17.125,15.375];
pileDSamples := [18.25,19.25,18.25,15.625,17.625,17.5,17.125,17.125,17.5,14.5,17.375,16.875,17.75,18.875,14.875,19.25,18.125,16.25,16.125,16.75,17.25,17.375,17.125,17.5,16.625];

Histogram([pileDSamples, pileESamples], title: "Wood Piles", series1Title: "Pile D", series2Title: "Pile E");

/%/mathpiper


/%mathpiper,title=""

numberOfRoles := 1000;

dieRolesList := RandomIntegerList(numberOfRoles,1,6);

Histogram(dieRolesList, binMinimum: .5, binMaximum: 6.5, numberOfBins: 6, title: "Single Die Rolls", xAxisLabel: "Number Rolled", yAxisLabel: "Frequency", seriesTitle: ToString(numberOfRoles) ~ " Roles");

/%/mathpiper

*SEE Show, BarChart, LineChart, PieChart, ScatterPlot, CumulativePlot

*SOURCE org/mathpiper/builtin/procedures/plugins/jfreechart/Histogram.java
==========
*CMD LineChart --- displays a graphic line chart
*CORE
*CALL
	LineChart([domain_list, range_list], option, option, option...)
    LineChart([domain_list_1, range_list_1, domain_list_2, range_list_2,...], option, option, option...)

*PARMS

{domain_list} -- a list which contains the domain values

{range_list} -- a list which contains the range values that go with the domain_list values

{title} -- the title of the line chart

{xAxisLabel} -- the label for the x axis

{yAxisLabel} -- the label for the y axis

{seriesTitle} -- the title for a single data series

{series<x>Title} -- the title for more than one series. <x> can be 1, 2, 3, etc.

*DESC

Creates either a single line chart or multiple line charts on the same plot. Options are entered using the : operator.
For example, here is how to set the {title} option: {title: "Example Title"}.

*E.G.
/%mathpiper,title=""

claim := 1 .. 40;
days := [48,41,35,36,37,26,36,46,35,47,35,34,36,42,43,36,56,32,46,30,37,43,17,26,28,27,45,33,22,27,16,22,33,30,24,23,22,30,31,17];
LineChart([claim, days], title: "Line Chart", series1Title: "Series 1", xAxisLabel: "Claim", yAxisLabel: "Days");

/%/mathpiper


/%mathpiper,title=""

claim := 1 .. 40;
days1 := [48,41,35,36,37,26,36,46,35,47,35,34,36,42,43,36,56,32,46,30,37,43,17,26,28,27,45,33,22,27,16,22,33,30,24,23,22,30,31,17];
days2 := RandomIntegerList(Length(claim), 20, 50);
LineChart([claim, days1, claim, days2], title: "Line Chart", series1Title: "Series 1", series2Title: "Series 2", xAxisLabel: "Claim", yAxisLabel: "Days");

/%/mathpiper

*SEE Show, BarChart, PieChart, Histogram, ScatterPlot, CumulativePlot

*SOURCE org/mathpiper/builtin/procedures/plugins/jfreechart/LineChart.java
==========
*CMD PieChart --- displays a graphic pie chart

*CALL
    PieChart(associationList, option, option, option...)


*PARMS

{accociationList} -- an association list that contains the key/value pairs

{Options:}

{title} -- a string that specifies a title for chart

{title} -- a string that specifies a subtitle for chart

{ledgend} -- a boolean that indicates if a ledgend should be provides

{tooltips} -- a boolean that indicates if tooltip information should be provided


*DESC

This procedure creates a pie chart. Options are entered using the : operator.
For example, here is how to set the {title} option: {title: "Example Title"}.

*E.G.
In> list := [["Pears", 27.8], ["Oranges", 16.8], ["Apples", 17.1], ["Others", 55.3]]
Result: [["Pears",27.8],["Oranges",16.8],["Apples",17.1],["Others",55.3]]

In> Show(PieChart(list, title: "Fruit"))
Result: class javax.swing.JFrame

*SEE Show, BarChart, LineChart, Histogram, ScatterPlot, CumulativePlot

*SOURCE org/mathpiper/builtin/procedures/plugins/jfreechart/PieChart.java
==========
*CMD ScatterPlot --- displays a graphic scatter plot
*CORE
*CALL
	ScatterPlot([domain_list, range_list], option, option, option...)
    ScatterPlot([domain_list_1, range_list_1, domain_list_2, range_list_2,...], option, option, option...)

*PARMS

{domain_list} -- a list which contains the domain values

{range_list} -- a list which contains the range values that go with the domain_list values

{title} -- the title of the scatter plot

{xAxisLabel} -- the label for the x axis

{yAxisLabel} -- the label for the y axis

{seriesTitle} -- the title for a single data series

{series<x>Title} -- the title for more than one series. <x> can be 1, 2, 3, etc.

*DESC

Creates either a single scatter plot or multiple scatter plots on the same plot. Options are entered using the : operator.
For example, here is how to set the {title} option: {title: "Example Title"}.

*E.G.
/%mathpiper,title=""

claim := 1 .. 40;
days := [48,41,35,36,37,26,36,46,35,47,35,34,36,42,43,36,56,32,46,30,37,43,17,26,28,27,45,33,22,27,16,22,33,30,24,23,22,30,31,17];
ScatterPlot([claim, days], title: "Scatter Plot", series1Title: "Series 1", xAxisLabel: "Claim", yAxisLabel: "Days");

/%/mathpiper


/%mathpiper,title=""

claim := 1 .. 40;
days1 := [48,41,35,36,37,26,36,46,35,47,35,34,36,42,43,36,56,32,46,30,37,43,17,26,28,27,45,33,22,27,16,22,33,30,24,23,22,30,31,17];
days2 := RandomIntegerList(Length(claim), 20, 50);
ScatterPlot([claim, days1, claim, days2], title: "Scatter Plot", series1Title: "Series 1", series2Title: "Series 2", xAxisLabel: "Claim", yAxisLabel: "Days");

/%/mathpiper

*SEE Show, BarChart, LineChart, PieChart, Histogram, CumulativePlot

*SOURCE org/mathpiper/builtin/procedures/plugins/jfreechart/ScatterPlot.java
==========
*CMD ? --- previous result
*CORE
*CALL
    ?

*DESC

{?} evaluates to the previous result on the command line. {?} is a global
variable that is bound to the previous result from the command line.
Using {?} will evaluate the previous result. (This uses the procedureality
offered by the {AssignGlobalLazy} command).

*E.G.

In> 2+2
Result: 4

In> ?
Result: 4


*SEE AssignGlobalLazy

*SOURCE org/mathpiper/scripts4/a_initialization/miscellaneous/miscellaneousdocs.mpws
==========
*CMD True --- boolean constant representing true
*CMD False --- boolean constant representing false
*CORE
*CALL
        True
        False

*DESC

{True} and {False} are typically a result
of boolean expressions such as {2 <? 3} or {True &? False}.

*SEE &?, |?, !?

*SOURCE org/mathpiper/scripts4/a_initialization/miscellaneous/miscellaneousdocs.mpws
==========
*CMD EndOfFile --- end-of-file marker
*CORE
*CALL
        EndOfFile

*DESC

End of file marker when reading from file. If a file
contains the expression {EndOfFile;} the
operation will stop reading the file at that point.

*SOURCE org/mathpiper/scripts4/a_initialization/miscellaneous/miscellaneousdocs.mpws
==========

*CMD Infinity --- constant representing mathematical infinity
*STD
*CALL
        Infinity

*DESC

Infinity represents infinitely large values. It can be the result of certain
calculations.

Note that for most analytic procedures MathPiper understands {Infinity} as a positive number.
Thus {Infinity*2} will return {Infinity}, and {a < Infinity} will evaluate to {True}.

*EXAMPLES
In> 2*Infinity 
Result: Infinity

In> 2 <? Infinity 
Result: True


*SOURCE org/mathpiper/scripts4/a_initialization/miscellaneous/miscellaneousdocs.mpws
==========
*CMD Undefined --- constant signifying an undefined result
*STD
*CALL
        Undefined

*DESC

{Undefined} is a token that can be returned by a function when it considers
its input to be invalid or when no meaningful answer can be given. The result is then "undefined".

Most procedures also return {Undefined} when evaluated on it.

*EXAMPLES
In> 0*Infinity 
Result: Undefined

In> Undefined+2*Exp(Undefined) 
Result: Undefined


*SEE Infinity

*SOURCE org/mathpiper/scripts4/a_initialization/miscellaneous/miscellaneousdocs.mpws
==========
*CMD        /* --- Start of comment
*CMD        */ --- end of comment
*CMD        // --- Beginning of one-line comment
*CORE
*CALL
        /* comment */
        // comment

*DESC

Introduce a comment block in a source file, similar to C++ comments.
{//} makes everything until the end of the line a comment, while {/*} and {*/} may delimit a multi-line comment.

*E.G..

//This comments out a whole line.

_a + _b; //This comments out the rest of a line.

a + /* This comments out everything between
the comment markers. */ b;

*SOURCE org/mathpiper/scripts4/a_initialization/miscellaneous/miscellaneousdocs.mpws
==========
*CMD {} --- encloses a block of statements
*CORE
*CALL

        { statement1; statement2; ... }

*PARMS

{statement1}, {statement2} -- expressions

*DESC

The {Sequence} and the {&#123; ... &#125;} construct have the same effect: they evaluate all
arguments in order and return the result of the last evaluated expression.

{Sequence(_a,_b);} is the same as typing {&#123;_a;_b;&#125;} and is very useful for writing out
function bodies. The {&#123; ... &#125;} construct is a syntactically nicer version of the
{Sequence} call; it is converted into {Sequence(...)} during the parsing stage.

*SEE Sequence

*SOURCE org/mathpiper/scripts4/a_initialization/miscellaneous/miscellaneousdocs.mpws
==========
*CMD None --- used with association lists
*CORE
*CALL
        None

*DESC

A constant that is used to indicate that an association list does not have a value for a given key.

*SOURCE org/mathpiper/scripts4/a_initialization/miscellaneous/miscellaneousdocs.mpws
==========
*CMD Nth --- return the $n$-th element of a list
*CORE
*CALL
        Nth(list, n)

*PARMS

{list} -- list to choose from

{n} -- index of entry to pick

*DESC

The entry with index "n" from "list" is returned. The first entry
has index 1. It is possible to pick several entries of the list by
taking "n" to be a list of indices.

More generally, {Nth} returns the n-th operand of the
expression passed as first argument.

An alternative but equivalent form of {Nth(list, n)} is
{list[n]}.

*E.G.

In> lst := [_a,_b,_c,13,19];
Result: [_a,_b,_c,13,19];

In> Nth(lst, 3);
Result: _c;

In> lst[3];
Result: _c;

In> Nth(lst, [3,4,1]);
Result: [_c,13,a];

In> Nth(_b*(_a+_c), 2);
Result: _a+_c;

*EXAMPLES

*SEE NthItem, Select

*SOURCE org/mathpiper/scripts4/a_initialization/standard/A_Nth.mpws
==========
*CMD ArgumentsCount --- return number of top-level arguments
*STD
*CALL
        ArgumentsCount(expr)

*PARMS

{expr} -- expression to examine

*DESC

This procedure evaluates to the number of top-level arguments of the
expression "expr". The argument "expr" may not be an atom, since
that would lead to an error.

*EXAMPLES
In> ArgumentsCount('anyProcedure(_a,3,Pi)) 
Result: 3

In> ArgumentsCount(Sin(_x)) 
Result: 1

In> ArgumentsCount(_a*(_b+_c)) 
Result: 2

*SEE Type, Length

*SOURCE org/mathpiper/scripts4/a_initialization/standard/ArgumentsCount.mpws
==========
*CMD Denominator --- denominator of an expression
*STD
*CALL
        Denominator(expr)

*PARMS

{expr} -- expression to determine denominator of

*DESC

This procedure determines the denominator of the rational expression
"expr" and returns it. As a special case, if its argument is numeric
but not rational, it returns {1}. If "expr" is
neither rational nor numeric, the procedure returns unevaluated.

*EXAMPLES
Denominator(2/7) -> 7

Denominator('_a / '_x^2) -> '_x^2

Denominator('-_a / '_x^2) -> '_x^2

Denominator(5) -> 1

*File: ../src/org/mathpiper/scripts4/a_initialization/standard/Denominator.mpw

*SEE Numerator, Rational?, Number?

*SOURCE org/mathpiper/scripts4/a_initialization/standard/Denominator.mpws
==========
*CMD NonObject? --- test whether argument is not an [Object()]
*STD
*CALL
        NonObject?(expr)

*PARMS

{expr} -- the expression to examine

*DESC

This procedure returns {True} if "expr" is not of
the form {Object(...)} and {False}
otherwise.

*HEAD Bugs

In fact, the result is always [True].

*SEE Object

*SOURCE org/mathpiper/scripts4/a_initialization/standard/NonObject_.mpws
==========
*CMD NthItem --- version of Nth that unparses to a procedure

*CALL
        NthItem(list, index)

*PARMS

{list} -- list to choose from

{index} -- index of the item to obtain

*DESC

This is a version of the "Nth" procedure that
unparses to a procedure instead of an operator. The
variable {index} will accept an integer or an integer
that has the unit "1".

*SEE Nth

*SOURCE org/mathpiper/scripts4/a_initialization/standard/NthItem.mpws
==========
*CMD Numerator --- numerator of an expression
*STD
*CALL
        Numerator(expr)

*PARMS

{expr} -- expression to determine numerator of

*DESC

This procedure determines the numerator of the rational expression
"expr" and returns it. As a special case, if its argument is numeric
but not rational, it returns this number. If "expr" is neither
rational nor numeric, the procedure returns unevaluated.

*EXAMPLES
Numerator(2/7) -> 2

Numerator('a / 'x^2) -> 'a

Numerator('-a / 'x^2) -> '-a

Numerator(5) -> 5

*SEE Denominator, Rational?, Number?

*SOURCE org/mathpiper/scripts4/a_initialization/standard/Numerator.mpws
==========
*CMD == --- symbolic equality operator
*STD
*CALL
    expression == expression

*PARMS

{expression} -- an expression

*DESC

This operator is used to symbolically represent the equality
of two expressions as opposed to the = operator which performs
a comparison operation on two expressions.

*E.G.

In> Solve(y == m*x + b, x)
Result: [x==(y-b)/m]

*SEE !==

*SOURCE org/mathpiper/scripts4/a_initialization/standard/equals_equals_operator.mpws
==========
*CMD !== --- symbolic inequality operator
*STD
*CALL
    expression !== expression

*PARMS

{expression} -- an expression

*DESC

This operator is used to symbolically represent the inequality
of two expressions as opposed to the != operator which performs
a comparison operation on two expressions.


*SEE ==

*SOURCE org/mathpiper/scripts4/a_initialization/standard/exclamationpoint_equals_equals_operator.mpws
==========
*CMD -:= --- subtract to a variable
*STD
*CALL
        var -:= subVar

*PARMS

{var} -- variable to subtract from
{subVar} -- variable to subtract
*DESC

The variable with name "subVar" is subtracted from var. This operation is a destructive assignment, ie. the 
variable is over written with the result of var - subVar. The expression {x -:= y} is equivalent to
the assignment {x := x - y}.

*EXAMPLES
In> test := 9 
Result: 9

In> test -:= 5 
Result: 4

In> test 
Result: 4

In> x := 1 
Result: 1

In> x -:= 3 
Result: -2

In> x 
Result: -2

*SEE :=, --


*SOURCE org/mathpiper/scripts4/a_initialization/standard/minus_colon_equals.mpws
==========
*CMD -- --- decrement variable
*STD
*CALL
        var--

*PARMS

{var} -- variable to decrement

*DESC

The variable with name "var" is decremented, i.e. the number 1 is
subtracted from it. The expression {x--} is
equivalent to the assignment {x := x - 1}.

*E.G.
In> x := 5;
Result: 5;

In> x--;
Result: 4;

In> x;
Result: 4;

*SEE ++, :=

*SOURCE org/mathpiper/scripts4/a_initialization/standard/minus_minus_operator.mpws
==========
*CMD NM --- try to determine an numerical approximation of expression

*CALL
        NM(expression)
        NM(expression, precision)
*PARMS

{expression} -- expression to evaluate

{precision} -- integer, precision to use

*DESC

The procedure {NM} instructs {MathPiper} to try to coerce an expression in to a numerical approximation to the
expression {expr}, using {prec} digits precision if the second calling
sequence is used, and the default precision otherwise. This overrides the normal
behaviour, in which expressions are kept in symbolic form (eg. {Sqrt(2)} instead of {1.41421}).

Application of the {NM} operator will make MathPiper
calculate floating point representations of procedures whenever
possible. In addition, the variable {Pi} is bound to
the value of $Pi$ calculated at the current precision.
(This value is a "cached constant", so it is not recalculated each time {NM} is used, unless the precision is increased.)


{NM} is a macro. Its argument {expr} will only
be evaluated after switching to numeric mode.

*E.G.
In> 1/2
Result: 1/2;

In> NM(1/2)
Result: 0.5;

In> SinE(1)
Result: Sin(1);

In> NM(SinE(1),10)
Result: 0.8414709848;

In> Pi
Result: Pi;

In> NM(Pi,20)
Result: 3.1415926535897932385

*SEE Pi, NumericMode?, NonNM

*SOURCE org/mathpiper/scripts4/a_initialization/standard/numeric.mpws
==========
*CMD NumericMode? --- determine if currently in numeric mode

*CALL
        NumericMode?()

*DESC

When in numeric mode, {NumericMode?()} will return {True}, else it will
return {False}. {MathPiper} is in numeric mode when evaluating an expression
with the procedure {NM}. Thus when calling {NM(expr)}, {NumericMode?()} will
return {True} while {expr} is being evaluated.

{NumericMode?()} would typically be used to define a transformation rule
that defines how to get a numeric approximation of some expression. One
could define a transformation rule

        f(x_)::NumericMode?() -> {... some code to get a numeric approximation of f(x) ... }

{NumericMode?()} usually returns {False}, so transformation rules that check for this
predicate are usually left alone.


*E.G.
In> NumericMode?()
Result: False

In> NM(NumericMode?())
Result: True

*SEE NM, BuiltinPrecisionSet, BuiltinPrecisionGet, Pi, CachedConstant

*SOURCE org/mathpiper/scripts4/a_initialization/standard/numeric.mpws
==========
*CMD NonNM --- calculate part in non-numeric mode

*CALL
        NonNM(expr)

*PARMS
{expr} -- expression to evaluate

*DESC
When in numeric mode, {NonNM} can be called to switch back to non-numeric
mode temporarily.

{NonNM} is a macro. Its argument {expr} will only
be evaluated after the numeric mode has been set appropriately.

*E.G.
In> NM(NonNM(NumericMode?()))
Result: False

*SEE NM, BuiltinPrecisionSet, BuiltinPrecisionGet, Pi, CachedConstant

*SOURCE org/mathpiper/scripts4/a_initialization/standard/numeric.mpws
==========
*CMD +:= --- add to variable or concatenate to a string
*CALL
    var +:= value

*PARMS

{var} -- variable to add to or concatenate to
{value} -- value to add or concatenate

*DESC
Add a value to var, or contenate to var if value is a string. This operation is a
destructive assignment, ie. the variable is over written with the result of var + 
value. The expression {x +:= y} is equivalent to the assignment {x := x + y}.

*E.G.
In> var := 3;
Result: 3

In> var +:= 2;
Result: 5

In> var
Result: 5

In> var := "A"
Result: "A"

In> var +:= "B"
Result: "AB"

In> var
Result: "AB"

*SEE :=, ++

*SOURCE org/mathpiper/scripts4/a_initialization/standard/plus_colon_equals.mpws
==========
*CMD ++ --- increment variable
*STD
*CALL
        var++

*PARMS

{var} -- variable to increment

*DESC

The variable with name "var" is incremented, i.e. the number 1 is
added to it. The expression {x++} is equivalent to
the assignment {x := x + 1}.

*E.G.
In> x := 5;
Result: 5;

In> x++;
Result: 6;

In> x;
Result: 6;

*SEE --, :=

*SOURCE org/mathpiper/scripts4/a_initialization/standard/plus_plus_operator.mpws
==========
*CMD * --- arithmetic multiplication
*STD
*CALL
        x*y

*PARMS

{x} and {y} -- objects for which arithmetic multiplication is defined

*DESC

The multiplication operator can work on integers,
rational numbers, complex numbers, vectors, matrices and lists.

This operator is implemented in the standard math library (as opposed
to being built-in). This means that they can be extended by the user.

*EXAMPLES
In> 2*3 
Result: 6

*SEE +, -, /, ^

*SOURCE org/mathpiper/scripts4/a_initialization/stdarith/asterisk_operator.mpws
==========
*CMD ^ --- arithmetic power
*STD
*CALL
        x^y

*PARMS

{x} and {y} -- objects for which arithmetic operations are defined

*DESC

These are the basic arithmetic operations. They can work on integers,
rational numbers, complex numbers, vectors, matrices and lists.

These operators are implemented in the standard math library (as opposed
to being built-in). This means that they can be extended by the user.

*EXAMPLES
In> 2^3 
Result: 8

*SEE +, -, *, /

*SOURCE org/mathpiper/scripts4/a_initialization/stdarith/caret_operator.mpws
==========
*CMD - --- arithmetic subtraction or negation
*STD
*CALL
        x-y
        -x

*PARMS

{x} and {y} -- objects for which subtraction is defined

*DESC

The subtraction operators can work on integers,
rational numbers, complex numbers, vectors, matrices and lists.

These operators are implemented in the standard math library (as opposed
to being built-in). This means that they can be extended by the user.

*EXAMPLES
In> 2-3 
Result: -1

In> - 3 
Result: -3

*SEE +, *, /, ^

*SOURCE org/mathpiper/scripts4/a_initialization/stdarith/minus_operator.mpws
==========
*CMD + --- arithmetic addition and string concatenation.
*STD
*CALL
        x+y
        +x

*PARMS

{x} and {y} -- objects for which arithmetic addition is defined or strings

*DESC

The addition operators can work on integers,
rational numbers, complex numbers, vectors, matrices, lists and strings.

These operators are implemented in the standard math library (as opposed
to being built-in). This means that they can be extended by the user.

If either or both arguments are strings, they are concatenated.

*EXAMPLES
In> 2 + 3 
Result: 5

In> "one " + "two" 
Result: "one two"

In> 1 + " two" 
Result: "1 two"

In> "one " + 2 
Result: "one 2"

*SEE -, *, /, ^

*SOURCE org/mathpiper/scripts4/a_initialization/stdarith/plus_operator.mpws
==========
*CMD / --- arithmetic division
*STD
*CALL
        x/y

*PARMS

{x} and {y} -- objects for which arithmetic division is defined

*DESC

The division operator can work on integers,
rational numbers, complex numbers, vectors, matrices and lists.

This operator is implemented in the standard math library (as opposed
to being built-in). This means that they can be extended by the user.

*EXAMPLES
In> 6/2 
Result: 3

In> 0/0 
Result: Undefined

*SEE +, -, *, ^

*SOURCE org/mathpiper/scripts4/a_initialization/stdarith/slash_operator.mpws
==========
*CMD Association --- return element stored in association list
*STD
*CALL
        Association(key, alist)

*PARMS

{key} -- string, key under which element is stored

{alist} -- association list to examine

*DESC

The association list "alist" is searched for an entry stored with
index "key". If such an entry is found, it is returned. Otherwise
the atom {None} is returned.

Association lists are represented as a list of two-entry lists. The
first element in the two-entry list is the key, the second element is
the value stored under this key.

The call {Association(key, alist)} can (probably more
intuitively) be accessed as {alist[key]}.

*E.G.

In> writer := [];
Result: [];

In> writer["Iliad"] := "Homer";
Result: True;

In> writer["Henry IV"] := "Shakespeare";
Result: True;

In> writer["Ulysses"] := "James Joyce";
Result: True;

In> Association("Henry IV", writer);
Result: ["Henry IV","Shakespeare"];

In> Association("War and Peace", writer);
Result: None;

*SEE AssociationIndices, :=, AssociationDelete, AssociationValues

*SOURCE org/mathpiper/scripts4/association/Association.mpws
==========
*CMD AssociationDelete --- delete an entry in an association list
*STD
*CALL
        AssociationDelete(alist, "key")
        AssociationDelete(alist, [key, value])

*PARMS

{alist} -- association list

{"key"} -- string, association key

{value} -- value of the key to be deleted

*DESC

The key {"key"} in the association list {alist} is deleted. (The list itself is modified.) If the key was found and successfully deleted, returns {True}, otherwise if the given key was not found, the procedure returns {False}.

The second, longer form of the procedure deletes the entry that has both the
specified key and the specified value. It can be used for two purposes:
*        1. to make sure that we are deleting the right value;
*        2. if several values are stored on the same key, to delete the specified entry (see the last example).

At most one entry is deleted.

*EXAMPLES
In> writer := [] 
Result: []

In> writer["Iliad"] := "Homer" 
Result: "Homer"

In> writer["Henry IV"] := "Shakespeare" 
Result: "Shakespeare"

In> writer["Ulysses"] := "James Joyce" 
Result: "James Joyce"

In> AssociationDelete(writer, "Henry IV") 
Result: True

In> AssociationDelete(writer, "Henry XII") 
Result: False

In> writer 
Result: [["Ulysses","James Joyce"], ["Iliad","Homer"]]

In> Append!(writer,["Ulysses", "Dublin"]) 
Result: [["Ulysses","James Joyce"],["Iliad","Homer"],["Ulysses","Dublin"]]

In> writer["Ulysses"] 
Result: "James Joyce"

In> AssociationDelete(writer,["Ulysses","James Joyce"]) 
Result: True

In> writer 
Result: [["Iliad","Homer"],["Ulysses","Dublin"]]

*SEE Association, AssociationIndices, AssociationValues

*SOURCE org/mathpiper/scripts4/association/AssociationDelete.mpws
==========
*CMD AssociationIndices --- return the keys in an association list
*STD
*CALL
        AssociationIndices(alist)

*PARMS

{alist} -- association list to examine

*DESC

All the keys in the association list "alist" are assembled in a list
and this list is returned.

*E.G.

In> writer := [];
Result: [];

In> writer["Iliad"] := "Homer";
Result: True;

In> writer["Henry IV"] := "Shakespeare";
Result: True;

In> writer["Ulysses"] := "James Joyce";
Result: True;

In> AssociationIndices(writer);
Result: ["Iliad","Henry IV","Ulysses"];

*SEE Association, AssociationDelete, AssociationValues

*SOURCE org/mathpiper/scripts4/association/AssociationIndices.mpws
==========
*CMD AssociationValues --- return the values in an association list
*STD
*CALL
        AssociationValues(alist)

*PARMS

{alist} -- association list to examine

*DESC

All the values in the association list "alist" are assembled in a list
and this list is returned.

*E.G.

In> writer := [];
Result: [];

In> writer["Iliad"] := "Homer";
Result: True;

In> writer["Henry IV"] := "Shakespeare";
Result: True;

In> writer["Ulysses"] := "James Joyce";
Result: True;

In> AssociationValues(writer);
Result: ["Homer","ShakespeareJames Joyce"];

*SEE Association, AssociationDelete, AssociationIndices

*SOURCE org/mathpiper/scripts4/association/AssociationValues.mpws
==========
*CMD : --- associate a value with a name
*CMD :: --- associate a value with a name

*CALL
        name:value
        name::value

*PARMS
{name} -- a name
{value} -- a value

*DESC
These operators are used to associate a name with a value. The {:} operator does not evaluate
its left operand, but it does evaluate its right operand. The {::} operator does not evaluate
its left operand or its right operand. Also, the {:} operator has a much higher precedence
than the {::} operator does.

*E.G.
In> aa := 1
Result: 1

In> aa:aa
Result: aa:1

In> aa::aa
Result: aa::aa

*SOURCE org/mathpiper/scripts4/association/colon_operator.mpws
==========
*CMD FoldGrade --- grade the code in a fold
*STD
*CALL
        FoldGrade(testMessage, points, failHalt?, testBody)

*PARMS

{testMessage} -- A natural language statement 

{points} -- The number of points the check is worth

{failHalt?} -- True means to halt the grading process if the statement is false

{testBody} -- Contains the checking code

*DESC
Each FoldGrade procedure checks for the presence or absence of a fact 
or a concept in the student's source code, or in the result the 
source code returns. What is being checked is specified by the 
natural language statement that is the first argument. FoldGrade returns 
True if the statement is true, and it returns False if the statement 
is false. When a given FoldGrade procedure returns True, the word 
"PASS" is printed, and when it returns False, the word "FAIL" is printed.

The second argument to FoldGrade specifies the number of points the 
check is worth. When all of the points in all of the FoldGrade 
procedures that are in a given %mathpiper_grade fold are set to 
either '0' or '1', this usually means that the given problem is 
not actually being graded in the sense of being assigned a grade 
between 0% and 100%. Instead, the grading code is being used to 
tell the student they need to keep working on their code until it 
passes all of the checks. In worksheets that contain these kind of 
"must pass all of the checks" problems, the student is not permitted to turn in 
the worksheet until all of the checks for all of the problems return "PASS".

The third argument to FoldGrade is a Boolean value that tells the 
automatic grading system if this check is critical enough to stop 
the grading process if the check fails. A value of True indicates 
the check is critical enough to stop the grading process, and a 
value of False indicates the check is not critical enough to stop 
the grading process.

FoldGrade is a bodied procedure, and the fourth argument is a body that 
contains the code that performs the checking.

*SOURCE org/mathpiper/scripts4/autograder/FoldGrade.mpws
==========
*CMD BraceTest --- Test brace allignment within a snippet of code.

*CALL
BraceTest(code)


*PARMS
{code} -- the snippet of code to be tested


*DESC
Tests alignment of braces within a snippet of code {code}

 
*E.G.
In> BraceTest(?code)
Result: True

In> BraceTest(?code)
Result: "The opening brace must be aligned vertically with the first character in its parent's name. Near Line: 6
         The closing brace must be aligned vertically with its opening brace. Near Line: 6"


*SEE IndentationTest


*SOURCE org/mathpiper/scripts4/autograder/code_style.mpws
==========
*CMD IndentationTest --- Test for proper indentation.

*CALL
IndentationTest(code)


*PARMS
{code} -- the snippet of code to be tested


*DESC
Tests for proper indentation style within a snippet of code {code}

 
*E.G.
In> IndentationTest(?code)
Result: True

In> IndentationTest(?code)
Result: "Indentation must be between 2 and 8 spaces. Near Line: 8"


*SEE BraceTest


*SOURCE org/mathpiper/scripts4/autograder/code_style.mpws
==========
*CMD CosN --- cosine (arbitrary-precision math function)
*CALL
        CosN(x)

*DESC

This command performs the calculation of an elementary mathematical
function.  The arguments <i>must</i> be numbers.  The reason for the
postfix {N} is that the library needs to define equivalent non-numerical
procedures for symbolic computations, such as {Exp}, {Sin}, etc.

Note that all xxxN procedures accept integers as well as floating-point numbers.
The resulting values may be integers or floats.  If the mathematical result is an
exact integer, then the integer is returned.  For example, {Sqrt(25)} returns
the integer {5}, and {Power(2,3)} returns the integer {8}.  In such cases, the
integer result is returned even if the calculation requires more digits than set by
{BuiltinPrecisionSet}.  However, when the result is mathematically not an integer,
the procedures return a floating-point result which is correct only to the current precision.

*E.G.
In> BuiltinPrecisionSet(50)
Result: True

In> CosN(0.7)
Result: 0.76484218728448842625585999019186490926821055037373

In>CosN(0.7)^2 + SinN(0.7)^2
Result: 1.0000000000000000000000000000000000000000000000000


*SOURCE org/mathpiper/scripts4/base/CosineN.mpws
==========
*CMD ExpN --- exponential (base 2.718)...(arbitrary-precision math function)
*CALL
        ExpN(x)

    
*PARMS    
{X} -- a real number
    
*DESC

This command performs the calculation of an elementary mathematical
function.  The arguments must be numbers.  The reason for the
postfix {N} is that the library needs to define equivalent non-numerical
procedures for symbolic computations, such as {Exp}, {Sin}, etc.

Note that all xxxN procedures accept integers as well as floating-point numbers.
The resulting values may be integers or floats.  If the mathematical result is an
exact integer, then the integer is returned.  For example, {Sqrt(25)} returns
the integer {5}, and {Power(2,3)} returns the integer {8}.  In such cases, the
integer result is returned even if the calculation requires more digits than set by
{BuiltinPrecisionSet}.  However, when the result is mathematically not an integer,
the procedures return a floating-point result which is correct only to the current precision.

*E.G.
In> ExpN(2)
Result: 7.389056086

In> ExpN(-.3)
Result: 0.7408182204

In> ExpN(0)
Result: 1


*SOURCE org/mathpiper/scripts4/base/ExpN.mpws
==========

*CMD MathExpDoubling --- Multiplies result by itself a specified number of times

*CALL

MathExpDoubling(k, n)

*PARMS

k -- Where k is the value that is being doubled
n -- Where n is the amount of times the value will be doubled

*DESC

The procedure acts as a way of compounding a non-complex rational number (k value) 
by doubling the result of itself the amount specified (n times), where n is rounded up
to the nearest whole number.

*EXAMPLES
In> MathExpDoubling(2, 1) 
Result: 4

In> MathExpDoubling(2, 2) 
Result: 16

In> MathExpDoubling(2, 3) 
Result: 256

*SEE MathMul2Exp, ExpN


*SOURCE org/mathpiper/scripts4/base/MathExpDoubling.mpws
==========
*CMD MathExpTaylor0 -- arbitrary precision partial sum of the Taylor series expansion of e^x around zero 
*CALL
    MathExpTaylor0(x)
    
*PARMS

{x} -- a real number, where $0 {\leq} x {\leq} 1$  

*DESC
    MathExpTaylor0 gives a decimal approximation of $e^{x}$ which is obtained by using 
    a partial sum of the Taylor series expansion around zero: $1 + x + \frac{x^2}{2!} + 
    \frac{x^3}{3!}{\cdots} = \sum_{n=0}^{\infty}\frac{x^n}{n!} $. The number of terms 
    used in the partial sum is determined by the built-in precision setting.

*E.G.
In> MathExpTaylor0(0)
Result: 1.0

In>  MathExpTaylor0(.2)
Result: 1.221402759

In>  MathExpTaylor0(1)
Result: 2.718281830

In> MathExpTaylor0(.13242)
Result: 1.141587685

*SEE  ExpN 


*SOURCE org/mathpiper/scripts4/base/MathExpTaylor0.mpws
==========
*CMD MathFloatPower --- *** UNDOCUMENTED ***

*CALL
        ?

*PARMS

?

*DESC

?


*SOURCE org/mathpiper/scripts4/base/MathFloatPower.mpws
==========
*CMD MathIntPower --- *** UNDOCUMENTED ***

*CALL
        ?

*PARMS

?

*DESC

?


*SOURCE org/mathpiper/scripts4/base/MathIntPower.mpws
==========
*CMD MathMul2Exp --- *** UNDOCUMENTED ***

*CALL
        ?

*PARMS

?

*DESC

?


*SOURCE org/mathpiper/scripts4/base/MathMul2Exp.mpws
==========
*CMD MathPi --- *** UNDOCUMENTED ***

*CALL
        ?

*PARMS

?

*DESC

?


*SOURCE org/mathpiper/scripts4/base/MathPi.mpws
==========
*CMD PositiveIntPower --- *** UNDOCUMENTED ***

*CALL
        ?

*PARMS

?

*DESC

?


*SOURCE org/mathpiper/scripts4/base/PositiveIntPower.mpws
==========
*CMD PowerN --- power x^y (arbitrary-precision math function)
*CALL
        PowerN(x,y)

*DESC

This command performs the calculation of an elementary mathematical
function.  The arguments <i>must</i> be numbers.  The reason for the
postfix {N} is that the library needs to define equivalent non-numerical
procedures for symbolic computations, such as {Exp}, {Sin}, etc.

Note that all xxxN procedures accept integers as well as floating-point numbers.
The resulting values may be integers or floats.  If the mathematical result is an
exact integer, then the integer is returned.  For example, {Sqrt(25)} returns
the integer {5}, and {Power(2,3)} returns the integer {8}.  In such cases, the
integer result is returned even if the calculation requires more digits than set by
{BuiltinPrecisionSet}.  However, when the result is mathematically not an integer,
the procedures return a floating-point result which is correct only to the current precision.

*EXAMPLES
In> BuiltinPrecisionSet(10) 
Result: 10

In> PowerN(2,3) 
Result: 8

In> PowerN(2,-3) 
Result: 0.125


*SOURCE org/mathpiper/scripts4/base/PowerN.mpws
==========
*CMD SinN --- sine (arbitrary-precision math function)
*CALL
        SinN(x)

*DESC

This command performs the calculation of an elementary mathematical
function.  The arguments <i>must</i> be numbers.  The reason for the
postfix {N} is that the library needs to define equivalent non-numerical
procedures for symbolic computations, such as {Exp}, {Sin}, etc.

Note that all xxxN procedures accept integers as well as floating-point numbers.
The resulting values may be integers or floats.  If the mathematical result is an
exact integer, then the integer is returned.  For example, {Sqrt(25)} returns
the integer {5}, and {Power(2,3)} returns the integer {8}.  In such cases, the
integer result is returned even if the calculation requires more digits than set by
{BuiltinPrecisionSet}.  However, when the result is mathematically not an integer,
the procedures return a floating-point result which is correct only to the current precision.

*E.G.
In>
Result:


*SOURCE org/mathpiper/scripts4/base/SineN.mpws
==========
*CMD TanN --- tangent (arbitrary-precision math function)
*CALL
        TanN(x)

*DESC

This command performs the calculation of an elementary mathematical
function.  The arguments <i>must</i> be numbers.  The reason for the
postfix {N} is that the library needs to define equivalent non-numerical
procedures for symbolic computations, such as {Exp}, {Sin}, etc.

Note that all xxxN procedures accept integers as well as floating-point numbers.
The resulting values may be integers or floats.  If the mathematical result is an
exact integer, then the integer is returned.  For example, {Sqrt(25)} returns
the integer {5}, and {Power(2,3)} returns the integer {8}.  In such cases, the
integer result is returned even if the calculation requires more digits than set by
{BuiltinPrecisionSet}.  However, when the result is mathematically not an integer,
the procedures return a floating-point result which is correct only to the current precision.

*E.G.
In>
Result:


*SOURCE org/mathpiper/scripts4/base/TangentN.mpws
==========
*CMD Trigonometry --- *** UNDOCUMENTED ***

*CALL
        ?

*PARMS

?

*DESC

?


*SOURCE org/mathpiper/scripts4/base/Trigonometry.mpws
==========
*CMD Combinations/BinomialCoefficient --- combinations/ binomial coefficient
*STD
*CALL
        Combinations(n, r)
        BinomialCoefficient(n, r)

*PARMS

{n} -- integer - total number of objects
{r} -- integer - number of objects chosen

*DESC

These procedures are actually two names for a single function.

In combinatorics, the procedure is thought of as being the number of ways
to choose "r" objects out of a total of "n" objects if order is
not taken into account.

In mathematics the procedure is called the binomial coefficient function
and it is thought of as the coefficient of the x^r term in the polynomial expansion
of the binomial power (1 + x)^n.

The binomial coefficient is defined to be zero
if "r" is negative or greater than "n"; {BinomialCoefficient(0,0)}=1.


*EXAMPLES
In> Combinations(10, 4) 
Result: 210

In> BinomialCoefficient(10, 4) 
Result: 210


*SEE CombinationsList, Permutations, PermutationsList, Eulerian

*SOURCE org/mathpiper/scripts4/combinatorics/Combinations.mpws
==========
*CMD PermutationsList --- return all permutations of a list
*STD
*CALL
        PermutationsList(list)

*PARMS

{list} -- a list of elements

*DESC

PermutationsList returns a list which contains all the permutations of
the elements in the original list.

*EXAMPLES
In> PermutationsList([_a,_b,_c]) 
Result: [[_a,_b,_c],[_a,_c,_b],[_c,_a,_b],[_b,_a,_c],[_b,_c,_a],[_c,_b,_a]]

*SEE Permutations, Combinations, CombinationsList, LeviCivita

*SOURCE org/mathpiper/scripts4/combinatorics/PermutationsList.mpws
==========
*CMD Arg --- argument of a complex number
*STD
*CALL
        Arg(x)

*PARMS

{x} -- argument to the procedure

*DESC

This procedure returns the argument of "x". The argument is the angle
with the positive real axis in the Argand diagram, or the angle
"phi" in the polar representation $r * Exp(I*phi)$ of "x". The
result is in the range [$-Pi$, $Pi$], that is, excluding $-Pi$ but including $Pi$. The
argument of 0 is {Undefined}.

*E.G.

In> Arg(2)
Result: 0;

In> Arg(-1)
Result: Pi;

In> Arg(1+I)
Result: Pi/4;

*SEE Abs, Sign

*SOURCE org/mathpiper/scripts4/complex/Arg.mpws
==========
*CMD Complex --- construct a complex number
*STD
*CALL
        Complex(r, c)

*PARMS

{r} -- real part

{c} -- imaginary part

*DESC

This procedure represents the complex number "r + I*c", where "I"
is the imaginary unit. It is the standard representation used in MathPiper
to represent complex numbers. Both "r" and "c" are supposed to be
real.

Note that, at the moment, many procedures in MathPiper assume that all
numbers are real unless it is obvious that it is a complex
number. Hence {Im(Sqrt(x))} evaluates to {0} which is only true for nonnegative "x".

*E.G.

In> I
Result: Complex(0,1);

In> 3+4*I
Result: Complex(3,4);

In> Complex(-2,0)
Result: -2;

*SEE Re, Im, I, Abs, Arg

*SOURCE org/mathpiper/scripts4/complex/Complex.mpws
==========
*CMD ComplexII? --- *** UNDOCUMENTED ***

*CALL
        ?

*PARMS

?

*DESC

?


*SOURCE org/mathpiper/scripts4/complex/ComplexII_.mpws
==========
*CMD Complex? --- *** UNDOCUMENTED ***

*CALL
        ?

*PARMS

?

*DESC

?


*SOURCE org/mathpiper/scripts4/complex/Complex_.mpws
==========
*CMD Conjugate --- complex conjugate
*STD
*CALL
        Conjugate(x)

*PARMS

{x} -- argument to the procedure

*DESC

This procedure returns the complex conjugate of "x". The complex
conjugate of $a + I*b$ is $a - I*b$. This procedure assumes that all
unbound variables are real.

*E.G.

In> Conjugate(2)
Result: 2;

In> Conjugate(Complex(3,5))
Result: Complex(3,-5);

*SEE Complex, Re, Im

*SOURCE org/mathpiper/scripts4/complex/Conjugate.mpws
==========
*CMD II --- *** UNDOCUMENTED ***

*CALL
        ?

*PARMS

?

*DESC

?


*SOURCE org/mathpiper/scripts4/complex/II.mpws
==========
*CMD Im --- imaginary part of a complex number
*STD
*CALL
        Im(x)

*PARMS

{x} -- argument to the procedure

*DESC

This procedure returns the imaginary part of the complex number "x".

*E.G.

In> Im(5)
Result: 0;

In> Im(I)
Result: 1;

In> Im(Complex(3,4))
Result: 4;

*SEE Complex, Re

*SOURCE org/mathpiper/scripts4/complex/Im.mpws
==========
*CMD ImII --- *** UNDOCUMENTED ***

*CALL
        ?

*PARMS

?

*DESC

?


*SOURCE org/mathpiper/scripts4/complex/ImII.mpws
==========
*CMD Magnitude --- *** UNDOCUMENTED ***

*CALL
        ?

*PARMS

?

*DESC

?


*SOURCE org/mathpiper/scripts4/complex/Magnitude.mpws
==========
*CMD NN --- *** UNDOCUMENTED ***

*CALL
        ?

*PARMS

?

*DESC

?


*SOURCE org/mathpiper/scripts4/complex/NN.mpws
==========
*CMD Re --- real part of a complex number
*STD
*CALL
        Re(x)

*PARMS

{x} -- argument to the procedure

*DESC

This procedure returns the real part of the complex number "x".

*E.G.

In> Re(5)
Result: 5;

In> Re(I)
Result: 0;

In> Re(Complex(3,4))
Result: 3;

*SEE Complex, Im

*SOURCE org/mathpiper/scripts4/complex/Re.mpws
==========
*CMD ReII --- *** UNDOCUMENTED ***

*CALL
        ?

*PARMS

?

*DESC

?


*SOURCE org/mathpiper/scripts4/complex/ReII.mpws
==========
*CMD I --- imaginary unit
*STD
*CALL
        I

*DESC

This symbol represents the imaginary unit, which equals the square
root of -1. It evaluates to {Complex(0,1)}.

*E.G.

In> I
Result: Complex(0,1);

In> I = Sqrt(-1)
Result: True;

*SEE Complex

*SOURCE org/mathpiper/scripts4/constants/constants.mpws
==========
*CMD Pi --- mathematical constant $pi$

*STD
*CALL
        Pi

*DESC

Pi symbolically represents the exact value of $pi$. When the {NM()} procedure is
used, {Pi} evaluates to a numerical value according to the current precision.
It is better to use {Pi} than {NM(Pi)} except in numerical calculations, because exact
simplification will be possible.

This is a "cached constant" which is recalculated only when precision is increased.

*E.G.

In> Pi+1
Result: Pi+1;

In> NM(Pi+1);
Result: 4.141592654

In> NM(Pi,40)
Result: 3.141592653589793238462643383279502884197

In> Pin :=NM(Pi)
Result: 3.141592654

In> Sin(3*Pi/2)
Result: Sin((3*Pi)/2)

In> SinD(3*Pin/2)
Result: -1.0



*SEE Sin, Cos, NM, CachedConstant

*SOURCE org/mathpiper/scripts4/constants/constants.mpws
==========
*CMD GoldenRatio --- the Golden Ratio
*STD
*CALL
        GoldenRatio

*DESC

These procedures compute the "golden ratio"
$$phi <=> 1.6180339887 <=> (1+Sqrt(5))/2 $$.

The ancient Greeks defined the "golden ratio" as follows:
If one divides a length 1 into two pieces $x$ and $1-x$, such that the ratio of 1 
to $x$ is the same as the ratio of $x$ to $1-x$, then $1/x <=> 1.618$... is the "golden ratio".


The constant is available symbolically as {GoldenRatio} or numerically through {NM(GoldenRatio)}.
This is a "cached constant" which is recalculated only when precision is increased.
The numerical value of the constant can also be obtained as {NM(GoldenRatio)}.


*E.G.

In> x:=GoldenRatio - 1
Result: GoldenRatio-1;

In> NM(x)
Result: 0.6180339887;

In> NM(1/GoldenRatio)
Result: 0.6180339887;

In> Verbose(NM(GoldenRatio,20));

        CachedConstant: Info: constant GoldenRatio is
        being recalculated at precision 20 
Result: 1.6180339887498948482;


*SEE NM, CachedConstant

*SOURCE org/mathpiper/scripts4/constants/constants.mpws
==========
*CMD Catalan --- Catalans Constant
*STD
*CALL
        Catalan

*DESC

These procedures compute Catalans Constant $Catalan<=>0.9159655941$.

The constant is available symbolically as {Catalan} or numerically through {NM(Catalan)} with {NM(...)} the usual operator used to try to coerce an expression in to a numeric approximation of that expression.
This is a "cached constant" which is recalculated only when precision is increased.
The numerical value of the constant can also be obtained as {NM(Catalan)}.
The low-level numerical computations are performed by the routine {CatalanConstNum}.


*E.G.

In> NM(Catalan)
Result: 0.9159655941;

In> DirichletBeta(2)
Result: Catalan;

In> Verbose(NM(Catalan,20))

        CachedConstant: Info: constant Catalan is
        being recalculated at precision 20
Result: 0.91596559417721901505;


*SEE NM, CachedConstant

*SOURCE org/mathpiper/scripts4/constants/constants.mpws
==========
*CMD gamma --- Eulers constant $gamma$
*STD
*CALL
        gamma

*DESC

These procedures compute Eulers constant $gamma<=>0.57722$...

The constant is available symbolically as {gamma} or numerically through using the usual procedure {NM(...)} to get a numeric result, {NM(gamma)}.
This is a "cached constant" which is recalculated only when precision is increased.
The numerical value of the constant can also be obtained as {NM(gamma)}.
The low-level numerical computations are performed by the routine {GammaConstNum}.

Note that Eulers Gamma function $Gamma(x)$ is the capitalized {Gamma} in MathPiper.

*E.G.

In> gamma+Pi
Result: gamma+Pi;

In> NM(gamma+Pi)
Result: 3.7188083184;

In> Verbose(NM(gamma,20))
        
        CachedConstant: Info: constant gamma is being
          recalculated at precision 20 
        GammaConstNum: Info: used 56 iterations at
          working precision 24 
Result: 0.57721566490153286061;

*SEE Gamma, NM, CachedConstant

*SOURCE org/mathpiper/scripts4/constants/constants.mpws
==========
*CMD CachedConstant --- precompute multiple-precision constants
*STD
*CALL
        CachedConstant(cache, Cname, Cfunc)

*PARMS
{cache} -- atom, name of the cache

{Cname} -- atom, name of the constant

{Cfunc} -- expression that evaluates the constant

*DESC

This procedure is used to create precomputed multiple-precision values of
constants. Caching these values will save time if they are frequently used.

The call to {CachedConstant} defines a new function named {Cname()} that
returns the value of the constant at given precision. If the precision is
changed, the value will be recalculated as necessary, otherwise calling {Cname()} will take very little time.

The parameter {Cfunc} must be an expression that can be evaluated and returns
the value of the desired constant at the current precision. (Most arbitrary-precision mathematical procedures do this by default.)

The associative list {cache} contains elements of the form {[Cname, prec, value]}, as illustrated in the example. If this list does not exist, it will be created.

This mechanism is currently used by {NM()} to precompute the values of $Pi$ and $gamma$ (and the golden ratio through {GoldenRatio}, and {Catalan}).
The name of the cache for {NM()} is {CacheOfConstantsN}.
The code in the procedure {NM()} assigns unevaluated calls to {InternalPi()} and {Internalgamma()} to the atoms {Pi} and {gamma} and declares them to be lazy global variables through {AssignGlobalLazy} (with equivalent procedures assigned to other constants that are added to the list of cached constants).

The result is that the constants will be recalculated only when they are used in the expression under {NM()}.
In other words, the code in {NM()} does the equivalent of

        AssignGlobalLazy(mypi,Hold(InternalPi()));
        AssignGlobalLazy(mygamma,Hold(Internalgamma()));

After this, evaluating an expression such as {1/2+gamma} will call the procedure {Internalgamma()} but not the procedure {InternalPi()}.

*E.G. notest

In> CachedConstant( mycache, Ln2, InternalLnNum(2) )
Result: True;

In> InternalLn2()
Result: 0.6931471806;

In> Verbose(NM(InternalLn2(),20))
        CachedConstant: Info: constant Ln2 is being
          recalculated at precision 20 
Result: 0.69314718055994530942;

In> mycache
Result: [["Ln2",20,0.69314718055994530942]];


*SEE NM, BuiltinPrecisionSet, Pi, GoldenRatio, Catalan, gamma

*SOURCE org/mathpiper/scripts4/constants/constants.mpws
==========
*CMD Else --- used with the If procedure to make decisions

*CALL
    If(predicate) body Else otherwise

*PARMS

{predicate} -- predicate to test

{body} -- expression to evaluate if the predicate is {True}.

{otherwise} -- expression to evaluate if the predicate if {False}.

*DESC

An If() procedure can be used with an Else operator to evaluate one body 
if a predicate expression is True, and an alternative body if the predicate 
expression is False.

*E.G.
/%mathpiper

x := 4;

If(x >? 5)
{
    Echo(x,"is greater than 5.");
}
Else
{
    Echo(x,"is NOT greater than 5.");
}

Echo("End of program.");

/%/mathpiper

    /%output,preserve="false"
      Result: True
      
      Side Effects:
      4 is NOT greater than 5.
      End of program.
    /%/output

*SEE If, Decide

*SOURCE org/mathpiper/scripts4/contolflow/Else.mpws
==========
*CMD ForEach --- loop over all entries in a list or a string
*STD
*CALL
        ForEach(var, sequence) body

*PARMS

{var} -- looping variable

{sequence} -- a list, string, or code sequence

{body} -- expression to evaluate with different values of "var"

*DESC

The expression "body" is evaluated multiple times. The first time,
"var" has the value of the first element of the sequence, then it gets
the value of the second element, and so on.

*E.G. notest

In> ForEach(i,[2,3,5,7,11]) Echo([i, i!]);
2  2
3  6
5  120
7  5040
11  39916800
Result: True;


In> ForEach(i,"Hello") Echo(i)
Result: True
Side Effects:
H
e
l
l
o

In> ForEach(expression, '{1+1;2+2;}) {Echo(expression);}
Result: True
Side Effects:
1 + 1 
2 + 2

*SEE For, While, DoWhile, Break, Continue

*SOURCE org/mathpiper/scripts4/contolflow/ForEach.mpws
==========
*CMD Lambda --- a form of pure procedure that can be passed to procedures like Apply and Select
*STD
*CALL
        Lambda(arglist, procedure body)

*PARMS

{arglist} -- list of arguments

*DESC

Lambda procedures are unnamed pure procedures which can be used in places where a small procedure
is needed and creating a normal procedure is either inconvenient or impossible.

*E.G.
In>  Apply(Lambda([x,y], x-y^2), [Cos(_a), Sin(_a)]);
Result: Cos(_a)-Sin(_a)^2


/%mathpiper

list := [1,-3,2,-6,-4,3];

Select(list, Lambda([i], i >? 0 ));

/%/mathpiper

    /%output,preserve="false"
      Result: [1,2,3]
.   /%/output

*SEE Apply, @, Select

*SOURCE org/mathpiper/scripts4/contolflow/Lambda.mpws
==========
*CMD Verbose, Verbose? --- set verbose output mode
*STD
*CALL
        Verbose(expression)
        Verbose?()

*PARMS

[expression] -- expression to be evaluated in verbose mode

*DESC

The procedure {Verbose(expression)} will evaluate the expression in
verbose mode. Various parts of MathPiper can show extra information
about the work done while doing a calculation when using {Verbose}.

In verbose mode, {Verbose?()} will return {True}, otherwise
it will return {False}.

VerboseOn() turns verbose mode on, and VerboseOff() turns verbose mode off.

*E.G. notest

In> OldSolve([x+2==0],[x])
Result: [[-2]];

In> Verbose(OldSolve([x+2==0],[x]))
        Entering OldSolve
        From  x+2==0  it follows that  x  = -2
           x+2==0  simplifies to  True
        Leaving OldSolve
Result: [[-2]];

In> Verbose?()
Result: False

In> Verbose(Verbose?())
Result: True

*SEE Echo, NM

*SOURCE org/mathpiper/scripts4/debug/verbose_mode.mpws
==========
*CMD AssignArray --- auxiliary procedure to help assign arrays using :=

*CALL
        AssignArray(listOrAssociationList, indexOrKey, newValue);

*PARMS

{listOrAssociationList} -- a list or an association list

{indexOrKey} -- an index or a string which is a key

{newValue} -- the new value to place into the list or the association list


*DESC
This procedure will destructively change a list, an association list, or a
Generic object.



*E.G.
// Change a normal list.
In> list := [7,8,9]
Result> [7,8,9]

In> AssignArray(list, 2, "eight")
Result> True

In> list
Result> [7,"eight",9]



// Change an association list.
In> list := [["seven", 7], ["eight", 8], ["nine", 9]]
Result> [["seven",7],["eight",8],["nine",9]]

In> AssignArray(list, "eight", "EIGHT")
Result> True

In> list
Result> [["seven",7],["eight","EIGHT"],["nine",9]]



// Add an association to an association list.
In> list := [["seven", 7], ["eight", 8], ["nine", 9]]
Result> [["seven",7],["eight",8],["nine",9]]

In> AssignArray(list, "ten", 10)
Result> True

In> list
Result> [["ten",10],["seven",7],["eight",8],["nine",9]]

*SEE :=

*SOURCE org/mathpiper/scripts4/define/AssignArray.mpws
==========
*CMD Function --- declare or define a procedure
*CALL
        Defun(procedure, args) body

*PARMS

{procedure} -- A procedure name

{[arglist]} -- list of atoms, formal arguments to the procedure

{body} -- expression comprising the body of the procedure

*DESC

Defun procedure.

*E.G. notest

In>


*SOURCE org/mathpiper/scripts4/define/Defun.mpws
==========
*CMD HoldArgumentNumber --- specify argument as not evaluated
*STD
*CALL
        HoldArgumentNumber("procedure", arity, argNum)

*PARMS
{"procedure"} -- string, procedure name

{arity}, {argNum} -- positive integers

*DESC

Declares the argument numbered {argNum} of the procedure named {"procedure"} with
specified {arity} to be unevaluated ("held"). Useful if you don't know symbolic
names of parameters, for instance, when the procedure was not defined using an
explicit {RulebaseHoldArguments} call. Otherwise you could use {HoldArgument}.
  
Note that defining rules with the {-->} operator can also result
in a rulebase with the implied arity being defined. Therefore,
{HoldArgument} should be placed after all rule definitions if all possible
rulebases are not defined by {Rulebase} procedures.

*SEE HoldArgument, RulebaseHoldArguments

*SOURCE org/mathpiper/scripts4/define/HoldArgumentNumber.mpws
==========
*CMD Macro --- declare or define a macro
*STD
*CALL
        Macro() func(arglist)
        Macro() func(arglist, ...)
        Macro("op", [arglist]) body
        Macro("op", [arglist, ...]) body

*PARMS

{func(args)} -- procedure declaration, e.g. {f(x,y)}

{"op"} -- string, name of the procedure

{{arglist}} -- list of atoms, formal arguments to the procedure

{...} -- literal ellipsis symbol "{...}" used to denote a variable number of arguments

{body} -- expression comprising the body of the procedure

*DESC

This does the same as {Function}, but for macros. One can define a macro
easily with this procedure, in stead of having to use {MacroRulebaseHoldArguments}.

*E.G. notest

the following example defines a looping procedure.

In> Macro("myfor",["init", "pred", "inc", "body"]) [@init,While(@pred)[@body,@inc,],True];
Result: True;

In> a:=10
Result: 10;

Here this new macro [myfor] is used to loop, using a variable [a] from the
calling environment.

In> myfor(i:=1,i<?10,i++,Echo(a*i))
        10 
        20 
        30 
        40 
        50 
        60 
        70 
        80 
        90 
Result: True;

In> i
Result: 10;

*SEE Procedure, MacroRulebaseHoldArguments

*SOURCE org/mathpiper/scripts4/define/Macro.mpws
==========
*CMD Function --- declare or define a procedure
*STD
*CALL
        Procedure() procedure(arglist)
        Procedure() procedure(arglist, ...)
        Procedure("name", [arglist]) body
        Procedure("name", [arglist, ...]) body

*PARMS

{func(args)} -- procedure declaration, e.g. {f(x,y)}

{"name"} -- string, name of the procedure

{[arglist]} -- list of atoms, formal arguments to the procedure

{...} -- literal ellipsis symbol "{...}" used to denote a variable number of arguments

{body} -- expression comprising the body of the procedure

*DESC

This command can be used to define a new procedure with named arguments.


The number of arguments of the new procedure and their names are determined 
by the list {arglist}. If the ellipsis "{...}" follows the last atom in 
{arglist}, a procedure with a variable number of arguments is declared 
(using {RulebaseListedHoldArguments}). Note that the ellipsis cannot be 
the only element of {arglist} and <i>must</i> be preceded by an atom.

A procedure with variable number of arguments can take more arguments than 
elements in {arglist} in this case, it obtains its last argument as a list 
containing all extra arguments.

The short form of the {Procedure} call merely declares a {RulebaseHoldArguments} 
for the new procedure but does not define any procedure body. This is a convenient 
shorthand for {RulebaseHoldArguments} and {RulebaseListedHoldArguments}, when 
definitions of the procedure are to be supplied by rules. If the new procedure 
has been already declared with the same number of arguments (with or without 
variable arguments), {Procedure} returns false and does nothing.

The second, longer form of the {Procedure} call declares a procedure and also 
defines a procedure body. It is equivalent to a
single rule such as {op(arg1_, arg2_) --> body}. The rule will be declared at
precedence 1025. Any previous rules associated with {"op"} (with the same
arity) will be discarded. More complicated procedures (with more than one body)
can be defined by adding more rules.

*E.G. notest

This will declare a new procedure with two or more arguments, but define no rules for it. This is equivalent to [Rulebase ("f1", [x, y, ...])].

In> Procedure() f1("x", "y",...);
Result: True

In> f1(3,4,5,[1,2,3])
Result: f1(3,[4,5,[1,2,3]])

In> Procedure() f1("x", "y");
Result: False;

This defines a procedure FirstOf which returns the
first element of a list. Equivalent definitions would be
FirstOf(list_) --> list[1] or FirstOf(list) := list[1].
In> Procedure("FirstOf", ["list"])  list[1];
Result: True;

In> FirstOf([_a,_b,_c]);
Result: _a;

The following procedure will print all arguments to a string:

In> Procedure("PrintAll",["x", ...]) Decide(List?(x),
          PrintList(x), PipeToString()Write(x));
Result: True;

In> PrintAll(1):
Result: "1";

In> PrintAll(1,2,3);
Result: "1 2 3";

*SEE TemplateProcedure, RuleHoldArguments, RulebaseHoldArguments,  RulebaseListedHoldArguments, :=, Retract

*SOURCE org/mathpiper/scripts4/define/Procedure.mpws
==========
*CMD TemplateProcedure --- defines a procedure
*CALL
        TemplateProcedure(operator, parameters)

*PARMS
{operator} -- string, name of a procedure

{parameters} -- list of strings that are names of parameters

*DESC
Defines a procedure.

*E.G.
/%mathpiper
TemplateProcedure("MyUntil",["predicate", "body"])
{
    Eval(body);
    While (Equal?(Eval(predicate),False))
    {
        Eval(body);
    }
    True;
}

UnFence("MyUntil",2);
HoldArgumentNumber("MyUntil",2,1);
HoldArgumentNumber("MyUntil",2,2);
Bodied("MyUntil",60000);


x := 1;

MyUntil(x =? 5)
{
    Echo(x);
    x++;
}

/%/mathpiper

    /%output,mpversion=".234",preserve="false"
      Result: True
      
      Side Effects:
      1 
      2 
      3 
      4 

.   /%/output

*SOURCE org/mathpiper/scripts4/define/TemplateFunction.mpws
==========
*CMD Unholdable --- make a variable unholdable

*CALL
    Unholdable(var)

*PARMS

{var} -- a variable

*DESC
This procedure makes a variable unholdable.  It is used to make sure that an :=
operator with an Eval() immediately to its right hand side evaluates its argument.

*SOURCE org/mathpiper/scripts4/define/Unholdable.mpws
==========
*CMD := --- assign a variable or a list; define a procedure
*STD
*CALL
        var := expr
        [var1, var2, ...] := [expr1, expr2, ...]
        var[i] := expr
        fn(arg1, arg2, ...) := expr

*PARMS

{var} -- atom, variable which should be assigned

{expr} -- expression to assign to the variable or body of procedure

{i} -- index (can be integer or string)

{fn} -- atom, name of a new procedure to define

{arg1}, {arg2} -- atoms, names of arguments of the new procedure {fn}

*DESC

The {:=} operator can be used
in a number of ways. In all cases, some sort of assignment or definition takes
place.

The listOrAssociationList form is the most basic one. It evaluates the expression on
the right-hand side and assigns it to the variable named on the
left-hand side. The left-hand side is not evaluated. The evaluated
expression is also returned.

The indexOrKey form is a small extension, which allows one to do multiple
assignments. The listOrAssociationList entry in the list on the right-hand side is
assigned to the listOrAssociationList variable mentioned in the left-hand side, the
indexOrKey entry on the right-hand side to the indexOrKey variable on the
left-hand side, etc. The list on the right-hand side must have at
least as many entries as the list on the left-hand side. Any excess
entries are silently ignored. The result of the expression is the list
of values that have been assigned.

The third form allows one to change an entry in the list. If the index
"i" is an integer, the "i"-th entry in the list is changed to the
expression on the right-hand side. It is assumed that the length of
the list is at least "i". If the index "i" is a string, then
"var" is considered to be an associative list (sometimes called hash
table), and the key "i" is paired with the value "exp". In both
cases, the right-hand side is evaluated before the assignment and the
result of the assignment is {True}.

The last form defines a procedure. For example, the assignment {fn(x) := x^2}
removes any rules previously associated with {fn(x)} and defines the rule
{fn(x_) --> x^2}. Note that the left-hand side may take a different form if
{fn} is defined to be a prefix, infix or bodied procedure. This case
is special since the right-hand side is not evaluated
immediately, but only when the procedure {fn} is used. If this takes
time, it may be better to force an immediate evaluation with {Eval}
(see the last example). If the expression on the right hand side begins
with {Eval()}, then it <i>will</i> be evaluated before defining the new procedure.

A variant of the procedure definition can be used to make a procedure
accepting a variable number of arguments.

*E.G.

A simple assignment:

In> a := Sin(_x) + 3;
Result: Sin(_x)+3;

In> a;
Result: Sin(_x)+3;

Multiple assignments:

In> [_a,_b,_c] := [1,2,3];
Result: [1,2,3];

In> a;
Result: 1;

In> b+c;
Result: 5;

Assignment to a list:

In> xs := [ 1,2,3,4,5 ];
Result: [1,2,3,4,5];

In> xs[3] := 15;
Result: True;

In> xs;
Result: [1,2,15,4,5];

Building an associative list:

In> alist := [];
Result: [];

In> alist["cherry"] := "red";
Result: True;

In> alist["banana"] := "yellow";
Result: True;

In> alist["cherry"];
Result: "red";

In> alist;
Result: [["banana","yellow"],["cherry","red"]];

Defining a procedure:

In> f(x) := x^2;
Result: True;

In> f(3);
Result: 9;

In> f(Sin(_a));
Result: Sin(_a)^2;

Defining a procedure with variable number of arguments:

In> f(x, ...) := Decide(List?(x),Sum(x),x);
Result: True;

In> f(2);
Result: 2;

In> f(1,2,3);
Result: 6;

Defining a new infix operator:

In> Infix("*&*",10);
Result: True;

In> _x1 *&* _x2 := _x1/_x2 + _x2/_x1;
Result: True;

In>Sin(_a) *&* Cos(_a);
Result: Sin(_a)/Cos(_a)+Cos(_a)/Sin(_a)

PKHG12-11-13 TODO
In> Sin(_a) *&* Cos(_a)
Result: Sin(_a)/Cos(_a)+Cos(_a)/Sin(_a)

In>  Sin(_a) *&* CosN(NM(Pi));
Result: -(1.000000000/Sin(_a)+Sin(_a))

In> Unassign(a);
Result: True;

In> Sin(_a) *&* Exp(_a);
Result: Sin(_a)/Exp(_a)+Exp(_a)/Sin(_a)

In the following example, it may take some time to compute the Taylor
expansion. This has to be done every time the procedure [f] is called.

PKHG12-11-13 TODO!
In> f(a) := Taylor(x,0,25) Sin(x);
Result: True;

In> f(1);
Result: x-x^3/6+x^5/120-x^7/5040+x^9/362880-
x^11/39916800+x^13/6227020800-x^15/
1307674368000+x^17/355687428096000-x^19/
121645100408832000+x^21/51090942171709440000
-x^23/25852016738884976640000+x^25
/15511210043330985984000000;

In> f(2);
Result: x-x^3/6+x^5/120-x^7/5040+x^9/362880-
x^11/39916800+x^13/6227020800-x^15
/1307674368000+x^17/355687428096000-x^19/
121645100408832000+x^21/51090942171709440000
-x^23/25852016738884976640000+x^25/
15511210043330985984000000;

The remedy is to evaluate the Taylor expansion immediately. Now the
expansion is computed only once.

In> f(a) := Eval(Taylor(_x,0,25) Sin(_x));
Result: True;

In> f(1);
Result: x-x^3/6+x^5/120-x^7/5040+x^9/362880-
x^11/39916800+x^13/6227020800-x^15/
1307674368000+x^17/355687428096000-x^19/
121645100408832000+x^21/51090942171709440000
-x^23/25852016738884976640000+x^25
/15511210043330985984000000;

In> f(2);
Result: x-x^3/6+x^5/120-x^7/5040+x^9/362880-
x^11/39916800+x^13/6227020800-x^15
/1307674368000+x^17/355687428096000-x^19/
121645100408832000+x^21/51090942171709440000
-x^23/25852016738884976640000+x^25/
15511210043330985984000000;

*SEE -->, Assign, Unassign, RuleHoldArguments, Infix, Eval, Procedure

*SOURCE org/mathpiper/scripts4/define/colon_equals_operator.mpws
==========
*CMD ResistorPowerRating --- determine a standard resistor power rating

*CALL
	ResistorPowerRating(value)

*PARMS

{value} -- the required power dissipation of a resistor

*DESC
A standard practice for selecting a resistor for a given application is 
to choose a power rating that is twice the resistor's power dissipation 
requirements. The standard resistor power ratings (in watts) are:

1/8, 1/4, 1/2, 1, 2, 3, 5, 7, 10, 15

This procedure returns the closest standard power rating that is greater
than or equal to twice the resistor's required power dissipation.

*EXAMPLES
In> ResistorPowerRating(7`W) 
Result: 15`W


*SOURCE org/mathpiper/scripts4/electronics/ResistorPowerRating.mpws
==========
*CMD || --- relates parts of circuits that are parallel to each other
*CALL
        R1 || R2

*DESC

Relates parts of circuits that are parallel to each other.

*E.G.
In>
Result:

*SEE ~~


*SOURCE org/mathpiper/scripts4/electronics/bar_bar_operator.mpws
==========
*CMD ColorsToOhms --- convert resistor color code colors to a value

*CALL
        ColorsToOhms(colors)

*PARMS

{colors} -- a list of resistor color code colors

*DESC

This procedure will convert 3-band, 4-band, and 5-band resistor color 
code colors to a value.

*EXAMPLES
In> ColorsToOhms([Orange, Blue, Gold]) 
Result: [3.6`Ω,20`%,2.88`Ω,4.32`Ω]

In> ColorsToOhms([Brown, Blue, Green, Silver]) 
Result: [1600000`Ω,10`%,1440000`Ω,1760000`Ω]

In> ColorsToOhms([Orange, Blue, Gold, Red]) 
Result: [3.6`Ω,2`%,3.528`Ω,3.672`Ω]

In> ColorsToOhms([Red, Green, Blue, Brown, Gold]) 
Result: [2560`Ω,5`%,2432`Ω,2688`Ω]

*SEE OhmsToColors

*SOURCE org/mathpiper/scripts4/electronics/resistor_color_bands/ColorsToOhms.mpws
==========
*CMD NumberToResistorColor --- convert a number to a resistor color code color

*CALL
        NumberToResistorColor(number)

*PARMS

{number} -- a number

*DESC

This procedure converts a number to a resistor color.

*EXAMPLES
In> NumberToResistorColor(2) 
Result: Red

*SEE ResistorColorToNumber

*SOURCE org/mathpiper/scripts4/electronics/resistor_color_bands/NumberToResistorColor.mpws
==========
*CMD NumberToResistorToleranceColor --- convert a tolerance number to a resistor color code color

*CALL
        NumberToResistorToleranceColor(number)

*PARMS

{number} -- a resistor tolerance number

*DESC

This procedure converts a tolerance number to a resistor color code color.

*EXAMPLES
In> NumberToResistorToleranceColor(.02) 
Result: Red

*SEE ResistorToleranceColorToNumber

*SOURCE org/mathpiper/scripts4/electronics/resistor_color_bands/NumberToResistorToleranceColor.mpws
==========
*CMD OhmsToColors --- convert a resistor value to the 4 color resistor code

*CALL
        OhmsToColors(value)

*PARMS

{value} -- the resistor value with a unit of Ω

*DESC

This procedure converts a resistor value to the 4 color
resistor code. The tolerance of the value is not specified.

*EXAMPLES
In> OhmsToColors(35`kΩ) 
Result: [Orange,Green,Orange]

*SEE ColorsToOhms

*SOURCE org/mathpiper/scripts4/electronics/resistor_color_bands/OhmsToColors.mpws
==========
*CMD ResistorColorToNumber --- convert a resistor color code color to its analogous number

*CALL
        ResistorColorToNumber(color)

*PARMS

{color} -- a resistor color code color


*DESC

This procedure converts a resistor color code color to its analogous number.

*EXAMPLES
In> ResistorColorToNumber(Red) 
Result: 2

*SEE NumberToResistorColor

*SOURCE org/mathpiper/scripts4/electronics/resistor_color_bands/ResistorColorToNumber.mpws
==========
*CMD ResistorToleranceColorToNumber --- convert a resistor color code color to a tolerance number

*CALL
        ResistorToleranceColorToNumber(color)

*PARMS

{color} -- a resistor color code color

*DESC

This procedure converts a resistor color code color to a tolerance number.

*EXAMPLES
In> ResistorToleranceColorToNumber(Red) 
Result: .02

*SEE NumberToResistorToleranceColor

*SOURCE org/mathpiper/scripts4/electronics/resistor_color_bands/ResistorToleranceColorToNumber.mpws
==========
*CMD ~~ --- relates parts of circuits that are in series
*CALL
        R1 ~~ R2

*DESC

Relates parts of circuits that are in series.

*E.G.
In>
Result:

*SEE ||


*SOURCE org/mathpiper/scripts4/electronics/tilda_tilda_operator.mpws
==========
*CMD EquationLeft --- return the left side of a symbolic equation
*STD
*CALL
        EquationLeft(equation)
        
*PARMS

{equation} -- symbolic equation.


*DESC

A symbolic equation is an equation which is defined using the == operator.  This
procedure returns the left side of a symbolic equation.

*E.G.


In> equ := y^2 == 4*p*x
Result: y^2==4*p*x


In> EquationLeft(equ)
Result: y^2

*SEE ==, EquationRight

*SOURCE org/mathpiper/scripts4/equations/EquationLeft.mpws
==========
*CMD EquationRight --- return the right side of a symbolic equation
*STD
*CALL
        EquationRight(equation)
        
*PARMS

{equation} -- symbolic equation.


*DESC

A symbolic equation is an equation which is defined using the == operator.  This
procedure returns the right side of a symbolic equation.

*E.G.


In> equ := y^2 == 4*p*x
Result: y^2==4*p*x


In> EquationRight(equ)
Result: 4*p*x

*SEE ==, EquationLeft

*SOURCE org/mathpiper/scripts4/equations/EquationRight.mpws
==========
*CMD Assert --- signal "soft" custom error
*STD
*CALL
        Assert("str", expr) pred
        Assert("str") pred
        Assert() pred

*PARMS

{pred} -- predicate to check

{"str"} -- string to classify the error

{expr} -- expression, error object

*DESC

{Assert} is a global error reporting mechanism. It can be used to check for
errors and report them. An error is considered to occur when the predicate
{pred} evaluates to anything except {True}. In this case, the procedure returns
{False} and an error object is created and posted to the global error tableau.
Otherwise the procedure returns {True}.

Unlike the "hard" error procedure {Check}, the procedure {Assert} does not stop
the execution of the program.

The error object consists of the string {"str"} and an arbitrary
expression {expr}. The string should be used to classify the kind of error that
has occurred, for example "domain" or "format". The error object can be any 
expression that might be useful for handling the error later;
for example, a list of erroneous values and explanations.
The association list of error objects is currently obtainable through
the procedure {GetErrorTableau()}.

If the parameter {expr} is missing, {Assert} substitutes {True}. If both 
optional parameters {"str"} and {expr} are missing, {Assert} creates an error of class {"generic"}.

Errors can be handled by a
custom error handler in the portion of the code that is able to handle a certain class of
errors. The procedures {Error?}, {GetError} and {ClearError} can be used.

Normally, all errors posted to the error tableau during evaluation of an expression should
be eventually printed to the screen. This is the behavior of unparsers
{DefaultPrint}, {Print}, {UnparseMath2D} and {UnparseLatex} (but not of the
inline unparser, which is enabled by default); they call
{DumpErrors} after evaluating the expression.

*E.G.

In> Assert("bad value", "must be zero") 1=0
Result: False;

In> Assert("bad value", "must be one") 1=1
Result: True;

In> Error?()
Result: True;

In> Error?("bad value")
Result: True;

In> Error?("bad file")
Result: False;

In> GetError("bad value");
Result: "must be zero";

In> DumpErrors()
        Error: bad value: must be zero
Result: True;
No more errors left:

In> Error?()
Result: False;

In> DumpErrors()
Result: True;

*SEE Error?, DumpErrors, Check, GetError, ClearError, ClearErrors, GetErrorTableau


*SOURCE org/mathpiper/scripts4/io/Assert.mpws
==========
*CMD DumpErrors --- simple error handlers
*STD
*CALL
        DumpErrors()

*DESC

{DumpErrors} is a simple error handler for the global error reporting mechanism. 
It prints all errors posted using {Assert} and clears the error tableau.

*SEE Assert, Error?, ClearErrors


*SOURCE org/mathpiper/scripts4/io/DumpErrors.mpws
==========
*CMD Echo --- high-level printing routine
*STD
*CALL
        Echo(item,item,item,...)

*PARMS

{item} -- the items to be printed


*DESC

If passed a single item, {Echo} will evaluate it and print it to the
current output, followed by a newline. If {item} is a string, it is
printed without quotation marks.

If {Echo} is called with a variable number of arguments, they will all
be printed and finally a newline will be printed.

If no arguments are passed to {Echo}, it will simply output a newline.

{Echo} always returns {True}.

*E.G.
In> Echo(5+3);
Result: True
Side Effects:
8 


In> Echo("The square of two is ", 2*2);
Result: True
Side Effects:
The square of two is 4 


In> Echo([_a,NM(Pi),[1,2,"PKHG"]]);
Result: True
Side Effects:
[_a,3.141592654,[1,2,"PKHG"]] 

*SEE UnparseMath2D, Write, WriteString, RulebaseListedHoldArguments

*SOURCE org/mathpiper/scripts4/io/Echo.mpws
==========
*CMD EchoTime --- measure the time taken by a procedure and echos it
*CALL
        EchoTime()expr
*PARMS
{expr} -- any expression

*DESC

The procedure {EchoTime()expr} evaluates the expression {expr} and prints the time in seconds needed for the evaluation.
The time is printed to the current output stream.
The built-in procedure {Time} is used for timing.

The result is the "user time" as reported by the OS, not the real ("wall clock") time.
Therefore, any CPU-intensive processes running alongside MathPiper will not significantly affect the result of {EchoTime}.

*E.G.

In> EchoTime() NM(Ln(1000),40)
Result: 6.907755278982137052053974364053092622803
Side Effects:
0.756 seconds taken.

*SEE Time

*SOURCE org/mathpiper/scripts4/io/EchoTime.mpws
==========
*CMD Error? --- check for custom error
*STD
*CALL
        Error?()
        Error?("str")

*PARMS

{"str"} -- string to classify the error

*DESC

{Error?()} returns {True} if any custom errors have been reported using {Assert}.
The second form takes a parameter {"str"} that designates the class of the
error we are interested in. It returns {True} if any errors of the given class
{"str"} have been reported.

*SEE GetError, ClearError, Assert, Check


*SOURCE org/mathpiper/scripts4/io/Error_.mpws
==========
*CMD ClearErrors --- simple error handlers
*STD
*CALL
        ClearErrors()

*DESC

{ClearErrors} is a trivial error handler that does nothing except it clears the tableau.

*SEE Assert, Error?, DumpErrors


*SOURCE org/mathpiper/scripts4/io/GetErrorTableau.mpws
==========
*CMD GetError --- custom errors handlers
*CMD ClearError --- custom errors handlers
*CMD GetErrorTableau --- custom errors handlers
*STD
*CALL
        GetError("str")
        ClearError("str")
        GetErrorTableau()

*PARMS

{"str"} -- string to classify the error

*DESC

These procedures can be used to create a custom error handler.

{GetError} returns the error object if a custom error of class {"str"} has been
reported using {Assert}, or {False} if no errors of this class have been
reported.

{ClearError("str")} deletes the same error object that is returned by
{GetError("str")}. It deletes at most one error object. It returns {True} if an
object was found and deleted, and {False} otherwise.

{GetErrorTableau()} returns the entire association list of currently reported errors.

*E.G.

In> x:=1
Result: 1;

In> Assert("bad value", [x,"must be zero"]) x=0
Result: False;

In> GetError("bad value")
Result: [1, "must be zero"];

In> ClearError("bad value");
Result: True;

In> Error?()
Result: False;

*SEE Error?, Assert, Check, ClearErrors


*SOURCE org/mathpiper/scripts4/io/GetErrorTableau.mpws
==========
*CMD TableForm --- print each entry in a list on a line
*STD
*CALL
        TableForm(list)

*PARMS

{list} -- list to print

*DESC

This procedures writes out the list {list} in a better readable form, by
printing every element in the list on a separate line.

*E.G.

In> TableForm(BuildList(Factorial(i), i, 1, 10, 1));

         1
         2
         6
         24
         120
         720
         5040
         40320
         362880
         3628800
Result: True;

*SEE UnparseMath2D, Echo

*SOURCE org/mathpiper/scripts4/io/TableForm.mpws
==========

*CMD Tell --- debug routine using Echo to print ID and (optional) variable(s)

*STD
*CALL
        Tell(ID)
        Tell(ID,list)

*PARMS

{ID} -- an arbitrary identifier for this printout

{list} -- a list of items to be printed (may be a single item)

*DESC

If passed a single item, {Tell} will display it using Echo().  
The dispayed value will be enclosed with << >> (see below).
If ID consists of more than one word, it should be quoted.

If there are two arguments, the first should be an ID as above, and the second 
should be a list of variables which are bound to values at the place where
{Tell} is called.  Using Echo(), the list of variable names will be printed
out, along with a list of their currently bound values.

{Tell} can be called with any number of variable names in the list.

{Tell} always returns {True}.

Because {Tell} uses Echo(), it prints to Standard Output.  If you are debuging
a program which may hang, you may get no printout.  In that case, use {TellNow}
instead of {Tell}

*E.G. notest

In> var1:=123
Result: 123

In> var2:= "a string"
Result: "a string"

In> var3:=Sin(_x)+Exp(1)
Result: Sin(_x)+Exp(1)

In> Tell('ID1)
Result: True
        Side Effects>
        << ID1 >>

In> Tell('ID2,[var1])
Result: True
        Side Effects>
        << ID2 >> [var1] :  [123] 

In> Tell('ID3,[var1,var2])
Result: True
        Side Effects>
        << ID3 >> [var1,var2] [123,"a string"] 

In> Tell('ID4,[var1,var2,var3])
Result: True
        Side Effects>
        << ID4 >> [var1,var2,var3] :  [123,"a string",Sin(x)+Exp(x)] 


*SEE TellNow

*SOURCE org/mathpiper/scripts4/io/Tell.mpws
==========

*CMD TellNow --- debug routine using SysOut to print ID and (optional) variable(s)

*STD
*CALL
        TellNow(ID)
        TellNow(ID,list)

*PARMS

{ID} -- an arbitrary identifier for this printout

{list} -- a list of items to be printed (may be a single item)

*DESC

If passed a single item, {TellNow} will display it using SysOut().  
The dispayed value will be enclosed with << >> (see below).
If ID consists of more than one word, it should be quoted.

If there are two arguments, the first should be an ID as above, and the second 
should be a list of variables which are bound to values at the place where
{TellNow} is called.  Using SysOut(), the list of variable names will be printed
out, along with a list of their currently bound values.

{TellNow} can be called with any number of variable names in the list.

{TellNow} always returns {True}.

Because {TellNow} uses SysOut() to print its output, the output will be visible
both on Standard Output and also on the Shell console (if MathPiper is started
this way), or on the MathPiperIDE Activity Log (if started in MathPiperIDE).  
The latter is very useful for debugging programs which hang in a loop or
otherwise, because standard output may not then be visible, but the alternative
output will usually be available.

*E.G. notest

In> var1:=123
Result: 123

In> var2:= "a string"
Result: "a string"

In> var3:=Sin(x)+Exp(x)
Result: Sin(x)+Exp(x)

In> TellNow(ID1)
Result: True
        Side Effects>
        << ID1 >>

In> TellNow(ID2,[var1])
Result: True
        Side Effects>
        << ID2 >> [var1]:  [123]

In> TellNow(ID3,[var1,var2])
Result: True
        Side Effects>
        << ID3 >> [var1,var2]:  [123,a string]

In> TellNow(ID4,[var1,var2,var3])
Result: True
        Side Effects>
        << ID4 >> [var1,var2,var3]:  [123,a string,Sin(x)+Exp(x)]

*SEE Tell

*SOURCE org/mathpiper/scripts4/io/TellNow.mpws
==========
*CMD BaseVector --- base vector
*STD
*CALL
        BaseVector(k, n)

*PARMS

{k} -- index of the base vector to construct

{n} -- dimension of the vector

*DESC

This command returns the "k"-th base vector of dimension "n". This
is a vector of length "n" with all zeros except for the "k"-th
entry, which contains a 1.

*E.G.

In> BaseVector(2,4)
Result: [0,1,0,0]

*SEE ZeroVector, IdentityMatrix

*SOURCE org/mathpiper/scripts4/linalg/BaseVector.mpws
==========
*CMD BuildMatrix --- generate a matrix with a procedure
*CALL
        BuildMatrix(procedure,m,n)

*PARMS
{procedure} -- a pure procedure
{m} -- row index
{n} -- column index

*DESC
Generate a matrix with a pure procedure.

*E.G.
In> BuildMatrix(Lambda([m,n],m*n),3,3)
Result: [[1,2,3],[2,4,6],[3,6,9]]

*SOURCE org/mathpiper/scripts4/linalg/BuildMatrix.mpws
==========
*CMD CartesianProduct --- returns the Cartesian product of two lists
*CALL
        CartesianProduct(list1, list2)

*PARMS

{list1} -- a list

{list2} -- a list

*DESC

This procedure returns the Cartesian product of two lists.

*E.G.

In> CartesianProduct([_a,_b], [_c,_d])
Result: [[_a,_c],[_a,_x],[_b,_c],[_b,_d]]


In> CartesianProduct([2,3,4,5,6,7,8,9,10,'Jack,'Queen,'King,'Ace], ['Spades, 'Hearts, 'Diamonds, 'Clubs])
Result: [[2,Spades],[2,Hearts],[2,Diamonds],[2,Clubs],
[3,Spades],[3,Hearts],[3,Diamonds],[3,Clubs],
[4,Spades],[4,Hearts],[4,Diamonds],[4,Clubs],
[5,Spades],[5,Hearts],[5,Diamonds],[5,Clubs],
[6,Spades],[6,Hearts],[6,Diamonds],[6,Clubs],
[7,Spades],[7,Hearts],[7,Diamonds],[7,Clubs],
[8,Spades],[8,Hearts],[8,Diamonds],[8,Clubs],
[9,Spades],[9,Hearts],[9,Diamonds],[9,Clubs],
[10,Spades],[10,Hearts],[10,Diamonds],[10,Clubs],
[Jack,Spades],[Jack,Hearts],[Jack,Diamonds],[Jack,Clubs],
[Queen,Spades],[Queen,Hearts],[Queen,Diamonds],[Queen,Clubs],
[King,Spades],[King,Hearts],[King,Diamonds],[King,Clubs],
[Ace,Spades],[Ace,Hearts],[Ace,Diamonds],[Ace,Clubs]]

*SOURCE org/mathpiper/scripts4/linalg/CartesianProduct.mpws
==========
*CMD CoFactor --- cofactor of a matrix
*STD
*CALL
        CoFactor(M,i,j)

*PARMS

{M} -- a matrix

{i}, {j} - positive integers

*DESC

{CoFactor} returns the cofactor of a matrix around
the element ($i$, $j$). The cofactor is the minor times
$(-1)^{i+j}$.

*E.G.

In> A := [[1,2,3], [4,5,6], [7,8,9]];
Result: [[1,2,3],[4,5,6],[7,8,9]];

In> UnparseMath2D(A);
        
        /                    \
        | ( 1 ) ( 2 ) ( 3 )  |
        |                    |
        | ( 4 ) ( 5 ) ( 6 )  |
        |                    |
        | ( 7 ) ( 8 ) ( 9 )  |
        \                    /
Result: True;

In> CoFactor(A,1,2);
Result: 6;

In> Minor(A,1,2);
Result: -6;

In> Minor(A,1,2) * (-1)^(1+2);
Result: 6;

*SEE Minor, Determinant, Inverse

*SOURCE org/mathpiper/scripts4/linalg/CoFactor.mpws
==========
*CMD CrossProduct --- outer product of vectors

*CALL
    CrossProduct(a,b)


*PARMS

{a}, {b} -- three-dimensional vectors

*DESC

The cross product of the vectors "a"
and "b" is returned. The result is perpendicular to both "a" and
"b" and its length is the product of the lengths of the vectors.
Both "a" and "b" have to be three-dimensional.

*E.G.

In> CrossProduct([_a,_b,_c], [_d,_e,_f])
Result: [_b*_f - _c*_e,_c*_d - _a*_f,_a*_e - _b*_d]

*SEE InnerProduct

*SOURCE org/mathpiper/scripts4/linalg/CrossProduct.mpws
==========
*CMD Diagonal --- extract the diagonal from a matrix

*CALL
    Diagonal(A)

*PARMS

{A} -- matrix

*DESC

This command returns a vector of the diagonal components
of the matrix {A}.


*E.G.

In> Diagonal(5*Identity(4))
Result: [5,5,5,5]

In> Diagonal(HilbertMatrix(3))
Result: [1,1/3,1/5]

*SEE DiagonalMatrix, Diagonal?

*SOURCE org/mathpiper/scripts4/linalg/Diagonal.mpws
==========
*CMD DiagonalMatrix --- construct a diagonal matrix
*STD
*CALL
        DiagonalMatrix(d)

*PARMS

{d} -- list of values to put on the diagonal

*DESC

This command constructs a diagonal matrix, that is a square matrix
whose off-diagonal entries are all zero. The elements of the vector
"d" are put on the diagonal.

*E.G.

In> DiagonalMatrix(1 .. 4)
Result: [[1,0,0,0],[0,2,0,0],[0,0,3,0],[0,0,0,4]];

*SEE IdentityMatrix, ZeroMatrix

*SOURCE org/mathpiper/scripts4/linalg/DiagonalMatrix.mpws
==========
*CMD Dimensions --- dimensions (number of rows and columns etc) of input Matrix
*STD
*CALL
        Dimensions(Matrix)

*PARMS

{Matrix} -- a matrix


*DESC

This command returns an array of dimensions {nrows,ncols,...} corresponding to the input array.
The input array can be 1-dimensional (i.e., vector), 2-dimensional (i.e., matrix),
or higher dimensioned (tensor).  

If multidimensional, the array must not be "ragged", Else this procedure will give 
an incorrect result.

*E.G.
In> Dimensions([1,2,3,4])
Result: [4]

In> Dimensions([[1,2,3,4],[5,6,7,8]])
Result: [2,4]

In> Dimensions([[[4,8,1,2],[1,7,-3,-14]],[[2,-3,2,3],[11,12,13,14]],[[21,22,23,24],[31,32,33,34]]])
Result: [3,2,4]

In> Dimensions([[1,2,3,4],[5,6,7,8,9]])
Result: [2]


*SOURCE org/mathpiper/scripts4/linalg/Dimensions.mpws
==========
*CMD DotProduct --- get dot product of tensors
*STD
*CALL
        DotProduct(t1,t2)

*PARMS

{t1,t2} -- tensor lists (currently only vectors and matrices are supported)

*DESC

{DotProduct} returns the dot (aka inner) product of two tensors t1 and t2. The last
index of t1 and the first index of t2 are contracted. Currently {DotProduct} works
only for vectors and matrices. {DotProduct}-multiplication of two vectors, a matrix
with a vector (and vice versa) or two matrices yields either a scalar, a
vector or a matrix.

*E.G.

In> DotProduct([1,2],[3,4])
Result: 11;

In> DotProduct([[1,2],[3,4]],[5,6])
Result: [17,39];

In> DotProduct([5,6],[[1,2],[3,4]])
Result: [23,34];

In> DotProduct([[1,2],[3,4]],[[5,6],[7,8]])
Result: [[19,22],[43,50]];

*SEE OuterProduct, CrossProduct, Scalar?, Vector?, Matrix?

*SOURCE org/mathpiper/scripts4/linalg/DotProduct.mpws
==========
*CMD IdentityMatrix --- make identity matrix
*STD
*CALL
        IdentityMatrix(n)

*PARMS

{n} -- size of the matrix

*DESC

This commands returns the identity matrix of size "n" by "n". This
matrix has ones on the diagonal while the other entries are zero.

*E.G.

In> IdentityMatrix(3)
Result: [[1,0,0],[0,1,0],[0,0,1]]

*SEE BaseVector, ZeroMatrix, DiagonalMatrix

*SOURCE org/mathpiper/scripts4/linalg/IdentityMatrix.mpws
==========
*CMD InnerProduct --- inner product of vectors (deprecated)
*STD
*CALL
        InnerProduct(a,b)

*PARMS

{a}, {b} -- vectors of equal length

*DESC

The inner product of the two vectors "a" and "b" is returned. The
vectors need to have the same size.

*E.G.

In> InnerProduct([_a,_b,_c], [_d,_e,_f])
Result: _a*_d + _b*_e + _c*_f

In> InnerProduct([1,2,3], [4,5,6])
Result: 32



*SEE OuterProduct, DotProduct, CrossProduct

*SOURCE org/mathpiper/scripts4/linalg/InnerProduct.mpws
==========
*CMD LeviCivita --- totally anti-symmetric Levi-Civita symbol
*STD
*CALL
        LeviCivita(list)

*PARMS

{list} -- a list of integers 1 .. n in some order

*DESC

{LeviCivita} implements the Levi-Civita symbol. This is generally
useful for tensor calculus.  {list}  should be a list of integers,
and this procedure returns 1 if the integers are in successive order,
eg. {LeviCivita( [1,2,3,...] )}  would return 1. Swapping two elements of this
list would return -1. So, {LeviCivita( [2,1,3] )} would evaluate
to -1.

*E.G.

In> LeviCivita([1,2,3])
Result: 1;

In> LeviCivita([2,1,3])
Result: -1;

In> LeviCivita([2,2,3])
Result: 0;

*SEE PermutationsList

*SOURCE org/mathpiper/scripts4/linalg/LeviCivita.mpws
==========
*CMD Minor --- get principal minor of a matrix
*STD
*CALL
        Minor(M,i,j)

*PARMS

{M} -- a matrix

{i}, {j} - positive integers

*DESC

Minor returns the minor of a matrix around
the element ($i$, $j$). The minor is the determinant of the matrix obtained from $M$ by
deleting the $i$-th row and the $j$-th column.

*E.G.

In> A := [[1,2,3], [4,5,6], [7,8,9]];
Result: [[1,2,3],[4,5,6],[7,8,9]];

In> UnparseMath2D(A);
        
        /                    \
        | ( 1 ) ( 2 ) ( 3 )  |
        |                    |
        | ( 4 ) ( 5 ) ( 6 )  |
        |                    |
        | ( 7 ) ( 8 ) ( 9 )  |
        \                    /
Result: True;

In> Minor(A,1,2);
Result: -6;

In> Determinant([[2,3], [8,9]]);
Result: -6;

*SEE CoFactor, Determinant, Inverse

*SOURCE org/mathpiper/scripts4/linalg/Minor.mpws
==========
*CMD OuterProduct, o --- get outer tensor product
*STD
*CALL
        OuterProduct(t1,t2)

*PARMS

{t1,t2} -- tensor lists (currently only vectors are supported)

*DESC

{OuterProduct} returns the outer product of two tensors t1 and t2. Currently
{OuterProduct} work works only for vectors, i.e. tensors of rank 1. The outer
product of two vectors yields a matrix.

*E.G.

In> OuterProduct([1,2],[3,4,5])
Result: [[3,4,5],[6,8,10]];

In> OuterProduct([_a,_b],[_c,_d])
Result: [[_a*_c,_a*_d],[_b*_c,_b*_d]];



*SEE InProduct, DotProduct, CrossProduct

*SOURCE org/mathpiper/scripts4/linalg/OuterProduct.mpws
==========
*CMD SolveMatrix --- solve a system of equations

*CALL
    SolveMatrix(A,b)

*PARMS

{A} -- coefficient matrix

{b} -- row vector

*DESC

{SolveMatrix} solves the matrix equations {A*x = b} using Gaussian Elimination
with Backward substitution. If your matrix is triangular or diagonal, it will
be recognized as such and a faster algorithm will be used.

*E.G.

In> A:=[[2,4,-2,-2],[1,2,4,-3],[-3,-3,8,-2],[-1,1,6,-3]];
Result: [[2,4,-2,-2],[1,2,4,-3],[-3,-3,8,-2],[-1,1,6,-3]]

In> b:=[-4,5,7,7];
Result: [-4,5,7,7]

In> SolveMatrix(A,b);
Result: [1,2,3,4]

*SOURCE org/mathpiper/scripts4/linalg/SolveMatrix.mpws
==========
*CMD Transpose --- get transpose of a matrix
*STD
*CALL
        Transpose(M)

*PARMS

{M} -- a matrix

*DESC

{Transpose} returns the transpose of a matrix $M$. Because matrices are
just lists of lists, this is a useful operation too for lists.

*E.G.

In> res := Transpose([[_a,_b]])
Result: [[_a],[_b]];

In> res2:=Transpose(res)
Result: [[_a,_b]]

In> re2*res
Result: [[_a^2+_b^2]]

In> res*res2
Result: [[_a^2,_a*_b],[_b*_a,_b^2]]



*SOURCE org/mathpiper/scripts4/linalg/Transpose.mpws
==========
*CMD ZeroMatrix --- make a zero matrix
*STD
*CALL
        ZeroMatrix(n)
        ZeroMatrix(n, m)

*PARMS

{n} -- number of rows

{m} -- number of columns

*DESC

This command returns a matrix with {n} rows and {m} columns,
completely filled with zeroes. If only given one parameter,
it returns the square {n} by {n} zero matrix.

*E.G.

In> ZeroMatrix(3,4)
Result: [[0,0,0,0],[0,0,0,0],[0,0,0,0]];

In> ZeroMatrix(3)
Result: [[0,0,0],[0,0,0],[0,0,0]];


*SEE ZeroVector

*SOURCE org/mathpiper/scripts4/linalg/ZeroMatrix.mpws
==========
*CMD ZeroVector --- create a vector with all zeroes
*STD
*CALL
        ZeroVector(n)

*PARMS

{n} -- length of the vector to return

*DESC

This command returns a vector of length "n", filled with zeroes.

*E.G.

In> ZeroVector(4)
Result: [0,0,0,0];

*SEE ZeroMatrix, ZeroVector?

*SOURCE org/mathpiper/scripts4/linalg/ZeroVector.mpws
==========
*CMD MatrixColumn --- obtain the column of a matrix
*STD
*CALL
        MatrixColumn(matrix,column)

*PARMS
{matrix} -- a matrix
{column} -- the index of a matrix column

*DESC
Returns the column of a matrix which is specified by {column}.

*E.G.
In> aa := [[1,2], [3,4]];
Result: [[1,2],[3,4]]

In> MatrixColumn(aa,1)
Result: [1,3]

*SEE MatrixRow

*SOURCE org/mathpiper/scripts4/linalg/rowandcolumnoperations/MatrixColumn.mpws
==========
*CMD MatrixColumnAugment --- Adds a column to the end of the matrix
*STD
*CALL
        MatrixColumnAugment(m,vec)

*PARMS

{m} -- Matrix
{vec} -- vector of values to put in the column

*DESC

This command will add a column to the end of a matrix. The modified matrix is returned.

*E.G.
In> aa := BuildMatrix(Lambda([m,n],m*n),3,3)
Result: [[1,2,3],[2,4,6],[3,6,9]]

In> MatrixColumnAugment(aa,[7,8,9])
Result: [[1,2,3,7],[2,4,6,8],[3,6,9,9]]

*SOURCE org/mathpiper/scripts4/linalg/rowandcolumnoperations/MatrixColumnAugment.mpws
==========
*CMD MatrixColumnReplace --- Replace a column in a matrix
*STD
*CALL
        MatrixColumnReplace(m,col,vec)

*PARMS

{m} -- Matrix
{col} -- column to replace(as an integer)
{vec} -- vector of values to put in the column

*DESC

This command will replace the specified column of a matrix with a vector you pass in. The modified matrix is returned.

*E.G.
In> aa := BuildMatrix(Lambda([m,n],m*n),3,3)
Result: [[1,2,3],[2,4,6],[3,6,9]]

In> MatrixColumnReplace(aa,2,[5,4,3])
Result: [[1,5,3],[2,4,6],[3,3,9]]


*SOURCE org/mathpiper/scripts4/linalg/rowandcolumnoperations/MatrixColumnReplace.mpws
==========
*CMD MatrixColumnSwap --- Swaps two different columns of a matrix
*STD
*CALL
        MatrixColumnSwap(m,col1,col2)

*PARMS

{m} -- Matrix
{col1} -- the first column to swap
{col2} -- the second column to swap

*DESC

This command will swap all the elements in the two specified columns.

*E.G.
In> aa := BuildMatrix(Lambda([m,n],m*n),3,3)
Result: [[1,2,3],[2,4,6],[3,6,9]]

In> MatrixColumnSwap(aa,1,3)
Result: [[3,2,1],[6,4,2],[9,6,3]]

*SOURCE org/mathpiper/scripts4/linalg/rowandcolumnoperations/MatrixColumnSwap.mpws
==========
*CMD MatrixRow --- obtain the row of a matrix
*STD
*CALL
        MatrixRow(matrix,row)

*PARMS
{matrix} -- a matrix
{row} -- the index of a matrix row

*DESC
Returns the row of a matrix which is specified by {row}.

*E.G.
In> aa := [[1,2], [3,4]];
Result: [[1,2],[3,4]]

In> MatrixRow(aa,1)
Result: [1,2]

*SEE MatrixColumn

*SOURCE org/mathpiper/scripts4/linalg/rowandcolumnoperations/MatrixRow.mpws
==========
*CMD MatrixRowReplace --- Replace a row in a matrix
*STD
*CALL
        MatrixRowReplace(m,row,vec)

*PARMS

{m} -- Matrix
{row} -- row to replace(as an integer)
{vec} -- vector of values to put in the row

*DESC

This command will replace the specified row of a matrix with a vector you pass in. The modified matrix is returned.

*E.G.
In> aa := BuildMatrix(Lambda([m,n],m*n),3,3)
Result: [[1,2,3],[2,4,6],[3,6,9]]

In> MatrixRowReplace(aa,1,[7,8,9])
Result: [[7,8,9],[2,4,6],[3,6,9]]

*SOURCE org/mathpiper/scripts4/linalg/rowandcolumnoperations/MatrixRowReplace.mpws
==========
*CMD MatrixRowStack --- Adds a row to the end of a matrix

*CALL
        MatrixRowStack(m, vec)

*PARMS

{m} -- Matrix
{vec} -- vector of values to put in the row

*DESC

This command will add a row to the end of a matrix. The modified matrix is returned.


*E.G.
In> aa := BuildMatrix(Lambda([m,n],m*n),3,3)
Result: [[1,2,3],[2,4,6],[3,6,9]]

In> MatrixRowStack(aa,[7,8,9])
Result: [[1,2,3],[2,4,6],[3,6,9],[7,8,9]]


*SOURCE org/mathpiper/scripts4/linalg/rowandcolumnoperations/MatrixRowStack.mpws
==========
*CMD MatrixRowSwap --- Swaps two different rows of a matrix
*STD
*CALL
        MatrixRowSwap(m,row1,row2)

*PARMS

{m} -- Matrix
{row1} -- the first row to swap
{row2} -- the second row to swap

*DESC

This command will swap all the elements in the two specified rows

*E.G.
In> aa := BuildMatrix(Lambda([m,n],m*n),3,3)
Result: [[1,2,3],[2,4,6],[3,6,9]]

In> MatrixRowSwap(aa,1,3)
Result: [[3,6,9],[2,4,6],[1,2,3]]

*SOURCE org/mathpiper/scripts4/linalg/rowandcolumnoperations/MatrixRowSwap.mpws
==========
*CMD Append --- append an entry at the end of a list
*STD
*CALL
        Append(list, expr)

*PARMS

{list} -- list to append "expr" to

{expr} -- expression to append to the list

*DESC

The expression "expr" is appended at the end of "list" and the
resulting list is returned.

Note that due to the underlying data structure, the time it takes to
append an entry at the end of a list grows linearly with the length of
the list, while the time for prepending an entry at the beginning is
constant.

*EXAMPLES
In> ll := [_a,Pi,3,[1,2,3]] 
Result: [_a,Pi,3,[1,2,3]]

In> Append(ll,1) 
Result: [_a,Pi,3,[1,2,3],1]

In> ll 
Result: [_a,Pi,3,[1,2,3]]

In> ll := Append(ll,"PKHG") 
Result: [_a,Pi,3,[1,2,3],"PKHG"]

In> ll 
Result: [_a,Pi,3,[1,2,3],"PKHG"]

*SEE Concat, Append!

*SOURCE org/mathpiper/scripts4/lists/Append.mpws
==========
*CMD AppendList! --- destructively append one list to another
*STD
*CALL
        AppendList!(list, listToAdd)

*PARMS

{list} -- list for which to append {listToAdd}

{listToAdd} -- second list to append to the first

*DESC

The {AppendList!} procedure destructively appends one list to another.

*E.G.

In> list1 := [1,2,3,4]
Result: [1,2,3,4]

In> list2 := [5,6,7,8]
Result: [5,6,7,8]

In> AppendList!(list1, list2)
Result: True

In> list1
Result: [1,2,3,4,5,6,7,8]

*SEE Concat, :, Append!

*SOURCE org/mathpiper/scripts4/lists/AppendList__.mpws
==========
*CMD Append! --- destructively append an entry to a list
*STD
*CALL
        Append!(list, expr)

*PARMS

{list} -- list to append "expr" to

{expr} -- expression to append to the list

*DESC

This is the destructive counterpart of {Append}. This
command yields the same result as the corresponding call to
{Append}, but the original list is modified. So if a
variable is bound to "list", it will now be bound to the list with
the expression "expr" inserted.

Destructive commands run faster than their nondestructive counterparts
because the latter copy the list before they alter it.

*E.G.

In> lst := [_a,_b,_c,_d];
Result: [_a,_b,_c,_d];

In> Append(lst, 1);
Result: [_a,_b,_c,_d,1];

In> lst
Result: [_a,_b,_c,_d];

In> Append!(lst, 1);
Result: [_a,_b,_c,_d,1];

In> lst;
Result: [_a,_b,_c,_d,1];

*SEE Concat, Append

*SOURCE org/mathpiper/scripts4/lists/Append__.mpws
==========
*CMD BuildList --- evaluate while some variable ranges over interval
*STD
*CALL
        BuildList(body, var, from, to, step)

*PARMS

{body} -- expression to evaluate multiple times

{var} -- variable to use as loop variable

{from} -- initial value for "var"

{to} -- final value for "var"

{step} -- step size with which "var" is incremented

*DESC

This command generates a list of values from "body", by assigning
variable "var" values from "from" up to "to", incrementing
"step" each time. So, the variable "var" first gets the value
"from", and the expression "body" is evaluated. Then the value
"from"+"step" is assigned to "var" and the expression "body"
is again evaluated. This continues, incrementing "var" with "step"
on every iteration, until "var" exceeds "to". At that moment, all
the results are assembled in a list and this list is returned.

*EXAMPLES
In> BuildList(Factorial(i), i, 1, 9, 1) 
Result: [1,2,6,24,120,720,5040,40320,362880]

In> BuildList(i, i, 3, 16, 4) 
Result: [3,7,11,15]

In> BuildList(i^2, i, 10, 1, -1) 
Result: [100,81,64,49,36,25,16,9,4,1]

The loop variables may not be Constants!

In> BuildList(_a+b, b, 0, 2, 1) 
Result: [_a,_a + 1,_a + 2]

In> BuildList(BuildList(a+b, b, 0, 2, 1), a, 0, 2, 1) 
Result: [[0,1,2],[1,2,3],[2,3,4]]

*SEE For, MapSingle, .., TableForm

*SOURCE org/mathpiper/scripts4/lists/BuildList.mpws
==========
*CMD Contains? --- test whether a list contains a certain element
*STD
*CALL
        Contains?(list, expr)

*PARMS

{list} -- list to examine

{expr} -- expression to look for in "list"

*DESC

This command tests whether "list" contains the expression "expr"
as an entry. It returns {True} if it does and
{False} otherwise. Only the top level of "list" is
examined. The parameter "list" may also be a general expression, in
that case the top-level operands are tested for the occurrence of
"expr".

*EXAMPLES
In> Contains?([_a,_b,_c,_d], _b) 
Result: True

In> Contains?([_a,_b,_c,_d], _x) 
Result: False

In> Contains?([_a,[1,2,3],_z], 1) 
Result: False

In> Contains?(_a*_b, _b) 
Result: True

*SEE Find, Count

*SOURCE org/mathpiper/scripts4/lists/Contains.mpws
==========
*CMD Count --- count the number of occurrences of an expression
*STD
*CALL
        Count(list, expr)

*PARMS

{list} -- the list to examine

{expr} -- expression to look for in "list"

*DESC

This command counts the number of times that the expression "expr"
occurs in "list" and returns this number.

*EXAMPLES
In> lst := [_a,Pi,3,1,Pi,II] 
Result: [_a,Pi,3,1,Pi,II]

In> Count(lst,Pi) 
Result: 2

In> Count(lst, 1) 
Result: 1

In> Count(lst, _x) 
Result: 0

*SEE Length, Select, Contains?

*SOURCE org/mathpiper/scripts4/lists/Count.mpws
==========
*CMD Difference --- return the difference of two lists
*STD
*CALL
        Difference(l1, l2)

*PARMS

{l1}, {l2} -- two lists

*DESC

The difference of the lists "l1" and "l2" is determined and
returned. The difference contains all elements that occur in "l1"
but not in "l2". The order of elements in "l1" is preserved. If a
certain expression occurs "n1" times in the first list and "n2"
times in the second list, it will occur "n1-n2" times in the result
if "n1" is greater than "n2" and not at all otherwise.

*EXAMPLES
In> Difference([_a,_b,_c], [_b,_c,_d]) 
Result: [_a]

In> Difference([_a,_e,_i,_o,_u],[_f,_o,_u,_r,_t,_e,_e,_n]) 
Result: [_a,_i]

In> Difference([1,2,2,3,3,3], [2,2,3,4,4]) 
Result: [1,3,3]

*SEE Intersection, Union

*SOURCE org/mathpiper/scripts4/lists/Difference.mpws
==========
*CMD Drop --- drop a range of elements from a list

*STD

*CALL
        Drop(list, n)
        Drop(list, -n)
        Drop(list, [m,n])

*PARMS

{list} -- list to act on

{n}, {m} -- positive integers describing the entries to drop

*DESC

This command removes a sublist of "list" and returns a list
containing the remaining entries. The first calling sequence drops the
first "n" entries in "list". The second form drops the last "n"
entries. The last invocation drops the elements with indices "m"
through "n".

*EXAMPLES
In> lst := [_a,_b,_c,_d,_e,_f,_g] 
Result: [_a,_b,_c,_d,_e,_f,_g]

In> Drop(lst, 2) 
Result: [_c,_d,_e,_f,_g]

In> Drop(lst, -3) 
Result: [_a,_b,_c,_d]

In> Drop(lst, [2,4]) 
Result: [_a,_e,_f,_g]

*SEE Take, Select, Remove

*SOURCE org/mathpiper/scripts4/lists/Drop.mpws
==========
*CMD FillList --- fill a list with a certain expression
*STD
*CALL
        FillList(expr, n)

*PARMS

{expr} -- expression to fill the list with

{n} -- the length of the list to construct

*DESC

This command creates a list of length "n" in which all slots contain
the expression "expr" and returns this list.

*E.G.

In> FillList(x, 5);
Result: [x,x,x,x,x];

*SEE MakeVector, ZeroVector, RandomIntegerList

*SOURCE org/mathpiper/scripts4/lists/FillList.mpws
==========
*CMD Find --- get the index at which a certain element occurs
*STD
*CALL
        Find(list, expr)

*PARMS

{list} -- the list to examine

{expr} -- expression to look for in "list"

*DESC

This commands returns the index at which the expression "expr"
occurs in "list". If "expr" occurs more than once, the lowest
index is returned. If "expr" does not occur at all,
{-1} is returned.
NOTE: Find is a synonym for FindFirst.

*E.G.

In> Find([_a,_b,_c,_d,_e,_f],_d);
Result: 4;

In> Find([1,2,3,2,1], 2);
Result: 2;

In> Find([1,2,3,2,1], 4);
Result: -1;

*SEE FindFirst, FindAll, Contains?

*SOURCE org/mathpiper/scripts4/lists/Find.mpws
==========
*CMD Find --- get all indexes at which a certain element occurs
*STD
*CALL
        FindAll(list, expr)

*PARMS

{list} -- the list to examine

{expr} -- expression to look for in "list"

*DESC

This commands returns a list of all the indexes at which the 
expression "expr" occurs in "list". If "expr" occurs only once, 
ithat ndex is returned as a list. If "expr" does not occur at all,
the empty list, [], is returned.

*E.G.

In> FindAll([_a,_b,_c,_d,_e,_f], _d);
Result: [4]

In> FindAll([1,2,3,2,1], 2);
Result: [2,4]

In> FindAll([1,2,3,2,1], 4);
Result: []


*SEE Find, FindFirst, Contains?

*SOURCE org/mathpiper/scripts4/lists/FindAll.mpws
==========
*CMD Find --- get the index at which a certain element occurs first
*STD
*CALL
        FindFirst(list, expr)

*PARMS

{list} -- the list to examine

{expr} -- expression to look for in "list"

*DESC

This commands returns the index at which the expression "expr"
first occurs in "list". If "expr" occurs more than once, the lowest
index is returned. If "expr" does not occur at all,
{-1} is returned.

*E.G.

In> FindFirst([_a,_b,_c,_d,_e,_f], _d);
Result: 4;

In> FindFirst([1,2,3,2,1], 2);
Result: 2;

In> FindFirst([1,2,3,2,1], 4);
Result: -1;

*SEE Find, FindAll, Contains?

*SOURCE org/mathpiper/scripts4/lists/FindFirst.mpws
==========
*CMD Flatten --- flatten expression w.r.t. some operator
*STD
*CALL
        Flatten(expression,operator)

*PARMS

{expression} -- an expression

{operator} -- string with the contents of an infix operator.

*DESC

Flatten flattens an expression with respect to a specific
operator, converting the result into a list.
This is useful for unnesting an expression. Flatten is typically
used in simple simplification schemes.

*E.G.

In> Flatten(_a+_b*_c+_d,"+");
Result: [_a,_b*_c,_d];

In> Flatten([_a,[_b,_c],_d],"List");
Result: [-a,_b,_c,-d];

*SEE UnFlatten

*SOURCE org/mathpiper/scripts4/lists/Flatten.mpws
==========
*CMD Intersection --- return the Intersection of two or more lists
*STD
*CALL
        Intersection(L1, L2)
or
    Intersection( ListOfLists )

*PARMS

{L1}, {L2} -- two lists
or
{ListOfLists}  --  a List of two or more lists

*DESC

The Intersection of all the lists is determined and
returned. The Intersection contains all elements that occur in all
lists. The entries in the result are listed in the same order as in
the first list. If an expression occurs multiple times in all the
lists, then it will occur the same number of times in the result.

*EXAMPLES
In> Intersection([_a,_b,_c], [_b,_c,_d]) 
Result: [_b,_c]

In> Intersection([_a,_e,_i,_o,_u], [_f,_o,_u,_r,_t,_e,_e,_n]) 
Result: [_e,_o,_u]

In> Intersection([1,2,2,3,3,3], [1,1,2,2,3,3]) 
Result: [1,2,2,3,3]

In> Intersection([[1,2,2,3,3,3,_a,_c,_e],[1,1,2,2,3,3,_a,_c,_e],[3,_a,_b,_c,_d,_e,_f,1,3,5]]) 
Result: [1,3,3,_a,_c,_e]
    
*SEE Union, Difference


*SOURCE org/mathpiper/scripts4/lists/Intersection.mpws
==========
*CMD Last --- returns the last element of a list
*STD
*CALL
        Last(list)
        
*PARMS
{list} -- a list

*DESC
This procedure returns the last element of a list. 


*E.G.


In> lst := [_a,_b,_c,_d,_e,_f];
Result: [_a,_b,_c,_d,_e,_f];

In> Last(lst);
Result: _f

*SEE First,Rest

*SOURCE org/mathpiper/scripts4/lists/Last.mpws
==========
*CMD Map --- apply an $n$-ary procedure to all entries in a list
*STD
*CALL
        Map(fn, list)

*PARMS

{fn} -- procedure to apply

{list} -- list of lists of arguments

*DESC

This procedure applies "fn" to every list of arguments to be found in
"list". So the first entry of "list" should be a list containing
the first, second, third, ... argument to "fn", and the same goes
for the other entries of "list". The procedure can either be given as
a string or as a pure procedure (see Apply for more information on 
pure procedures).

*E.G.
For procedures needing TWO arguments
In> Map("+",[[_a,1/5],[Pi,4]]);
Result> [_a+Pi,21/5]

In> Map("List",[[1,2,3],[4,5,6]]);
Result: [[1,4],[2,5],[3,6]]

For procedures needing ONE argument
In> MapSingle("Sin",[_a,Pi,0]);
Result> [Sin(_a),Sin(Pi),Sin(0)]

*SEE MapSingle, MapArgs, Apply

*SOURCE org/mathpiper/scripts4/lists/Map.mpws
==========
*CMD MapArgs --- apply a procedure to all top-level arguments
*STD
*CALL
        MapArgs(expr, fn)

*PARMS

{expr} -- an expression to work on

{fn} -- an operation to perform on each argument

*DESC

Every top-level argument in "expr" is substituted by the result of
applying "fn" to this argument. Here "fn" can be either the name
of a procedure or a pure procedure (see Apply for more information on 
pure procedures).

*E.G.

In> MapArgs(f(x,y,z),"Sin");
Result: f(Sin(x),Sin(y),Sin(z));

In> MapArgs([3,4,5,6], [[x],x^2]);
Result: [9,16,25,36];

*SEE MapSingle, Map, Apply

*SOURCE org/mathpiper/scripts4/lists/MapArgs.mpws
==========
*CMD MapSingle --- apply a unary procedure to all entries in a list
*STD
*CALL
        MapSingle(fn, list)

*PARMS

{fn} -- procedure to apply

{list} -- list of arguments

*DESC

The procedure "fn" is successively applied to all entries in
"list", and a list containing the respective results is
returned. The procedure can be given either as a string or as a pure
procedure (see Apply for more information on pure procedures).

The {/@} operator provides a shorthand for
{MapSingle}.

*E.G.

Known procedures of with one argument:
In> MapSingle("Sin",[_a,4,Pi]);
Result: [Sin(_a),Sin(4),Sin(Pi)]

In> MapSingle(Lambda([x],x^2), [(_a+2)^2,2,Pi]); 
Result: [(_a+2)^4,4,Pi^2]

In> MapSingle(Lambda([x],Expand(x^2)), [(_a+2)^2,2,Pi])
Result: [_a^4+8*_a^3+24*_a^2+32*_a+16,4,Pi^2]


*SEE Map, MapArgs, /@, Apply, Lambda

*SOURCE org/mathpiper/scripts4/lists/MapSingle.mpws
==========
*CMD Partition --- partition a list in sublists of equal length
*STD
*CALL
        Partition(list, n)

*PARMS

{list} -- list to partition

{n} -- length of partitions

*DESC

This command partitions "list" into non-overlapping sublists of
length "n" and returns a list of these sublists. The first "n"
entries in "list" form the first partition, the entries from
position "n+1" up to "2n" form the second partition, and so on. If
"n" does not divide the length of "list", the remaining entries
will be thrown away. If "n" equals zero, an empty list is
returned.

*E.G.

In> Partition([_a,_b,_c,_d,_e,_f,], 2);
Result: [[_a,_b],[_c,_d],[_e,_f]];

In> Partition(1 .. 11, 3);
Result: [[1,2,3],[4,5,6],[7,8,9]];

*SEE Take, PermutationsList

*SOURCE org/mathpiper/scripts4/lists/Partition.mpws
==========
*CMD Pop --- remove an element from a stack
*STD
*CALL
        Pop(stack, n)

*PARMS

{stack} -- a list (which serves as the stack container)

{n} -- index of the element to remove

*DESC

This is part of a simple implementation of a stack, internally
represented as a list. This command removes the element with index
"n" from the stack and returns this element. The top of the stack is
represented by the index 1. Invalid indices, for example indices
greater than the number of element on the stack, lead to an error.

*E.G.

In> stack := [];
Result: [];

In> Push(stack, x);
Result: [x];

In> Push(stack, x2);
Result: [x2,x];

In> Push(stack, x3);
Result: [x3,x2,x];

In> Pop(stack, 2);
Result: x2;

In> stack;
Result: [x3,x];

*SEE Push, PopFront, PopBack

*SOURCE org/mathpiper/scripts4/lists/Pop.mpws
==========
*CMD PopBack --- remove an element from the bottom of a stack
*STD
*CALL
        PopBack(stack)

*PARMS

{stack} -- a list (which serves as the stack container)

*DESC

This is part of a simple implementation of a stack, internally
represented as a list. This command removes the element at the bottom
of the stack and returns this element. Of course, the stack should not
be empty.

*E.G.

In> stack := [];
Result: [];

In> Push(stack, x);
Result: [x];

In> Push(stack, x2);
Result: [x2,x];

In> Push(stack, x3);
Result: [x3,x2,x];

In> PopBack(stack);
Result: x;

In> stack;
Result: [x3,x2];

*SEE Push, Pop, PopFront

*SOURCE org/mathpiper/scripts4/lists/PopBack.mpws
==========
*CMD PopFront --- remove an element from the top of a stack
*STD
*CALL
        PopFront(stack)

*PARMS

{stack} -- a list (which serves as the stack container)

*DESC

This is part of a simple implementation of a stack, internally
represented as a list. This command removes the element on the top of
the stack and returns it. This is the last element that is pushed onto
the stack.

*E.G.

In> stack := [];
Result: [];

In> Push(stack, x);
Result: [x];

In> Push(stack, x2);
Result: [x2,x];

In> Push(stack, x3);
Result: [x3,x2,x];

In> PopFront(stack);
Result: x3;

In> stack;
Result: [x2,x];

*SEE Push, Pop, PopBack

*SOURCE org/mathpiper/scripts4/lists/PopFront.mpws
==========
*CMD PrintList --- print list with padding
*STD
*CALL
        PrintList(list)
        PrintList(list, padding);

*PARMS

{list} -- a list to be printed

{padding} -- (optional) a string

*DESC

Prints {list} and inserts the {padding} string between each pair of items of the list. 
Items of the list which are strings  are printed without quotes, unlike {Write()}. 
Items of the list which are themselves lists are printed inside brackets {[]}. 
If padding is not specified, a standard one is used (comma, space).

*E.G.

In> PrintList([_a,_b,[_c,_d]], " .. ")
Result: " _a ..  _b .. [ _c ..  _d]";

*SEE Write, WriteString

*SOURCE org/mathpiper/scripts4/lists/PrintList.mpws
==========
*CMD ProcedureList --- list of procedures used in an expression
*CMD ProcedureListAll --- list of procedures used in an expression
*CMD ProcedureListArithmetic --- list of procedures used in an expression
*CMD ProcedureListSome --- list of procedures used in an expression
*STD
*CALL
        ProcedureList(expr)
        ProcedureListAll(expr)
        ProcedureListArithmetic(expr)
        ProcedureListSome(expr, list)

*PARMS

{expr} -- an expression

{list} -- list of procedure atoms to be considered "transparent"

*DESC

The command {ProcedureList(expr)} returns a list of all procedure atoms that appear
in the expression {expr} with no duplicates. The expression is recursively 
traversed.

The command {ProcedureListAll(expr)} is similar to ProcedureList, except it does not
remove duplicates.

The command {ProcedureListSome(expr, list)} does the same, except it only looks 
at arguments of a given {list} of procedures. All other procedures become 
"opaque" (as if they do not contain any other procedures).
For example, {ProcedureListSome(a + Sin(b-c))} will see that the expression has 
a "{-}" operation and return {[+,Sin,-]}, but {ProcedureListSome(a + Sin(b-c), [+])} 
will not look at arguments of {Sin()} and will return {[+,Sin]}.

{ProcedureListArithmetic} is defined through {ProcedureListSome} to look only at arithmetic operations {+}, {-}, {*}, {/}.

Note that since the operators "{+}" and "{-}" are prefix as well as infix operators, 
it is currently required to use {ToAtom("+")} to obtain the unevaluated atom "{+}".

*EXAMPLES
In> ProcedureList('x+'y*Cos(Ln('x)/'x)) 
Result: ["+","*","Cos","/","Ln"]

In> ProcedureListArithmetic(_x+_y*Cos(Ln(_x)/_x)) 
Result: [+,*,Cos]

*SEE ProcedureListArithmetic, ProcedureListSome, VarList, HasExpression?, HasProcedure?

*SOURCE org/mathpiper/scripts4/lists/ProcedureList.mpws
==========
*CMD ProcedureList --- list of procedures used in an expression
*CMD ProcedureListArithmetic --- list of procedures used in an expression
*CMD ProcedureListSome --- list of procedures used in an expression
*STD
*CALL
        ProcedureList(expr)
        ProcedureListArithmetic(expr)
        ProcedureListSome(expr, list)

*PARMS

{expr} -- an expression

{list} -- list of procedure atoms to be considered "transparent"

*DESC

The command {ProcedureList(expr)} returns a list of all procedure atoms that appear
in the expression {expr}. The expression is recursively traversed.

The command {ProcedureListSome(expr, list)} does the same, except it only looks at arguments of a given {list} 
of procedures. All other procedures become "opaque" (as if they do not contain any other procedures).
For example, {ProcedureListSome(a + Sin(b-c))} will see that the expression has a "{-}" operation and return 
{[+,Sin,-]}, but {ProcedureListSome(a + Sin(b-c), {+})} will not look at arguments of {Sin()} and will return {[+,Sin]}.

{ProcedureListArithmetic} is defined through {ProcedureListSome} to look only at arithmetic operations {+}, {-}, {*}, {/}.

Note that since the operators "{+}" and "{-}" are prefix as well as infix operators, it is currently required to use 
{ToAtom("+")} to obtain the unevaluated atom "{+}".

*EXAMPLES
In> ProcedureList('x+'y*Cos(Ln('x)/'x)) 
Result: ["+","*","Cos","/","Ln"]

In> ProcedureListArithmetic(_x+_y*Cos(Ln(_x)/_x)) 
Result: [+,*,Cos]

*SEE ProcedureList, ProcedureListSome, VarList, HasExpression?, HasProcedure?

*SOURCE org/mathpiper/scripts4/lists/ProcedureListArithmetic.mpws
==========
*CMD ProcedureList --- list of procedures used in an expression
*CMD ProcedureListArithmetic --- list of procedures used in an expression
*CMD ProcedureListSome --- list of procedures used in an expression
*STD
*CALL
        ProcedureList(expr)
        ProcedureListArithmetic(expr)
        ProcedureListSome(expr, list)

*PARMS

{expr} -- an expression

{list} -- list of procedure atoms to be considered "transparent"

*DESC

The command {ProcedureList(expr)} returns a list of all procedure atoms that appear
in the expression {expr}. The expression is recursively traversed.

The command {ProcedureListSome(expr, list)} does the same, except it only looks at 
arguments of a given {list} of procedures. All other procedures become "opaque" 
(as if they do not contain any other procedures).
For example, {ProcedureListSome(a + Sin(b-c))} will see that the expression has a 
"{-}" operation and return {[+,Sin,-]}, but {ProcedureListSome(a + Sin(b-c), [+])} 
will not look at arguments of {Sin()} and will return {[+,Sin]}.

{ProcedureListArithmetic} is defined through {ProcedureListSome} to look only at arithmetic 
operations {+}, {-}, {*}, {/}.

Note that since the operators "{+}" and "{-}" are prefix as well as infix 
operators, it is currently required to use {ToAtom("+")} to obtain the 
unevaluated atom "{+}".

*E.G.

*EXAMPLES

*SEE ProcedureList, ProcedureListArithmetic, VarList, HasExpression?, HasProcedure?

*SOURCE org/mathpiper/scripts4/lists/ProcedureListSome.mpws
==========
*CMD Push --- add an element on top of a stack
*STD
*CALL
        Push(stack, expr)

*PARMS

{stack} -- a list (which serves as the stack container)

{expr} -- expression to push on "stack"

*DESC

This is part of a simple implementation of a stack, internally
represented as a list. This command pushes the expression "expr" on
top of the stack, and returns the stack afterwards.

*E.G.

In> stack := [];
Result: [];

In> Push(stack, x);
Result: [x];

In> Push(stack, x2);
Result: [x2,x];

In> PopFront(stack);
Result: x2;

*SEE Pop, PopFront, PopBack

*SOURCE org/mathpiper/scripts4/lists/Push.mpws
==========
*CMD Remove --- remove all occurrences of an expression from a list
*STD
*CALL
        Remove(list, expr)

*PARMS

{list} -- list to act on

{expr} -- expression to look for in "list"

*DESC

This command removes all elements that match a given expression from a given list and returns the resulting list.

*E.G.
In> Remove([_a,_b,_a,_b,_c,_a,_c],_a)
Result> [_b,_b,_c,_c]

*SEE RemoveDuplicates


*SOURCE org/mathpiper/scripts4/lists/Remove.mpws
==========
*CMD RemoveDuplicates --- remove any duplicates from a list
*STD
*CALL
        RemoveDuplicates(list)

*PARMS

{list} -- list to act on

*DESC

This command removes all duplicate elements from a given list and returns the resulting list.
To be precise, the second occurrence of any entry is deleted, as are the
third, the fourth, etc.

*EXAMPLES
In> RemoveDuplicates([1,2,3,2,1]) 
Result: [1,2,3]

In> RemoveDuplicates('([a,1,b,1,c,1])) 
Result: [a,1,b,c]

*SEE Remove, Drop, Select, Take

*SOURCE org/mathpiper/scripts4/lists/RemoveDuplicates.mpws
==========
*CMD Reverse --- return the reversed list (without touching the original)
*STD
*CALL
        Reverse(list)

*PARMS

{list} -- list to reverse

*DESC

This procedure returns a list reversed, without changing the
original list. It is similar to {Reverse!}, but safer
and slower.


*EXAMPLES
In> lst:='[a,b,c,13,19] 
Result: [a,b,c,13,19]

In> revlst:=Reverse(lst) 
Result: [19,13,c,b,a]

In> lst 
Result: [a,b,c,13,19]

*SEE FlatCopy, Reverse!

*SOURCE org/mathpiper/scripts4/lists/Reverse.mpws
==========
*CMD Select --- select entries satisfying some predicate
*STD
*CALL
        Select(list, pred)

*PARMS

{pred} -- a predicate

{list} -- a list of elements to select from

*DESC

{Select} returns a sublist of "list" which contains all
the entries for which the predicate "pred" returns
{True} when applied to this entry.

The {Lambda} procedure can be used in place of a predicate procedure
if desired.

*E.G.

In> Select([_a,_b,2,_c,3,_d,4,_e,_f], "Integer?")
Result: [2,3,4];


/%mathpiper

list := [1,-3,2,-6,-4,3];

Select(list, Lambda([i], i >? 0 ));

/%/mathpiper

    /%output,preserve="false"
      Result: [1,2,3]
.   /%/output

*SEE Length, Find, Count, Lambda

*SOURCE org/mathpiper/scripts4/lists/Select.mpws
==========
*CMD Swap --- swap two elements in a list
*STD
*CALL
        Swap(list, i1, i2)

*PARMS

{list} -- the list in which a pair of entries should be swapped

{i1, i2} -- indices of the entries in "list" to swap

*DESC

This command swaps the pair of entries with entries "i1" and "i2"
in "list". So the element at index "i1" ends up at index "i2"
and the entry at "i2" is put at index "i1". Both indices should be
valid to address elements in the list. Then the updated list is
returned.

{Swap()} works also on generic arrays.

*E.G.

In> lst := [_a,_b,_c,_d,_e,_f];
Result: [_a,_b,_c,_d,_e,_f];

In> Swap(lst, 2, 4);
Result: [_a,_d,_c,_b,_e,_f];

*SEE Replace, Replace!, ArrayCreate

*SOURCE org/mathpiper/scripts4/lists/Swap.mpws
==========
*CMD Take --- take a sublist from a list (dropping the rest)
*STD
*CALL
        Take(list, n)
        Take(list, -n)
        Take(list, [m,n])

*PARMS

{list} -- list to act on

{n}, {m} -- positive integers describing the entries to take

*DESC

This command takes a sublist of "list", drops the rest, and returns
the selected sublist. The first calling sequence selects the first
"n" entries in "list". The second form takes the last "n"
entries. The last invocation selects the sublist beginning with entry
number "m" and ending with the "n"-th entry.

*E.G.

In> lst := [_a,_b,_c,_d,_e,_f,_g];
Result: [_a,_b,_c,_d,_e,_f,_g];

In> Take(lst, 2);
Result: [_a,_b];

In> Take(lst, -3);
Result: [_e,_f,_g];

In> Take(lst, [2,4]);
Result: [_b,_c,_d];

*SEE Drop, Select, Remove

*SOURCE org/mathpiper/scripts4/lists/Take.mpws
==========
*CMD UnFlatten --- inverse operation of Flatten
*STD
*CALL
    UnFlatten(list, operator)
    UnFlatten(list, operator, identity)

*PARMS

{list} -- list of objects the operator is to work on

{operator} -- infix operator

{identity} -- identity of the operator

*DESC

UnFlatten is the inverse operation of Flatten. Given
a list, it can be turned into an expression representing
for instance the addition of these elements by calling
UnFlatten with "+" as argument to operator, and 0 as
argument to identity (0 is the identity for addition, since
a+0=a). For multiplication the identity element would be 1.

*E.G.

In> UnFlatten([_a,_b,_c], "+")
Result: _a+_b+_c

In> UnFlatten([_a,_b,_c], "+", 0)
Result: _a+_b+_c

In> UnFlatten([_a,_b,_c], "*", 1)
Result: _a*_b*_c

*SEE Flatten

*SOURCE org/mathpiper/scripts4/lists/UnFlatten.mpws
==========
*CMD Union --- return the union of two lists
*STD
*CALL
        Union(l1, l2)

*PARMS

{l1}, {l2} -- two lists

*DESC

The union of the lists "l1" and "l2" is determined and
returned. The union contains all elements that occur in one or both of
the lists. In the resulting list, any element will occur only once.

*EXAMPLES
In> Union([_a,_b,_c], [_b,_c,_d]) 
Result: [_a,_b,_c,_d]

In> Union([_a,_e,_i,_o,_u], [_f,_o,_u,_r,_t,_e,_e,_n]) 
Result: [_a,_e,_i,_o,_u,_f,_r,_t,_n]

In> Union([1,2,2,3,3,3], [2,2,3,3,4,4]) 
Result: [1,2,3,4]

*SEE Intersection, Difference

*SOURCE org/mathpiper/scripts4/lists/Union.mpws
==========
*CMD VarList --- list of variables appearing in an expression (without duplicates)
*STD
*CALL
        VarList(expr)

*PARMS

{expr} -- an expression

{list} -- a list of procedure atoms

*DESC

The command {VarList(expr)} returns a list of all variables that appear in 
the expression {expr}. The expression is traversed recursively.

Note that since the operators "{+}" and "{-}" are prefix as well as infix 
operators, it is currently required to use {ToAtom("+")} to obtain the 
unevaluated atom "{+}".

*EXAMPLES
In> VarList('(Sin('x))) 
Result: [x]

In> VarList('('x+'a*'y)) 
Result: [x,a,y]

In> VarList('(2+'a*3)) 
Result: [a]

*SEE VarListArith, VarListSome, VarListAll, FreeOf?, Variable?, ProcedureList, HasExpression?, HasProcedure?, UnderscoreConstants, UnderscoreConstantsAll

*SOURCE org/mathpiper/scripts4/lists/VarList.mpws
==========
*CMD VarListAll --- list of variables appearing in an expression (with duplicates)
*STD
*CALL
        VarListAll(expr)

*PARMS

{expr} -- an expression

{list} -- a list of procedure atoms

*DESC

The command {VarListAll(expr)} returns a list of all variables (including duplicates) 
that appear in the expression {expr}. The expression is traversed recursively.

Note that since the operators "{+}" and "{-}" are prefix as well as infix operators, 
it is currently required to use {ToAtom("+")} to obtain the unevaluated atom "{+}".

*E.G.

In> VarListAll(x^2 + 2*x + x + a)
Result: [x,x,x,a]

*SEE VarList, VarListArith, VarListSome, FreeOf?, Variable?, ProcedureList, HasExpression?, HasProcedure?

*SOURCE org/mathpiper/scripts4/lists/VarListAll.mpws
==========
*CMD VarListArith --- list of variables appearing in an expression (without duplicates)
*STD
*CALL
        VarListArith(expr)

*PARMS

{expr} -- an expression

{list} -- a list of procedure atoms

*DESC

The command [VarListArith] returns a list of all variables (without duplicates) that appear
arithmetically in the expression [expr]. This is implemented through
[VarListSome] by restricting to the arithmetic procedures [+], [-], [*], [/].
Arguments of other procedures are not checked.

Note that since the operators "[+]" and "[-]" are prefix as well as infix operators, it is currently required to use [ToAtom("+")] to obtain the unevaluated atom "[+]".

*E.G.

In> VarListArith(x+y*Cos(Ln(x)/x))
Result: [x,y,Cos(Ln(x)/x)]

In> VarListArith(x+a*y^2-1)
Result: [x,a,y^2];

*SEE VarList, VarListSome, VarListAll, FreeOf?, Variable?, ProcedureList, HasExpression?, HasProcedure?

*SOURCE org/mathpiper/scripts4/lists/VarListArith.mpws
==========
*CMD VarListSome --- list of variables appearing in an expression (without duplicates)
*STD
*CALL
        VarListSome(expr, list)

*PARMS

{expr} -- an expression

{list} -- a list of procedure atoms

*DESC

The command {VarList(expr)} returns a list of variables (without duplicates) that appear in the
expression {expr}. The command {VarListSome} looks only at arguments of procedures in the {list}. 
All other procedures are  considered "opaque" (as if they do not contain any variables) and their 
arguments are not checked. For example, {VarListSome(a + Sin(b-c))} will return {[a, b, c]}, 
but [VarListSome(a*Sin(b-c), [*])]  will not look at arguments of [Sin()] and will return 
{[a,Sin(b-c)]}. Here {Sin(b-c)} is considered a "variable" because the procedure {Sin} does not 
belong to {list}.

Note that since the operators "{+}" and "{-}" are prefix as well as infix operators, it is currently 
required to use {ToAtom("+")} to obtain the unevaluated atom "{+}".

*E.G.

In> VarListSome(x+a*y, [ToAtom("+")])
Result: [x,a*y];


*SEE VarList, VarListArith, VarListAll, FreeOf?, Variable?, ProcedureList, HasExpression?, HasProcedure?

*SOURCE org/mathpiper/scripts4/lists/VarListSome.mpws
==========
*CMD GlobalPop --- restore variables using a global stack
*CMD GlobalPush --- save variables using a global stack
*STD
*CALL
        GlobalPop(var)
        GlobalPop()
        GlobalPush(expr)

*PARMS

{var} -- atom, name of variable to restore from the stack

{expr} -- expression, value to save on the stack

*DESC

These procedures operate with a global stack, currently implemented as a list 
that is not accessible externally (it is protected 
through {LocalSymbols}).

{GlobalPush} stores a value on the stack. {GlobalPop} removes the last pushed 
value from the stack. If a variable name is given, the variable is assigned, 
otherwise the popped value is returned.

If the global stack is empty, an error message is printed.

*E.G.

In> GlobalPush(3)
Result: 3;

In> GlobalPush(Sin(_x))
Result: Sin(_x);

In> GlobalPop(x)
Result: Sin_(_x);

In> GlobalPop(x)
Result: 3;

In> x
Result: 3;

In> GlobalPop()
Result: Exception
Exception: Invariant Error: GlobalPop: Error: empty GlobalStack 


*SEE Push, PopFront

*SOURCE org/mathpiper/scripts4/lists/global_stack.mpws
==========
*CMD AddTo --- add an equation to a set of equations or set of set of equations
*STD
*CALL
        eq1 AddTo eq2

*PARMS

{eq} - (set of) set of equations

*DESC

Given two (sets of) sets of equations, the command AddTo combines
multiple sets of equations into one. 

A list {a,b} means that a is a solution, OR b is a solution.
AddTo then acts as a AND operation:

        (a or b) and (c or d) => 
        (a or b) Addto (c or d) => 
        (a and c) or (a and d) or (b and c)
          or (b and d)

This procedure is useful for adding an identity to an already
existing set of equations. Suppose a solve command returned
{a>=?0 &? x==a,a<?0 &? x== -a} from an expression x==Abs(a),
then a new identity a==2 could be added as follows:

In> a==2 AddTo {a>=?0 &? x==a,a<?0 &? x== -a}
Result: {a==2 &? a>=?0 &? x==a,a==2 &? a<?0 &? x== -a}

Passing this set of set of identities back to solve, solve
should recognize that the second one is not a possibility
any more, since a==2 &? a<?0 can never be true at the same time.

This operator can help the user to program in the style of functional 
programming languages such as Miranda or Haskell.

*E.G.

In> [A==2,c==d] AddTo [b==3 &? d==2]
Result: [A==2 &? b==3 &? d==2,c==d &? b==3 &? d==2];

In> [A==2,c==d] AddTo [b==3, d==2]
Result: [A==2 &? b==3,A==2 &? d==2,c==d &? b==3,c==d &? d==2];

*SEE Where, Solve

*SOURCE org/mathpiper/scripts4/localrules/AddTo.mpws
==========
*CMD Where --- substitute result into expression
*STD
*CALL
        expr Where x == v
        expr Where x1 == v1 &? x2 == v2 &? ...
        expr Where [x1 == v1 &? x2 == v2, x1 == v3
          &? x2 == v4, ...]

*PARMS

{expr} - expression to evaluate

{x} - variable to set

{v} - value to substitute for variable

*DESC

The operator {Where} fills in values for variables, in its simplest form.
It accepts sets of variable/value pairs defined as 

        var1 == val1 &? var2 == val2 &? ...

and fills in the corresponding values. Lists of value pairs are
also possible, as:

        [var1 == val1 &? var2 == val2, var1 == val3 &? var2 == val4]

These values might be obtained through {Solve}.

This operator can help the user to program in the style of functional 
programming languages such as Miranda or Haskell.

*E.G.
In> _x^2 + _y^2 Where _x == 2
Result: 4 + _y^2

In> _x^2 + _y^2 Where _x == 2 &? _y == 3
Result: 13

In> _x^2 + _y^2 Where [_x == 2 &? _y == 3]
Result: [13]

In> _x^2 + _y^2 Where [_x == 2 &? _y == 3, _x == 4 &? _y == 5]
Result: [13,41]

*SEE Solve, AddTo, Substitute, Where, WithValue, /:

*SOURCE org/mathpiper/scripts4/localrules/Where.mpws
==========
*CMD /:: --- local transformation rules

    expressions /:: patterns


*PARMS

{expression} -- an expression

{patterns} -- a list of patterns

*DESC

It might be necessary sometimes to use the {/::} operator, which
repeatedly applies the {/:} operator until the result doesn't change
any more. Caution is required, since rules can contradict each other,
which could result in an infinite loop. To detect this situation,
just use /: repeatedly on the expression. The repetitive nature
should become apparent.


*E.G.

In> Sin(u)*Ln(a*b) /:: [ a -> 2, b -> 3 ]
Result: Sin(u)*Ln(6);

*SEE /:, Substitute

*SOURCE org/mathpiper/scripts4/localrules/slash_colon_colon_operator.mpws
==========
*CMD /: --- local transformation rules

        expression /: patterns

*PARMS

{expression} -- an expression

{patterns} -- a list of patterns

*DESC

Sometimes you have an expression, and you want to use specific
transformation rules on it that are not done by default. This
can be done with the {/:} and the {/::} operators. Suppose we have the
expression containing things such as {Ln(a*b)}, and we want
to change these into {Ln(a)+Ln(b)}, the easiest way
to do this is using the {/:} operator, as follows:

PKHG: 
In> Sin(_x)*Ln(_a*_b) /: [ Ln(x_*y_) -> Ln(x)+Ln(y) ]
Result: Sin(_x)*(Ln(_a)+Ln(_b))

In> var := Sin(_x)*Ln(a_*b_)
Result: Sin(_x)*Ln(a_*b_);

In> var /: [ Ln(x_*y_) -> Ln(x)+Ln(y) ]
Result: Sin(_x)*(Ln(a_)+Ln(b_));

A whole list of simplification rules can be built up in the list,
and they will be applied to the expression on the left hand side
of {/:} .

The forms the patterns can have are one of:

        pattern -> replacement
        {pattern,replacement}
        {pattern,postpredicate,replacement}

Note that for these local rules, {->} should be used instead of
{-->} which would be used in a global rule.

The {/:} operator traverses an expression much as {Substitute} does, that is, top
down, trying to apply the rules from the beginning of the list of
rules to the end of the list of rules. If the rules cannot be applied
to an expression, it will try subexpressions of that
expression and so on.

A local rule that is defined by the -> operator can be given a name by using the 
# operator:

"RuleName" ## Ln(x_*y_) -> Ln(x) + Ln(y)

Each time the rule is selected while the system is in verbose mode, the name of 
the rule will be printed as a side effect.


*E.G.

In> Sin(_u)*Ln(_a*_b) /: [Ln(x_*y_) -> Ln(x) + Ln(y)]
Result: Sin(u)*(Ln(a)+Ln(b));

In> Verbose(Sin(u)*Ln(a*b) /: [ "RuleName" ## Ln(x_*y_) -> Ln(x) + Ln(y)])
Result: Sin(u)*(Ln(a)+Ln(b))
Side Effects:
RuleName


/%mathpiper

Hold((a + b) * (1 + 2) * (2 + 1) * (1/2 + c) * (3/4 + d) ) /:
   [
     (x_Odd? + y_Even?) -> m1_,
     
     (x_Even? + y_Odd?) -> m2_,
     
     (x_Rational? + y_Variable?)::(Denominator(x) =? 2) -> m3_
   ];

/%/mathpiper

    /%output,preserve="false"
      Result: ((((a + b) * m1_) * m2_) * m3_) * (3 / 4 + d)
.   /%/output

*SEE /::, Substitute

*SOURCE org/mathpiper/scripts4/localrules/slash_colon_operator.mpws
==========
*CMD Conversion --- define unit conversion rules in a Problem body

*CALL
        Conversion()

*DESC

Define unit conversions in a Problem body.

*EXAMPLES
In> Conversion() {_pixel -> 3 * byte;} 
Result: Conversion() {_pixel -> 3 * byte;}
*SEE Problem, Formula, Formulas, EvaluateFormula, Lookup

*SOURCE org/mathpiper/scripts4/manual_solving/Conversion.mpws
==========
*CMD Description --- describe a problem using a natural language in a Problem body.

*CALL
        Description()

*DESC

Describe a problem using a natural language in a Problem body.



*SEE Problem, Formula, Given, EvaluateFormula

*SOURCE org/mathpiper/scripts4/manual_solving/Description.mpws
==========
*CMD EvaluateFormula --- evaluate an expression inside of a Problem body

*CALL
        EvaluateFormula(exp)
        EvaluateFormula(exp, unit)

*PARMS

{exp} -- an expression

{unit} -- A unit to convert the result to

*DESC

evaluate an expression inside of a Problem bod.

*EXAMPLES
In> formulaName := Formula(z == x + y, Label: "Example Formula") 
Result: Formula(z == x + y, Label: "Example Formula")

In> x := 1`MHz 
Result: 1`MHz

In> y := 2`MHz 
Result: 2`MHz

In> EvaluateFormula(formulaName) 
Result: 3`MHz

In> EvaluateFormula(formulaName, kHz) 
Result: 3000`kHz

*SEE Problem, Formula, Formulas, Given


*SOURCE org/mathpiper/scripts4/manual_solving/EvaluateFormula.mpws
==========
*CMD Evaluations --- perform evaluations in a Problem body

*CALL
        Evaluations()

*PARMS


*DESC

Perform evaluations in a Problem body.



*SEE Problem, Formula, Given, EvaluateFormula

*SOURCE org/mathpiper/scripts4/manual_solving/Evaluations.mpws
==========
*CMD Formula --- define a formula in a Problem body

*CALL
        Formula(formula, <options>)

*PARMS

{formula} -- a formula


*DESC

Evaluate an expression inside of a {Formulas} body.

*EXAMPLES
In> formulaName := Formula(z == x + y, Label: "Example Formula") 
Result: Formula(z == x + y, Label: "Example Formula")

In> f3~1 := Formula(I~I`A == V~V`V/R~R`Ω, Label: "3.1", Page: "78", Description: "Find current using Ohm's Law") 
Result: Formula(I~I`A == V~V`V / R~R`Ω, Label:"3.1", Page:"78", Description:"Find current using Ohms Law")

In> f3~1a := Formula(f3~1, Label: "3.1a", Page: "78", Description: "Find voltage using Ohm's Law", Subject: 'V~V) 
Result: Formula(f3~1, Label:"3.1a", Page:"78", Description:"Find voltage using Ohms Law", Subject: V~V)

In> f3~1b := Formula(f3~1, Label: "3.1b", Description: "Ohm's Law with substituted variable names", Substitutions: ['V~V -> 'V~V, 'R~R -> 'R~R, 'I~I -> 'I~I]) 
Result: Formula(f3~1, Label:"3.1b", Description:"Ohms Law with substituted variable names", Substitutions:[ V~V -> V~V, R~R -> R~R, I~I -> I~I])

*SEE Problem, Formulas, Given, EvaluateFormula


*SOURCE org/mathpiper/scripts4/manual_solving/Formula.mpws
==========
*CMD Formulas --- define formulas in a Problem body

*CALL
        Formulas()

*PARMS


*DESC

Define formulas in a Problem body.


*EXAMPLES
In> Formulas() { formulaName := Formula(z == x + y, Label: "Example Formula"); } 
Result: Formulas() {formulaName := Formula(z == x + y, Label: "Example Formula");}
*SEE Problem, Formula, Given, EvaluateFormula

*SOURCE org/mathpiper/scripts4/manual_solving/Formulas.mpws
==========
*CMD Given --- define values that are given in a Problem body

*CALL
        Given()

*DESC

Define values that are given in a Problem body.

*EXAMPLES
In> Given() { R~R := 10`Ω; I~I := 5`mA; } 
Result: Given() { R~R := 10`Ω; I~I := 5`mA; }
*SEE Problem, Formula, Formulas, EvaluateFormula

*SOURCE org/mathpiper/scripts4/manual_solving/Given.mpws
==========
*CMD Lookup --- define values that are known in a Problem body

*CALL
        Lookup()

*DESC

Define values that are known in a Problem body.

*EXAMPLES
In> Lookup() { percent := 20`%; } 
Result: Lookup() { percent := 20`%;}
*SEE Problem, Formula, Formulas, EvaluateFormula

*SOURCE org/mathpiper/scripts4/manual_solving/Lookup.mpws
==========
*CMD Problem --- the manually entered step-by-step solution to a math problem

*CALL
        Problem(solutionVariables) body

*PARMS

{solutionVariables} -- a list that contains the names of the variables that provide a solution to the problem

{body} -- a code sequence {} that contains the solution to the problem

*DESC

The manually entered step-by-step solution to a math problem.


*SEE Formula, Formulas, Given, EvaluateFormula

*SOURCE org/mathpiper/scripts4/manual_solving/Problem.mpws
==========
*CMD Schematic --- a schematic file in string form

*CALL
        Schematic()

*DESC

A schematic file in string form.



*SEE Problem, Formula, Given, EvaluateFormula

*SOURCE org/mathpiper/scripts4/manual_solving/Schematic.mpws
==========
*CMD Sought --- define values that are sought in a Problem body

*CALL
        Sought()

*DESC

Define values that are sought in a Problem body.


*SEE Problem, Formula, Formulas, EvaluateFormula, Given

*SOURCE org/mathpiper/scripts4/manual_solving/Sought.mpws
==========
*CMD Dx(arg) expression --- Differentiate expression as procedure of arg, or Dx([var,order]) expression
*STD
*CALL
        Dx(arg) expression;

*PARMS

{arg} -- one (unknown) variable
      -- or [unknown,order]
 
*DESC
Differentiate the expression once with respect to arg

*E.G.

/%mathpiper,title="example"
Echo(Dx(_x) Sin(_x));
Dx(_x) Dx(_x) Sin(_x); 
/%/mathpiper
.    /%output,sequence="27",timestamp="2014-04-04 09:31:37.838",preserve="false"
      Result: -Sin(_x)
      
      Side Effects:
      Cos(_x) 
      
.   /%/output

*SOURCE org/mathpiper/scripts4/mpreduce/Doperator.mpws
==========
*CMD Taylor --- a Taylor development of an expression
*STD
*CALL
        Taylor([args]) expression;

*PARMS

{args} -- one ore more triples of variable, where, order
 
*DESC
Taylor carries out the Taylor expansion of an expression in one or more variables.

*E.G.

/%mathpiper,title="some checks"
h:= Taylor([_xx, Pi, 5]) Sin(_xx);
Echo(h);
help1 := Taylor([_xx,1.1,4]) _xx^4;
Echo(help1);
help2 := Expand(help1);
tmp := help2 =? _xx^4 ;
/%/mathpiper

    /%output,sequence="3",timestamp="2014-03-12 07:40:16.333",preserve="false"
      Result: True
      
      Side Effects:
      -(_xx-Pi)+1/6*(_xx-Pi)^3-1/120*(_xx-Pi)^5 
      14641/10000+1331/250*(_xx-11/10)+363/50*(_xx-11/10)^2+22/5*(_xx-11/10)^3+(_xx-11/10)^4 
      
.   /%/output

  
  
    
/%mathpiper,title="multivariate expansion"    
Taylor([_xx,1,8,_y,1.1,6]) Cos(_xx) + _y^6 ;
/%/mathpiper

    /%output,sequence="5",timestamp="2014-03-12 07:41:25.89",preserve="false"
      Result: (1000000*Cos(1)+1771561)/1000000+483153/50000*(_y-11/10)+43923/2000*(_y-11/10)^2+1331/50*(_y-11/10)^3+363/20*(_y-11/10)^4+33/5*(_y-11/10)^5+(_y-11/10)^6-Sin(1)*(_xx-1)-Cos(1)/2*(_xx-1)^2+Sin(1)/6*(_xx-1)^3+Cos(1)/24*(_xx-1)^4-Sin(1)/120*(_xx-1)^5-Cos(1)/720*(_xx-1)^6+Sin(1)/5040*(_xx-1)^7+Cos(1)/40320*(_xx-1)^8
.   /%/output




/%mathpiper,title="change to numerics"
h:= Taylor([_x,1.2,3]) Sin(_x);
Echo(h);
h := NM(h);
h:=Substitute(Sin,SinN)h;
Echo(h);
h:=Substitute(Cos,CosN)h;
Echo(h);
mS(x):= Substitute(_x,x) h;
res:= mS(1);
Echo(res);
Eval(res);
//*/
/%/mathpiper

    /%output,sequence="8",timestamp="2014-03-12 07:44:42.565",preserve="false"
      Result: 0.8414098971
      
      Side Effects:
      Sin(6/5)+Cos(6/5)*(_x-6/5)-Sin(6/5)/2*(_x-6/5)^2-Cos(6/5)/6*(_x-6/5)^3 
      0.932039085967227+0.362357754476674*(_x-1.2)-0.466019542983614*(_x-1.2)^2-0.0603929590794457*(_x-1.2)^3 
      0.932039085967227+0.362357754476674*(_x-1.2)-0.466019542983614*(_x-1.2)^2-0.0603929590794457*(_x-1.2)^3 
      0.932039085967227+0.362357754476674*(1-1.2)-0.466019542983614*(1-1.2)^2-0.0603929590794457*(1-1.2)^3 
      
.   /%/output




/%mathpiper,title=""
h:= Taylor([_x,1.2,3]) Cos(_x)^2;
Procedure("ff",["xx"]) {Eval(Substitute(_x,xx) h);}
Plot2D(ff(_x), 0 :: 3.5);
/%/mathpiper

    /%output,sequence="15",timestamp="2014-03-11 18:46:58.483",preserve="false"
      Result: class org.jfree.chart.ChartPanel
.   /%/output




/%mathpiper,title="plotting example"

t := Taylor([_x,0.2,2]) _x^4;
Echo(t);
nt := NM(t);
Echo(Expand(nt));
Echo(nt);
Procedure("ft",["yy"]) Eval(Substitute(_x,yy) nt);
NumericProcedure("myFT","ft",["xxx"]);
Plot2D([_x^4,myFT(_x)],-1 :: 1);
/%/mathpiper

    /%output,sequence="9",timestamp="2014-03-12 07:45:49.901",preserve="false"
      Result: class org.jfree.chart.ChartPanel
      
      Side Effects:
      1/625+4/125*(_x-1/5)+6/25*(_x-1/5)^2 
      (150*_x^2-40*_x+3)/625 
      0.0016+0.032*(_x-0.2)+0.24*(_x-0.2)^2 
      
.   /%/output




/%mathpiper,title="Ted's propsal to make a procedure suitable for Plot2D"

h:= Taylor([_x,1.2,3]) Sin(_x)^2;
//DBG: Echo(h);
h := NM(h);
h:=Substitute(Sin,SinN)h;
h:=Substitute(Cos,CosN)h;
mS(x):= Substitute(_x,x) h;

mS2(x) := Eval(mS(' 'x)); //There is a space between the ' operators. 
Plot2D(mS2(_x), 0 :: 1.5);
/%/mathpiper

    /%output,sequence="12",timestamp="2014-03-12 07:48:32.723",preserve="false"
      Result: class org.jfree.chart.ChartPanel
.   /%/output

*SOURCE org/mathpiper/scripts4/mpreduce/Taylor.mpws
==========
*CMD Factor -- Factorization of almost anything factorable
*CALL
Factor( expr )
*PARMS
{expr} -- An Integer, Rational number, Gaussian Integer, Polynomial, or Rational Function
*DESC
This procedure factors integers and symbolic polynomials.
    
*EXAMPLES
In> Factor(16940) 
Result: (2^2*5*7*11^2)

In> Factor('(5*_x^7-20*_x^6+25*_x^5-20*_x^4+25*_x^3-20*_x^2+20*_x)) 
Result: 5 * (_x^2 + _x + 1) * (_x^2 - _x + 1) * _x * (_x - 2)^2
 
*SEE Expand


*SOURCE org/mathpiper/scripts4/mpreduce/mpreduce.mpws
==========
*CMD Solve --- solve an equation
*STD
*CALL
        Solve(equ, var)
        Solve([equ1, equ2, ...], [var1, var2])

*PARMS

{equ} -- equation to solve

{var} -- variable to solve for

*DESC

Solves equations.

*EXAMPLES
Solve(_x^2+_x,_x) -> '([_x == 0,_x ==  -1])

Solve([2 * _x + _y == 5, -_x + _y == 2], [_x, _y]) -> [_x == 1,_y == 3]

*SEE Where, AddTo, ==, SolveInequality

*SOURCE org/mathpiper/scripts4/mpreduce/mpreduce.mpws
==========
*CMD SolveInequality --- solve an inequality
*STD
*CALL
        SolveInequality(ineq, var)

*PARMS

{ineq} -- inequality to solve

{var} -- variable to solve for

*DESC

Solves inequalities.

*EXAMPLES
SolveInequality('( (-3*(3*_y-2)^2 + 1) * (-3*_y^2 - 2*_y) <=? 0 ), _y) -> [_y == (-2/3 .. 0),_y == (0.474217 .. 0.859117)]

*SEE Where, AddTo, ==, Solve

*SOURCE org/mathpiper/scripts4/mpreduce/mpreduce.mpws
==========
*CMD Expand --- transform a polynomial to an expanded form
*STD
*CALL
    Expand(expr)

*PARMS

{expr} -- a polynomial expression

*DESC

This command brings a polynomial in expanded form, in which
polynomials are represented in the form 
$c0 + c1*x + c2*x^2 + ... + c[n]*x^n$. In this form, it is easier to test whether a polynomial is
zero, namely by testing whether all coefficients are zero.



*EXAMPLES
In> Expand((1+_x)^5) 
Result: ((((_x^5 + 5*_x^4) + 10*_x^3) + 10*_x^2) + 5*_x) + 1

*SEE Factor

*SOURCE org/mathpiper/scripts4/mpreduce/mpreduce.mpws
==========
*CMD Differentiate --- take derivative of expression with respect to variable
*STD
*CALL
    Differentiate(expression,variable)

*PARMS

{expression} -- expression to take derivatives of

{variable} -- variable


*DESC

This procedure calculates the derivative of the expression {expr} with
respect to the variable {var}

*EXAMPLES
In> Differentiate(_x^2,_x) 
Result: 2*_x

*SEE Integrate, Limit, Equivalent?

*SOURCE org/mathpiper/scripts4/mpreduce/mpreduce.mpws
==========
*CMD Limit --- (try) to compute a limit
*STD
*CALL
    Limit(expression,variable,where)

*PARMS

{expression} -- expression to take a the limit, for  variable -> where

{variable} -- variable

{where} -- value  


*DESC

This procedure calculates the limit of the expression {expr} with
respect to the variable {var} var  to where (number).

*EXAMPLES
In> Limit(_x*Sin(1/_x),_x,3) 
Result: 3 * Sin(1 / 3)

*SEE ForEach, Differentiate, Integrate, Equivalent?

*SOURCE org/mathpiper/scripts4/mpreduce/mpreduce.mpws
==========
*CMD Integrate --- integration

*CALL
    Integrate(expression, variable)
    Integrate(expression, variable, lowerValue, higherValue)

*PARMS

{expression} -- expression to integrate

{variable} -- atom, variable to integrate over

{lowerValue} -- lower value of definite integration

{higherValue} -- higher value of definite integration


*DESC

This procedure integrates the expression {expression} with respect to the
variable {variable}.

*EXAMPLES
In> Integrate(_x^2,_x) 
Result: _x^3/3

In> Integrate(_x^2,_x, 1, 2) 
Result: 7/3

*SEE Differentiate, Limit, Equivalent?

*SOURCE org/mathpiper/scripts4/mpreduce/mpreduce.mpws
==========
*CMD Equivalent? --- determine if one polynomial expression equals another one
*STD
*CALL
    Equivalent?(expr1, expr2)

*PARMS

{expr1} -- a polynomial expression

{expr2} -- a polynomial expression

*DESC
Determine if one polynomial expression equals another one. If the procedure is called
in verbose mode, the difference between the expressions is printed.


*EXAMPLES
In> Equivalent?(2*_a, 2*_a) 
Result: True

In> Equivalent?(2*_a, 3*_a) 
Result: False

*SEE Differentiate, Integrate, Limit

*SOURCE org/mathpiper/scripts4/mpreduce/mpreduce.mpws
==========
*CMD BracketRational --- find optimal rational approximations
*STD
*CALL
        BracketRational(x, eps)

*PARMS

{x} -- a number to be approximated (must be already evaluated to floating-point)

{eps} -- desired precision

*DESC

The procedure {BracketRational(x,eps)} can be used to find approximations 
with a given relative precision from above and from below. This procedure 
returns a list of two rational numbers {[r1,r2]} such that $r1<x<r2$ and 
$Abs(r2-r1)<Abs(x*eps)$. The argument {x} must be already evaluated to 
enough precision so that this approximation can be meaningfully found.
If the approximation with the desired precision cannot be found, the 
procedure returns an empty list.

*E.G.

Find an approximation to $Ln(10)$ good to 8 digits:

In> BracketRational(NM(Ln(10)), 10^(-8))
Result: [12381/5377,41062/17833];


*SEE GuessRational, NearRational, ContFrac, ContFracList, Rationalize

*SOURCE org/mathpiper/scripts4/newly/BracketRational.mpws
==========
*CMD ContFrac --- continued fraction expansion
*STD
*CALL
        ContFrac(x)
        ContFrac(x, depth)

*PARMS

{x} -- number or polynomial to expand in continued fractions

{depth} -- integer, maximum required depth of result

*DESC

This command returns the continued fraction expansion of {x}, which
should be either a floating point number or a polynomial. If
{depth} is not specified, it defaults to 6. The remainder is
denoted by {rest}.

This is especially useful for polynomials, since series expansions
that converge slowly will typically converge a lot faster if
calculated using a continued fraction expansion.

*E.G.

In> UnparseMath2D(ContFrac(NM(Pi)))
        
                     1
        --------------------------- + 3
                   1
        ----------------------- + 7
                1
        ------------------ + 15
              1
        -------------- + 1
           1
        -------- + 292
        rest + 1

Result: True;

In> UnparseMath2D(ContFrac(x^2+x+1, 3))
        
               x
        ---------------- + 1
                 x
        1 - ------------
               x
            -------- + 1
            rest + 1
        
Result: True;

*SEE NM

*SOURCE org/mathpiper/scripts4/newly/ContFrac.mpws
==========
*CMD ContFracList --- manipulate continued fractions
*CMD ContFracEval --- manipulate continued fractions
*STD
*CALL
        ContFracList(frac)
        ContFracList(frac, depth)
        ContFracEval(list)
        ContFracEval(list, rest)

*PARMS

{frac} -- a number to be expanded

{depth} -- desired number of terms

{list} -- a list of coefficients

{rest} -- expression to put at the end of the continued fraction

*DESC

The procedure {ContFracList} computes terms of the continued fraction
representation of a rational number {frac}.  It returns a list of terms 
of length {depth}. If {depth} is not specified, it returns all terms.

The procedure {ContFracEval} converts a list of coefficients into a 
continued fraction expression. The optional parameter {rest} specifies 
the symbol to put at the end of the expansion. If it is not given, the 
result is the same as if {rest=0}.

*E.G.

In> A:=ContFracList(33/7 + 0.000001)
Result: [4,1,2,1,1,20393,40,35]

In> ContFracEval(Take(A, 5))
Result: 33/7;

In> ContFracEval(Take(A,3),_remainder)
Result: 4+1/(1/(_remainder+2)+1);
        
*SEE ContFrac, GuessRational

*SOURCE org/mathpiper/scripts4/newly/ContFracEval.mpws
==========
*CMD ContFracList --- manipulate continued fractions
*CMD ContFracEval --- manipulate continued fractions
*STD
*CALL
        ContFracList(frac)
        ContFracList(frac, depth)
        ContFracEval(list)
        ContFracEval(list, rest)

*PARMS

{frac} -- a number to be expanded

{depth} -- desired number of terms

{list} -- a list of coefficients

{rest} -- expression to put at the end of the continued fraction

*DESC

The procedure {ContFracList} computes terms of the continued fraction
representation of a rational number {frac}.  It returns a list of 
terms of length {depth}. If {depth} is not specified, it returns all terms.

The procedure {ContFracEval} converts a list of coefficients into a 
continued fraction expression. The  optional parameter {rest} specifies 
the symbol to put at the end of the expansion. If it is not given, 
the result is the same as if {rest=0}.

*E.G.

In> A:=ContFracList(33/7 + 0.000001)
Result: [4,1,2,1,1,20409,2,1,13,2,1,4,1,1,3,3,2];

In> ContFracEval(Take(A, 5))
Result: 33/7;

In> ContFracEval(Take(A,3), remainder)
Result: 1/(1/(remainder+2)+1)+4;
        
*SEE ContFrac, GuessRational

*SOURCE org/mathpiper/scripts4/newly/ContFracList.mpws
==========
*CMD Decimal --- decimal representation of a rational
*STD
*CALL
        Decimal(frac)

*PARMS

{frac} -- a rational number

*DESC

This procedure returns the infinite decimal representation of a
rational number {frac}.  It returns a list, with the first element
being the number before the decimal point and the last element the
sequence of digits that will repeat forever. All the intermediate list
elements are the initial digits before the period sets in.

*E.G.

In> Decimal(1/22)
Result: [0,0,[4,5]];

In> NM(1/22,30)
Result: 0.045454545454545454545454545454;

*SEE NM

*SOURCE org/mathpiper/scripts4/newly/Decimal.mpws
==========
*CMD FreeOf? --- test whether expression depends on variable
*STD
*CALL
        FreeOf?(var, expr)
        FreeOf?([var, ...], expr)

*PARMS

{expr} -- expression to test

{var} -- variable to look for in "expr"

*DESC

This procedure checks whether the expression "expr" (after being
evaluated) depends on the variable "var". It returns {False} if this 
is the case and {True} otherwise.

The second form test whether the expression depends on <i>any</i> of
the variables named in the list. The result is {True} if none of the 
variables appear in the expression and {False} otherwise.

*E.G. PKHG 11-11-2-13 changes _ before variables

In> FreeOf?(_x, Sin(_x));
Result: False;

In> FreeOf?(_y, Sin(_x));
Result: True;

In> FreeOf?(_x, Differentiate( _a*_x+_b,_x));
Result: True;

In> FreeOf?([_x,_y], Sin(_x));
Result: False;

The third command returns [True] because the
expression [Differentiate( _a*_x+_b,_x)] evaluates to [_a], which does not depend on [_x].

*SEE Contains?

*SOURCE org/mathpiper/scripts4/newly/FreeOf_.mpws
==========
*CMD GuessRational --- find optimal rational approximations
*STD
*CALL
        GuessRational(x)
        GuessRational(x, digits)

*PARMS

{x} -- a number to be approximated (must be already evaluated to floating-point)

{digits} -- desired number of decimal digits (integer)

*DESC

The procedures {GuessRational(x)} and {NearRational(x)} attempt to find "optimal"
rational approximations to a given value {x}. The approximations are "optimal"
in the sense of having smallest numerators and denominators among all rational
numbers close to {x}. This is done by computing a continued fraction
representation of {x} and truncating it at a suitably chosen term.  Both
procedures return a rational number which is an approximation of {x}.

Unlike the procedure {Rationalize()} which converts floating-point numbers to
rationals without loss of precision, the procedures {GuessRational()} and
{NearRational()} are intended to find the best rational that is <i>approximately</i>
equal to a given value.

The procedure {GuessRational()} is useful if you have obtained a
floating-point representation of a rational number and you know
approximately how many digits its exact representation should contain.
This procedure takes an optional second parameter {digits} which limits
the number of decimal digits in the denominator of the resulting
rational number. If this parameter is not given, it defaults to half
the current precision. This procedure truncates the continuous fraction
expansion when it encounters an unusually large value (see example).
This procedure does not always give the "correct" rational number; a
rule of thumb is that the floating-point number should have at least as
many digits as the combined number of digits in the numerator and the
denominator of the correct rational number.

*E.G.

Start with a rational number and obtain a floating-point approximation:

In> x:=NM(956/1013)
Result: 0.9437314906

In> Rationalize(x)
Result: 4718657453/5000000000;

In> Verbose(GuessRational(x))
        
        GuessRational: using 10 terms of the  continued fraction
Result: 956/1013;

In> ContFracList(x)
Result: [0,1,16,1,3,2,1,1,1,1,508848,3,1,2,1,2,2];

*SEE BracketRational, NearRational, ContFrac, ContFracList, Rationalize

*SOURCE org/mathpiper/scripts4/newly/GuessRational.mpws
==========
*CMD NearRational --- find optimal rational approximations
*STD
*CALL
    NearRational(x)
    NearRational(x, digits)
    NearRational(z)
    NearRational(z, digits)

*PARMS

{x} -- a number to be approximated (must be already evaluated to floating-point)
{z} -- a complex number to be approximated (Re and Im as above)

{digits} -- desired number of decimal digits (integer)

*DESC

The procedures {GuessRational(x)} and {NearRational(x)} attempt to find "optimal"
rational approximations to a given value {x}. The approximations are "optimal"
in the sense of having smallest numerators and denominators among all rational
numbers close to {x}. This is done by computing a continued fraction
representation of {x} and truncating it at a suitably chosen term.  Both
procedures return a rational number which is an approximation of {x}.

Unlike the procedure {Rationalize()} which converts floating-point numbers to
rationals without loss of precision, the procedures {GuessRational()} and
{NearRational()} are intended to find the best rational that is <i>approximately</i>
equal to a given value.

The procedure {NearRational(x)} is useful if one needs to
approximate a given value, i.e. to find an "optimal" rational number
that lies in a certain small interval around a certain value {x}. This
procedure takes an optional second parameter {digits} which has slightly
different meaning: it specifies the number of digits of precision of
the approximation; in other words, the difference between {x} and the
resulting rational number should be at most one digit of that
precision. The parameter {digits} also defaults to half of the current
precision.

*E.G.

Start with a rational number and obtain a floating-point approximation:

In> x:=NM(956/1013)
Result: 0.9437314906

In> Rationalize(x)
Result: 4718657453/5000000000;
The first 10 terms of this continued fraction correspond to the correct 
continued fraction for the original rational number.

In> NearRational(x)
Result: 218/231;

This procedure found a different rational number closeby because the precision was not high enough.
In> NearRational(x, 10)
Result: 956/1013;

*SEE BracketRational, GuessRational, ContFrac, ContFracList, Rationalize

*SOURCE org/mathpiper/scripts4/newly/NearRational.mpws
==========
*CMD NewLine --- print one or more newline characters
*STD
*CALL
        NewLine()
        NewLine(nr)

*PARMS

{nr} -- the number of newline characters to print

*DESC

The command {NewLine()} prints one newline character
on the current output. The second form prints "nr" newlines on the
current output. The result is always True.

*E.G. notest

In> NewLine();
        
Result: True;

*SEE Echo, Write, Space

*SOURCE org/mathpiper/scripts4/newly/NewLine.mpws
==========
*CMD Nl --- the newline character
*STD
*CALL
        Nl()
        Nl(count))

{count} -- the number of newline characters to print

*DESC

The zero argument version of this procedure returns a string with one 
newline character in it. The argument {count} indicates the number of
newline characters to place in the returned string.

Note that the second letter in the name of this command is a lower
case {L} (from "line").

*E.G. notest

In> WriteString("First line" + Nl() + "Second line");
Result: True
Side Effects:
First line
Second line


In> WriteString("First line" + Nl(2) + "Second line");
Result: True
Side Effects:
First line

Second line

*SEE NewLine

*SOURCE org/mathpiper/scripts4/newly/Nl.mpws
==========
*CMD ReversePoly --- solve $h(f(x)) = g(x) + O(x^n)$ for $h$
*STD
*CALL
        ReversePoly(f, g, var, newvar, degree)

*PARMS

{f}, {g} -- procedures of "var"

{var} -- a variable

{newvar} -- a new variable to express the result in

{degree} -- the degree of the required solution

*DESC

This procedure returns a polynomial in "newvar", say "h(newvar)",
with the property that "h(f(var))" equals "g(var)" up to order
"degree". The degree of the result will be at most "degree-1". The
only requirement is that the first derivative of "f" should not be zero.

This procedure is used to determine the Taylor series expansion of the
inverse of a function "f": if we take "g(var)=var", then
"h(f(var))=var" (up to order "degree"), so "h" will be the
inverse of "f".

*E.G.

In> f(x):=Eval(Expand((1+x)^4))
Result: True;

In> g(x) := x^2
Result: True;

In> h(y):=Eval(ReversePoly(f(x),g(x),x,y,8))
Result: True;

In> BigOh(h(f(x)),x,8)
Result: x^2;

In> h(x)
Result: (-2695*(x-1)^7)/131072+(791*(x-1)^6)
        /32768 +(-119*(x-1)^5)/4096+(37*(x-1)^4)
        /1024+(-3*(x-1)^3)/64+(x-1)^2/16;

*SEE Taylor

*SOURCE org/mathpiper/scripts4/newly/ReversePoly.mpws
==========
*CMD Space --- print one or more spaces
*STD
*CALL
        Space()
        Space(nr)

*PARMS

{nr} -- the number of spaces to print

*DESC

The command {Space()} prints one space on the
current output. The second form prints {nr} spaces on the current
output. The result is always True.

*E.G. notest

In> Space(5);
             Result: True;

*SEE Echo, Write, NewLine

*SOURCE org/mathpiper/scripts4/newly/Space.mpws
==========
*CMD UniqueConstant --- create a unique identifier
*STD
*CALL
        UniqueConstant()

*DESC

This procedure returns a unique constant atom each time you call
it. The atom starts with a C character, and a unique number is
appended to it.

*E.G.

In> UniqueConstant()
Result: C9

In>  UniqueConstant()
Result: C10

*SEE LocalSymbols

*SOURCE org/mathpiper/scripts4/newly/UniqueConstant.mpws
==========
*CMD WithValue --- temporary assignment during an evaluation
*STD
*CALL
        WithValue(var, val, expr)
        WithValue([var,...], [val,...], expr)

*PARMS

{var} -- variable to assign to

{val} -- value to be assigned to "var"

{expr} -- expression to evaluate with "var" equal to "val"

*DESC

First, the expression "val" is assigned to the variable
"var". Then, the expression "expr" is evaluated and
returned. Finally, the assignment is reversed so that the variable
"var" has the same value as it had before {WithValue} was evaluated.

The second calling sequence assigns the first element in the list of
values to the first element in the list of variables, the second value
to the second variable, etc.

*E.G.

In> WithValue(x, 3, x^2+y^2+1);
Result: y^2+10;

In> WithValue([x,y], [3,2], x^2+y^2+1);
Result: 14;

*SEE Substitute, /:, Where

*SOURCE org/mathpiper/scripts4/newly/WithValue.mpws
==========
*CMD IntLog --- integer part of logarithm
*STD
*CALL
        IntLog(n, base)

*PARMS

{n}, {base} -- positive integers

*DESC

{IntLog} calculates the integer part of the logarithm of {n} 
in base {base}. The algorithm uses only integer  math and may 
be faster than computing $$Ln(n)/Ln(base)$$ with multiple 
precision floating-point math and rounding off to get the integer part.

This procedure can also be used to quickly count the digits in a given number.

*E.G.
Count the number of bits:

In> IntLog(257^8, 2)
Result: 64;

Count the number of decimal digits:

In> IntLog(321^321, 10)
Result: 804;

*SEE Quotient, Modulo, Ln

*SOURCE org/mathpiper/scripts4/numbers/IntLog.mpws
==========
*CMD NextPrime --- generate a prime following a number
*STD
*CALL
        NextPrime(i)

*PARMS

{i} -- integer value

*DESC

The procedure finds the smallest prime number that is greater than the given
integer value.

The routine generates "candidate numbers" using the formula $n+2*Modulo(-n,3)$
where $n$ is an odd number (this generates the sequence 5, 7, 11, 13, 17,
19, ...) and {Prime?()} to test whether the next candidate number is in
fact prime.

*E.G.
In> NextPrime(5)
Result: 7;

*SEE Prime?

*SOURCE org/mathpiper/scripts4/numbers/NextPrime.mpws
==========
*CMD NthRoot --- calculate/simplify nth root of an integer
*STD
*CALL
        NthRoot(m,n)

*PARMS

{m} -- a non-negative integer ($m>0$)

{n} -- a positive integer greater than 1 ($n>1$)

*DESC

{NthRoot(m,n)} calculates the integer part of the $n$-th root $m^{1/n}$ and
returns a list {[f,r]}. {f} and {r} are both positive integers
that satisfy $f^n*r$=$m$.
In other words, $f$ is the largest integer such that $m$ divides $f^n$ and 
$r$ is the remaining factor.

For large {m} and small {n}
{NthRoot} may work quite slowly. Every result {[f,r]} for given
{m}, {n} is saved in a lookup table, thus subsequent calls to
{NthRoot} with the same values {m}, {n} will be executed quite
fast.

*E.G.
In> NthRoot(12,2)
Result: [2,3];

In> NthRoot(81,3)
Result: [3,3];

In> NthRoot(3255552,2)
Result: [144,157];

In> NthRoot(3255552,3)
Result: [12,1884];

*SEE PowerN

*SOURCE org/mathpiper/scripts4/numbers/NthRoot.mpws
==========
*CMD NumberToRep --- returns a List showing MathPiper's internal representation of a number
*STD
*CALL
        NumberToRep(number)
        
*PARMS

{number} -- an Integer, Decimal, or Complex number


*DESC

Internally, MathPiper represents {arbitrary precision} numbers as Java BigIntegers or
BigDecimals.  Java code handles calculations using such numbers.

All the information needed to correctly understand the precision attached to a number,
and the rounding and comparison thereof, is contained in the Java structure.

For a Decimal number (essentially anything with a decimal point), the representation
consists of an arbitrary-precision integer containing {all} the significant digits of
the number, and a {scale factor} telling where the implied decimal point is supposed to
be placed with respect to the end of the integer.  The {precision} of the number is
just the number of digits in the integer.

The three components of the List returned for a decimal number are, respectively,
{[BigInteger (unscaled), Precision, ScaleFactor]}.
Note that the second of these is redundent: only the BigInteger and the ScaleFactor
are needed to completely define the number.

For an Integer number, the integer is its own representation, and again, the number of
its digits gives its precision.

For a Complex number, this procedure returns a List containing the representations of
the Real and Imaginary parts of the number.

The best way to {consistently} deal with precision and rounding issues is by making use
of the information given by this procedure.

*E.G.
    

In> NumberToRep(123.45678)
Result: [12345678,8,5]
    

In> NumberToRep(34700)
Result: [34700,5]
    

In> NumberToRep(1.5+6.75*I)
Result: [[150,3,2],[675,3,2]]
    

In> NumberToRep(123.45678E-10)
Result: [12345678,8,15]
   

In> NumberToRep(123.45678E+10)
Result: [12345678,8,-5]
    
NOTICE that the first, fourth, and fifth of these have the same 
BigInteger representation, and hence the same precision, namely 8.  
The ScaleFactor tells how many places the decimal point must be 
moved [leftward] from the [end] of the integer.  A negative 
ScaleFactor says to move the decimal point to the right -- 
i.e., effectively, add terminal zeros. However, if the number had 
originally been written as 1234567800000., it would actually have
a different representation, namely [1234567800000,13,0].  That is
because, if we write those terminal zeros explicitly, they are assumed
to be "significant", and so the number is shown with precision 13.
Exponential notation must be used if the precision really is 8.

*SEE RepToNumber, DumpNumber

*SOURCE org/mathpiper/scripts4/numbers/NumberToRep.mpws
==========
*CMD PrimePower? --- test for a power of a prime number
*STD
*CALL
        PrimePower?(n)

*PARMS

{n} -- integer to test

*DESC

This command tests whether "n", which should be a positive integer,
is a prime power, that is whether it is of the form $p^m$, with
"p" prime and "m" an integer.

This procedure does not try to decompose the number $n$ into factors.
Instead we check for all prime numbers $r=2$, $3$, ... that the $r$-th root of $n$ is an integer, and we find such $r$ and $m$ that $n=m^r$, we check that $m$ is a prime. If it is not a prime, we execute the same procedure call on $m$.

*E.G.

In> PrimePower?(9)
Result: True;

In> PrimePower?(10)
Result: False;

In> Select(1 .. 50, "PrimePower?")
Result: [2,3,4,5,7,8,9,11,13,16,17,19,23,25,27,
          29,31,32,37,41,43,47,49];

*SEE Prime?

*SOURCE org/mathpiper/scripts4/numbers/PrimePower_.mpws
==========
*CMD Prime? --- test for a prime number
*CMD SmallPrime? --- test for a (small) prime number
*STD
*CALL
        Prime?(n)
        SmallPrime?(n)

*PARMS

{n} -- integer to test

*DESC

The commands checks whether $n$, which should be a positive integer,
is a prime number. A number $n$ is a prime number if it is only divisible
by 1 and itself. As a special case, 1 is not considered a prime number.
The first prime numbers are 2, 3, 5, ...

The procedure {IsShortPrime} only works for numbers $n<=65537$ but it is very fast.

The procedure {Prime?} operates on all numbers and uses different algorithms 
depending on the magnitude of the number $n$.For small numbers $n<=65537$, 
a constant-time table lookup is performed.(The procedure {IsShortPrime} is used 
for that.)For numbers $n$ between $65537$ and $34155071728321$, the procedure 
uses the Rabin-Miller test together with table lookups to guarantee correct results.

For even larger numbers a version of the probabilistic Rabin-Miller test is executed.
The test can sometimes mistakenly mark a number as prime while it is in fact composite, 
but a prime number will never be mistakenly declared composite. The parameters of the 
test are such that the probability for a false result is less than $10^{-24}$.

*E.G.

In> Prime?(1)
Result: False;

In> Prime?(2)
Result: True;

In> Prime?(10)
Result: False;

In> Prime?(23)
Result: True;

In> Select(1 .. 100, "Prime?")
Result: [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,
          53,59,61,67,71,73,79,83,89,97];

*SEE PrimePower?

*SOURCE org/mathpiper/scripts4/numbers/Prime_.mpws
==========
*CMD Rationalize --- convert floating point numbers to fractions
*STD
*CALL
        Rationalize(expr)

*PARMS

{expr} -- an expression containing real numbers

*DESC

This command converts every real number in the expression "expr"
into a rational number. This is useful when a calculation needs to be
done on floating point numbers and the algorithm is unstable.
Converting the floating point numbers to rational numbers will force
calculations to be done with infinite precision (by using rational
numbers as representations).

It does this by finding the smallest integer $n$ such that multiplying
the number with $10^n$ is an integer. Then it divides by $10^n$ again,
depending on the internal gcd calculation to reduce the resulting
division of integers.

*E.G.
    

In> Rationalize(-1.2)
Result: (-6)/5

In> Rationalize(1.3+7.43*x)
Result: 743/100*x+13/10

In> [1.2,3.123,4.5]
Result: [1.2,3.123,4.5];

In> Rationalize(%)
Result: [6/5,3123/1000,9/2];

*SEE Rational?


*SOURCE org/mathpiper/scripts4/numbers/Rationalize.mpws
==========
*CMD RepToNumber --- Given a List representing a number as MathPiper stores it, returns the number
*STD
*CALL
        RepToNumber(rep)
        
*PARMS

{rep} -- A list representing MathPiper's internal structure for a number


*DESC

This procedure returns a Decimal, Integer, or Complex number, when given a data
structure containing MathPiper's internal representation of the number.

Internally, MathPiper represents {arbitrary precision} numbers as Java BigIntegers or
BigDecimals.  Java code handles calculations using such numbers.

All the information needed to correctly understand the precision attached to a number,
and the rounding and comparison thereof, is contained in the Java structure.

For a Decimal number (essentially anything with a decimal point), the representation
consists of an arbitrary-precision integer containing {all} the significant digits of
the number, and a {scale factor} telling where the implied decimal point is supposed to
be placed with respect to the end of the integer.  The {precision} of the number is
just the number of digits in the integer.

The three components of the List representing a decimal number are, respectively,
{{BigInteger (unscaled), Precision, ScaleFactor}}.
Note that the second of these is redundent: only the BigInteger and the ScaleFactor
are needed to completely define the number.

For an Integer number, the integer is its own representation, and again, the number of
its digits gives its precision, but the representation is still a list, with the number
as first component and its precision as second.

For a Complex number, the representation is a List of Lists,
containing the representations of the Real and Imaginary parts of the number.

The best way to {consistently} deal with precision and rounding issues is by making use
of the information given by the representation (or "rep" for short).

*E.G.

In> RepToNumber([12345678,8,5])
Result: 123.45678


In> RepToNumber([34700,5])
Result: 34700


In> RepToNumber([[150,3,2],[675,3,2]])
Result: Complex(1.50,6.75)


In> RepToNumber([12345678,8,15])
Result: 0.000000012345678   :   BETTER WOULD BE 123.45678E-10


In> RepToNumber([12345678,8,-5])
Result: 1234567800000       :   BETTER WOULD BE 123.45678E+10
    
*SEE NumberToRep, DumpNumber

*SOURCE org/mathpiper/scripts4/numbers/RepToNumber.mpws
==========
*CMD RoundToPlace --- Rounds or Sets a number to the specified "decimal place"
*STD
*CALL
        RoundToPlace(number,place)
*PARMS
{number} -- a number (Decimal, Integer, or Complex) whose precision is to be changed
{place}  -- the decimal place to which to round


*DESC
This procedure rounds an {arbitrary-precision number} (A.P.N.) to the given
decimal place.  The variable {place} is an integer counting from the current
position of the decimal point in {number}.  If {place} is positive, the
number will be rounded to the position that many places to the right of
the current decimal point.  If {place} is negative, the number will be rounded
to the position that many places to the left of the current decimal point. 

The examples shown below will hopefully clarify the above description.

See the documentation for the related procedure {RoundToPrecision} for a
detailed description of the way MathPiper internally represents A.P.N.s.

NOTE:  It is important to recognize the distinction (often misused or misunderstood)
between rounding "to a specified decimal place" (which this procedure does) and 
rounding "to a specified precision", which in MathPiper is accomplished by
the procedure {RoundToPrecision} (q.v.).  

For Decimal numbers and Decimal Complex numbers, the concept of Rounding to a 
given decimal place to the left or right of the current decimal point is well 
understood. It makes no sense to try to round further to the left than the first 
digit of the number, and this procedure will return zero if you try.  To "round"
further to the right than the last decimal place of the number just adds 
trailing zeros.

For Integers and Complex Integers (Gaussian Integers), the concept of
Rounding to a decimal position {within} the integer (place < 0 ) makes sense,
and will be accomplished by this procedure.  Digits between the rounding digit
and the end of the integer will be replaced by zeros. 
However, it makes no sense to try to round an integer to a decimal place
{outside} the integer, and this procedure will return unevaluated if place > 0.

*E.G.

In> dec:=123.45678
Result: 123.45678
    

In> dec2:=RoundToPlace(dec,1)
Result: 123.5
    

In> dec3:=RoundToPlace(dec,-1)
Result: 120
    

In> dec3:=RoundToPlace(dec,-4)
Result: 0.
    

In> dec3:=RoundToPlace(dec,6)
Result: 123.456780
    

In> int:=12345678
Result: 12345678
    

In> int2:=RoundToPlace(int,-2)
Result: 12345700
    

In> int2:=RoundToPlace(int,2)
Result: RoundToPlace(12345678,2)

*SEE RoundToPrecision, RoundToN, NumberToRep, DumpNumber

*SOURCE org/mathpiper/scripts4/numbers/RoundToPlace.mpws
==========
*CMD RoundToPrecision --- Rounds or Sets a number to the specified precision
*STD
*CALL
        RoundToPrecision(number,precision)
*PARMS
{number} -- a number (Decimal, Integer, or Complex) whose precision is to be changed
{precision} -- the new precision to be used


*DESC
This procedure changes the precision of an {arbitrary-precision number} (A.P.N.).
If the new precision is less than the original precision, the {significand}
will be appropriately rounded.  If the new precision is greater than the 
original precision, terminal zeros will be appended to the {significand}
and the indicated precision will be reset accordingly.

Internally, MathPiper represents an A.P.N. as Java a BigIntegers or
BigDecimal.  Java code handles calculations using such numbers.

All the information needed to correctly understand the precision attached to a number,
and the rounding and comparison thereof, is contained in the Java structure.

For a Decimal number (essentially anything with a decimal point), the representation
consists of an arbitrary-precision integer (called the {significand}) containing {all}
the significant digits of the number, and a {scale factor} telling where the implied 
decimal point is supposed to be placed with respect to the end of this integer.  
The {precision} of the number is usually just the number of digits in the 
{significand}.

The three components of the List representing a decimal number are, respectively,
{{BigInteger (unscaled), Precision, ScaleFactor}}.
Note that the second of these is redundent: only the BigInteger and the ScaleFactor
are needed to completely define the number.  The name 'BigInteger' is Java's
terminology for the {significand}.

For an Integer number, the integer is its own significand, and again, the number of
its digits gives its precision.  The representation is still a list, with the number
as first component and its precision as second.

For a Complex number, the representation is a List of Lists,
containing the representations of the Real and Imaginary parts of the number.

The best way to {consistently} deal with precision and rounding issues is by making use
of the information given by the representation (or "rep" for short)..

NOTE:  It is important to recognize the distinction (often misused or misunderstood)
between rounding "to a specified precision" (which this procedure does) and rounding
"to a specified number of decimal places", which in MathPiper is accomplished by
the procedure {RoundToPlace} (q.v.).  

For Decimal numbers and Decimal Complex numbers, the concept of Rounding DOWN to a 
given precision is well understood, and the concept of Rounding UP is pretty
clear also.  

However, for Integers and Complex Integers (Gaussian Integers), the
concept of Rounding down is somewhat obscure, and the concept of Rounding up 
makes very little sense at all.  An 8-digit integer, when rounded DOWN to 5
digits of precision, remains an 8-digit integer still, but the last 3 digits
have become zeros; the original number is still approximated by the new one.
But an 8-digit integer, when rounded UP to 10 digits of precision, has
two trailing zeros appended to it.  In the latter case, the new integer is
arguably not any kind of approximation of the old one.  

On the whole, it is probably best NOT to round integers UP.

*E.G.

In> dec:=123.45678
Result: 123.45678

In> NumberToRep(dec)
Result: [12345678,8,5]


In> dec2:=RoundToPrecision(dec,5)
Result: 123.46

In> NumberToRep(dec2)
Result: [12346,5,2]


In> dec3:=RoundToPrecision(dec,10)
Result: 123.4567800

In> NumberToRep(dec3)
Result: [1234567800,10,7]


In> cmplx:=12.345-I*567.891
Result: Complex(12.345,-567.891)

In> NumberToRep(cmplx)
Result: [[12345,5,3],[-567891,6,3]]


In> cmplx2:=RoundToPrecision(cmplx,4)
Result: Complex(12.34,-567.9)

In> NumberToRep(cmplx2)
Result: [[1234,4,2],[-5679,4,1]]


In> cmplx3:=RoundToPrecision(cmplx,8)
Result: Complex(12.345000,-567.89100)

In> NumberToRep(cmplx3)
Result: [[12345000,8,6],[-56789100,8,5]]


In> int:=12345678
Result: 12345678

In> NumberToRep(int)
Result: [12345678,8]


In> int2:=RoundToPrecision(int,5)
Result: 12346000

In> NumberToRep(int2)
Result: [12346000,8]


In> int3:=RoundToPrecision(int,10)
Result: 1234567800

In> NumberToRep(int3)
Result: [1234567800,10]
*SEE RoundToPlace, RoundToN, NumberToRep, DumpNumber

*SOURCE org/mathpiper/scripts4/numbers/RoundToPrecision.mpws
==========
*CMD Prime? --- test for a prime number
*CMD SmallPrime? --- test for a (small) prime number
*STD
*CALL
        Prime?(n)
        SmallPrime?(n)

*PARMS

{n} -- integer to test

*DESC

The commands checks whether $n$, which should be a positive integer,
is a prime number. A number $n$ is a prime number if it is only divisible
by 1 and itself. As a special case, 1 is not considered a prime number.
The first prime numbers are 2, 3, 5, ...

The procedure {IsShortPrime} only works for numbers $n<=65537$ but it is very fast.

The procedure {Prime?} operates on all numbers and uses different algorithms 
depending on the magnitude of the number $n$.
For small numbers $n<=65537$, a constant-time table lookup is performed.
(The procedure {IsShortPrime} is used for that.)
For numbers $n$ between $65537$ and $34155071728321$, the procedure uses the 
Rabin-Miller test together with table lookups to guarantee correct results.

For even larger numbers a version of the probabilistic Rabin-Miller test is executed.
The test can sometimes mistakenly mark a number as prime while it is in fact 
composite, but a prime number will never be mistakenly declared composite.
The parameters of the test are such that the probability for a false result is less than $10^(-24)$.

*E.G.

In> Prime?(1)
Result: False;

In> Prime?(2)
Result: True;

In> Prime?(10)
Result: False;

In> Prime?(23)
Result: True;

In> Select(1 .. 100, "Prime?")
Result: [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,
          53,59,61,67,71,73,79,83,89,97];

*SEE PrimePower?

*SOURCE org/mathpiper/scripts4/numbers/SmallPrime_.mpws
==========
*CMD GaussianGcd --- greatest common divisor in Gaussian integers
*STD
*CALL
        GaussianGcd(z,w)

*PARMS

{z}, {w} -- Gaussian integers 

*DESC

This procedure returns the greatest common divisor, in the ring of Gaussian
integers, computed using Euclid's algorithm. Note that in the Gaussian
integers, the greatest common divisor is only defined up to a Gaussian unit factor.

*E.G.

In> GaussianGcd(2+I,5)
Result: Complex(2,1);
The GCD of two mutually prime Gaussian integers might come out to be equal to some Gaussian unit instead of $1$:

In> GaussianGcd(2+I,3+I)
Result: -1;

*SEE Gcd, Lcm

*SOURCE org/mathpiper/scripts4/numbers/gaussianintegers/GaussianGcd.mpws
==========
*CMD GaussianInteger? ---  test for a Gaussian integer
*STD
*CALL
        GaussianInteger?(z)
*PARMS

{z} -- a complex or real number        

*DESC

This procedure returns {True} if the argument is a Gaussian integer and {False} otherwise.
A Gaussian integer is a generalization
of integers into the complex plane. A complex number $a+b*I$ is a Gaussian
integer if and only if $a$ and $b$ are integers.

*E.G.
In> GaussianInteger?(5)
Result: True;

In> GaussianInteger?(5+6*I)
Result: True;

In> GaussianInteger?(1+2.5*I)
Result: False;


*SOURCE org/mathpiper/scripts4/numbers/gaussianintegers/GaussianInteger_.mpws
==========

*CMD DirectoryCreate --- Creates a directory

*CALL DirectoryCreate(pathOrFile)
        

*PARMS 
{pathOrFile} -- The path of the directory that is to be deleted or a Java 'File' object.

*DESC
This procedure creates the specified directory. It returns "True" if the specified directory
was created or "False" if it was not created.

*E.G.
In> DirectoryCreate("/home/temp_dir")
Result: True

*SOURCE org/mathpiper/scripts4/optional/files/DirectoryCreate.mpws
==========

*CMD DirectoryDelete --- Deletes a directory

*CALL DirectoryDelete(fileOrPath)
        

*PARMS 
{fileOrPath} -- The path of the directory that is to be deleted or a Java 'File' object.

*DESC
This procedure deletes the specified directory. It returns "True" if the specified directory
was deleted or "False" if it was not deleted.

*E.G.
In> DirectoryDelete("/home/temp_dir")
Result: True

*SOURCE org/mathpiper/scripts4/optional/files/DirectoryDelete.mpws
==========

*CMD DirectoryFiles --- Returns a list of all the files in a directory.

*CALL DirectoryFiles(filename)
        

*PARMS 
{filename} -- The filename that you enter.

*DESC
This procedure returns a list of all the files in a directory.

*E.G.
In> DirectoryFiles("/")
Result: [class java.io.File,class java.io.File,class java.io.File]

*SOURCE org/mathpiper/scripts4/optional/files/DirectoryFiles.mpws
==========

*CMD File --- Returns a new Java File object.
*CALL File(filename)

*PARMS 
{filename} -- The filename that you enter.

*DESC
This procedure returns a new Java File object.

*E.G.
In> File("/testFile.txt")
Result: class java.io.File

*SOURCE org/mathpiper/scripts4/optional/files/File.mpws
==========
*CMD FileClose --- closes an open file
*CALL
        FileClose(file)

*PARMS
{file} --  file object

*DESC
This procedure accepts a file object, if that file objec thas been previously opened the procedure will close it.

*E.G.
FileClose(<file object>)

*SOURCE org/mathpiper/scripts4/optional/files/FileClose.mpws
==========
*CMD FileExists? --- tests file to determine if it exists

*CALL
    FileExists?(filename)
    
*PARMS
{filename} -- a file used to be tested

*DESC
This procedure returns as true or false in determining whether a file exists or not.

*E.G.
In> FileExists?(<filename>)

*SOURCE org/mathpiper/scripts4/optional/files/FileExists_.mpws
==========
*CMD FileReaderOpen --- opens a file
*CALL
        FileReaderOpen(fileName)

*PARMS
{fileName} -- a string of the full path to the file

*DESC
This procedure opens a file. The full path to the file must be passed in as an argument.

*E.G.
FireReaderOpen("<filename")

*SOURCE org/mathpiper/scripts4/optional/files/FileReaderOpen.mpws
==========
*CMD FileWriterOpen --- opens a file
*CALL
        FileWriterOpen(filename)
        FileWriterOpen(filename, append?)

*PARMS
filename --- the full path of a file in a string
append? --- "True" means append to the file if it exists, and "False" means replace the file if it exists.

*DESC
This procedure opens a file for writing. The full path of the file must be given.

*E.G.
In> FileWriterOpen("<filename>")

*SOURCE org/mathpiper/scripts4/optional/files/FileWriterOpen.mpws
==========
*CMD  ReadLine --- returns the next line of a file as a string
*CALL
        ReadLine(reader)

*PARMS
{reader} -- a reader

*DESC
Returns the next line of the file as a string or False if the end of the file was reached.

*E.G.
ReadLine(<reader object>)

*SOURCE org/mathpiper/scripts4/optional/files/ReadLine.mpws
==========
*CMD  ReadLines --- returns the lines of a text file as a list of strings
*CALL
        ReadLines(filename)
        ReadLines(reader)

*PARMS
{filename} -- a string that contains the name of a file

{reader} -- a reader

*DESC
This procedure returns the lines of a text file as a list of strings. The full path of the
file must be provided if the version of the procedure that accepts a filename is used.

*E.G.
ReadLines("testfile.txt")

*SOURCE org/mathpiper/scripts4/optional/files/ReadLines.mpws
==========
*CMD StringFromFile --- reads in a text file as a string
*CALL
        StringFromFile(path)

*PARMS
{path} -- the path of the file as a string

*DESC
This procedure reads in a text file as a string.

*E.G.
In> StringFromFile("filename")

*SOURCE org/mathpiper/scripts4/optional/files/StringFromFile.mpws
==========
*CMD StringToFile --- creates a file from the contents a string
*CALL
        StringToFile(path)

*PARMS
{string} -- the string to write to a file
{path} -- the path of the file as a string

*DESC
This procedure writes the contents of a string into a file.

*E.G.
In> StringToFile("Hello", "./tmp")

*SOURCE org/mathpiper/scripts4/optional/files/StringToFile.mpws
==========
*CMD SystemExecute --- executes a command in the system

*CALL
    SystemExecute(command)
        SystemExecute(command, environment, directory, waitFor?)

*PARMS
{command} -- a list of strings that contains the command to execute along with its arguments

{environment} -- a list that contains the environment to execute the command in

{directory} -- directory to execute the command in

{waitFor?} -- when True waits for the command to finish executing before returning

*DESC
This procedure executes a command in a system shell.

*E.G.
SystemExecute(["ls", "-la"])


*SOURCE org/mathpiper/scripts4/optional/files/SystemExecute.mpws
==========

*CMD WriteLine --- writes a line to the
*CALL
        WriteLine(writer, line)

*PARMS
{writer} -- 

{line} -- line to add to specified file

*DESC
This procedure writes a line to a program.

*E.G.
In> WriteLine("Some text.");


*SOURCE org/mathpiper/scripts4/optional/files/WriteLine.mpws
==========
*CMD BrowserOpen --- opens a URI in the system's default browser

*CALL
        BrowserOpen(uri)

*PARMS

{uri} -- the URI of a resource to open

*DESC

This procedure opens a URI in the system's default browser.

*E.G.

In> BrowserOpen("http://www.mathpiper.org")
Result: True

In> BrowserOpen("mailto:example@example.com")
Result: True


*SOURCE org/mathpiper/scripts4/optional/misc/BrowserOpen.mpws
==========
*CMD ViewTreeParts --- Displays a Java GUI component containing an expression in tree form.

*CALL
    ViewTreeParts(expression)

    ViewTreeParts(expression, option, option, ...)


*PARMS

{expression} -- an expression (which may be in string form) to display as an expression tree

{options}:

{Scale} -- Alters the scale of the tree. (Defaults to 2.0)

{FontSize} -- Alters the size of the font. (Defaults to 30.0)

{NodeHighlight} -- Highlights a node with a specified tree path. (Path is a string with each node position separated by a comma)

{ShowDepths} -- If set to True, displays each node's distance from the root node of the tree.

{ShowPositions} -- If set to True, displays each branch's position in relation to its parent node.

{Resizable} -- If set to True, allows for resizing of both the linear view and the tree view of {expression}.

{ArcsHighlight} -- If set to True, highlights each arc between nodes.

{NodesHighlight} -- If set to True, highlights each node of the tree.

{LeafNodesHighlight} -- If set to True, highlights each leaf node of the tree.

{RootNodeHighlight} -- If set to True, highlights the root node of the tree

{IncludeExpression} -- If set to True, displays the linear view of {expression} at the top of window. (Defaults to True)

{Code} -- If set to True, the expression is rendered using code symbols instead of mathematical symbols.

{Pattern} -- Highlights nodes in the tree that match the provided pattern.



*DESC
Returns a Java GUI component that contains an expression rendered as an expression tree.
Options are entered using the : operator. For example, here is how to disable {Resizable} option: {Resizable: False}.

Any number and combination of options may be used, however some may not be effective when paired with others, for example: {NodesHighlight: True} and {LeafNodesHighlight: True}

 
*E.G.
In> ViewTreeParts("(1 + a_) / b_ * c_ == 13", Scale: 3.0, FontSize: 35.0, NodesHighlight:True)
Result: class javax.swing.Box

In> ViewTreeParts('((1 + 12) / 2 * 5), Pattern:(a_Integer?::(a >? 3)), FontSize: 35.0, Code:True)
Result: class javax.swing.Box

In> ViewTreeParts('((1 + 12) / 2 * 5), NodeHighlight:"1,1,2")
Result: class javax.swing.Box

In> ViewTreeParts('((1 + 12) / 2 * 5))
Result: class javax.swing.Box


*SEE TreeView


*SOURCE org/mathpiper/scripts4/optional/misc/ViewTreeParts.mpws
==========
*CMD DateToNumber --- converts a string that is in date format to number format
*CALL
        DateToNumber(date)

*PARMS
{date} -- a string in "EEE MMM dd HH:mm:ss z yyyy" format


*DESC
converts a string that is in date format to number format

*E.G.
In> DateToNumber("Tue Jan 13 12:37:40 EST 2015")
Result: 1421170660000

*SOURCE org/mathpiper/scripts4/optional/strings/DateToNumber.mpws
==========
*CMD NumberToDate --- converts an integer to a date
*CALL
        NumberToDate(date)

*PARMS
{date} -- an integer that represents milliseconds from

*DESC
This procedure converts an integer to a date string that is similar in format to "Tue Jan 13 12:37:40 EST 2015".

The string has the form "dow mon dd hh:mm:ss zzz yyyy" where:

- {dow} is the day of the week (Sun, Mon, Tue, Wed, Thu, Fri, Sat).

- {mon} is the month (Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec).

- {dd} is the day of the month (01 through 31), as two decimal digits.

- {hh} is the hour of the day (00 through 23), as two decimal digits.

- {mm} is the minute within the hour (00 through 59), as two decimal digits.

- {ss} is the second within the minute (00 through 61, as two decimal digits.

- {zzz} is the time zone (which may use daylight saving time).

- {yyyy} is the year, as four decimal digits. 

*E.G.
In> NumberToDate(1421170660612)
Result: "Tue Jan 13 12:37:40 EST 2015"

*SOURCE org/mathpiper/scripts4/optional/strings/NumberToDate.mpws
==========
*CMD RegexGet -- Searches a string for the regular expression specified.
*CALL
        RegexGet(string, regex)

*PARMS
{string} -- a string to search.

{regex} -- a string that contains a regular expression. Note: all \ must be escaped with a \.

*DESC
This procedure searches a string for a regular expression.

*E.G.
In> RegexGet("This example finds the first character in the string.", "^.")
Result: ["T"]

*SOURCE org/mathpiper/scripts4/optional/strings/RegexGet.mpws
==========
*CMD StringContains? -- Searches for substrings that are in strings. 
*CALL
    StringContains?(string, substring)

*PARMS
{string} --  The string that you are searcing for the substring in.

{substring} --  The word or part of a string that you are looking for in the string.
 
*DESC
This procedure searches for a word or a substring in the string that you specify it to search within. 

*E.G.
In> StringContains?("This is a string", "is");
Result: True 

*SOURCE org/mathpiper/scripts4/optional/strings/StringContains_.mpws
==========
*CMD StringEndsWith? --- check if end of string matches
*CALL
        StringEndsWith?(string, substring)

*PARMS
{string} -- the string to check

{substring} -- string to check with

*DESC
This procedure checks if "string" ends with "substring" and is case-sensitive

*E.G.
In> StringEndsWith?("Hello", "lo");
Result: True;

In> StringEndsWith?("Hello", "clo");
Result: False;

*SOURCE org/mathpiper/scripts4/optional/strings/StringEndsWith_.mpws
==========
*CMD StringIndexOf --- locate the beginning index of a substring within a given string
*CALL

StringIndexOf(string, substring)
StringIndexOf(string, substring, fromIndex)

*PARMS
{string} -- a string of characters

{substring} -- a character or string of characters

{fromIndex} -- the index to start the search from


*DESC
This procedure returns the Mathpiper index of the
given string where the given substring begins. If
the given substring cannot be found, the procedure
will return -1.

*E.G.
In> StringIndexOf("Hello", "H")
Result: 1;

In> StringIndexOf("Hello", "llo")
Result: 3

In> StringIndexOf("Hello", "G")
Result: -1

In> StringIndexOf("abcdcfg", "c", 4)
Result: 5

*SOURCE org/mathpiper/scripts4/optional/strings/StringIndexOf.mpws
==========
*CMD StringLastIndexOf --- locate the last index of a substring within a given string
*CALL

StringLastIndexOf(string, substring)
StringLastIndexOf(string, substring, fromIndex)

*PARMS
{string} -- a string of characters

{substring} -- a character or string of characters

{fromIndex} -- the index to start the backwards search from


*DESC
This procedure returns the index of the last
occurrence of the given substring.

If a {fromIndex} is given, the backwards search
begins at this index.

If the given substring cannot be found, the
procedure will return -1.

*E.G.
In> StringLastIndexOf("Hello", "l")
Result: 4

In> StringLastIndexOf("abcdcfg", "c", 4)
Result: 3

In> StringLastIndexOf("Hello", "G")
Result: -1

*SOURCE org/mathpiper/scripts4/optional/strings/StringLastIndexOf.mpws
==========
*CMD StringLowerCase --- return a copy of a string that contains only lower case letters
*CALL
    StringLowerCase(string)

*PARMS
{string} -- A string

*DESC
This procedure accepts a string and returns the same string with all letters being lower case.

*E.G.
In> StringLowerCase("ThIs iS aN ExAmPlE")
Result: "this is an example"


*SOURCE org/mathpiper/scripts4/optional/strings/StringLowerCase.mpws
==========
*CMD StringMatches? -- tests if a string matches a regular expression
*CALL
    StringMatches?(string, regexp)
    
*PARMS
{string} -- a string

{regexp} -- a regular expression

*DESC
This procedure returns True if it matches {regexp} and False otherwise.

*E.G.
In> StringMatches?("AAA", "A*")
Result: True


*SOURCE org/mathpiper/scripts4/optional/strings/StringMatches_.mpws
==========
*CMD StringReplace --- replace substrings of a string with another string
*CALL
        StringReplace(string, substring, replacement)

*PARMS
{string} -- the parent string

{substring} -- the substring within the string to be replaced

{replacement} -- the string with which to replace all occurrences of the substring

*DESC
This procedure replaces all occurrences of a substring within a string with 
a replacement string and returns the new string. If the substring 
is not located within the string, then the procedures returns the 
string unaltered. This procedure is case sensitive.

*E.G.
In> StringReplace("Heljo", "j", "l")
Result: "Hello"

In> StringReplace("RedBlueRedGreen", "Green", "Blue")
Result: "RedBlueRedBlue"

In> StringReplace("Yes", "yes", "no")
Result: "Yes"

*SOURCE org/mathpiper/scripts4/optional/strings/StringReplace.mpws
==========
*CMD StringReplaceAll --- replace substrings of a string with another string using a regular expression
*CALL
        StringReplaceAll(string, regex, replacement)

*PARMS
{string} -- the parent string

{regex} -- a regular expression

{replacement} -- the string with which to replace all substrings that match the regular expression

*DESC
This procedure replaces all occurrences of a
substring within a string that match {regex} with
a replacement string and returns the new string.
If the regular expression does not match any
substrings, then the procedures returns the string
unaltered.

*E.G.
In> StringReplaceAll("Hel2354lo", "[0-9]+", "X")
Result: "HelXlo"


*SOURCE org/mathpiper/scripts4/optional/strings/StringReplaceAll.mpws
==========
*CMD StringSplit --- splits a string into a list of substrings using a regular expression

*CALL
        StringSplit(string, reqularExpression)

*PARMS
{string} -- A string.

{regularExpression} -- The regular expression to use for splitting.


*DESC
This procedure splits a string into a list of substrings using a regular expression.

*E.G.
In> StringSplit("1,2,3", ",")
Result: ["1","2","3"]

In> StringSplit("1    2    3", "\\t")
Result: ["1","2","3"]

In> StringSplit("oneTwoThree", "(?=\\p{Upper})");
Result: ["one","Two","Three"]

*SOURCE org/mathpiper/scripts4/optional/strings/StringSplit.mpws
==========
*CMD StringStartsWith? --- check if start of string matches
*CALL
        StringStartsWith?(string, substring)

*PARMS
{string} -- the string to check

{substring} -- string to check with

*DESC
This procedure checks if "string" starts with "substring" and is case-sensitive

*E.G.
In> StringStartsWith?("Hello", "He");
Result: True;

In> StringStartsWith?("Hello", "Help");
Result: False;

*SOURCE org/mathpiper/scripts4/optional/strings/StringStartsWith_.mpws
==========
*CMD StringSubstring --- returns a substring of a string

*CALL
        StringSubstring(string, beginIndex, endIndex)

*PARMS
{string} -- A string.

{beginIndex} -- The index of the string where you wish to begin.

{endIndex} -- The index of the string where you wish to end.

*DESC
This procedure takes a string and returns every character inbetween the indexes provided.  

*E.G.
In> StringSubstring("Goodbye", 1,4)
Result: "Good"

*SOURCE org/mathpiper/scripts4/optional/strings/StringSubstring.mpws
==========
*CMD StringTrim --- removes all whitespace characters from the ends of a string

*CALL
        StringTrim(string)

*PARMS
{string} -- a string

*DESC
Removes all whitespace characters from the ends of a string.

*E.G.
In> StringTrim("  hello  ")
Result: "hello"

*SOURCE org/mathpiper/scripts4/optional/strings/StringTrim.mpws
==========
*CMD StringUpperCase --- capitalizes all letters in a string

*CALL
        StringUpperCase(string)

*PARMS
{string} -- a string

*DESC
Capitializes all letters in a string.

*E.G.
In> StringUpperCase("hello")
Result: "HELLO"

*SOURCE org/mathpiper/scripts4/optional/strings/StringUpperCase.mpws
==========
*CMD DefinePattern --- defines a rule which uses a pattern as its predicate

*CALL
        DefinePattern("operator", arity, precedence, pattern) body
*PARMS

{"operator"} -- string, name of procedure

{arity}, {precedence} -- integers

{pattern} -- a pattern object

{body} -- expression, body of rule

*DESC
This procedure defines a rule which uses a pattern as its predicate.

*SEE RulePatternEvaluateArguments

*SOURCE org/mathpiper/scripts4/patterns/DefinePattern.mpws
==========
*CMD MakeVector --- vector of uniquely numbered variable names
*STD
*CALL
        MakeVector("var",n)

*PARMS

{var} -- string

{n} -- length of the vector

*DESC

A list of length "n" is generated. The first entry contains the
identifier "var" with the number 1 appended to it, the second entry
contains "var" with the suffix 2, and so on until the last entry
which contains "var" with the number "n" appended to it.

*E.G.

In> MakeVector("a", 3)
Result: ["a1", "a2", "a3"];

*SEE RandomIntegerList, ZeroVector

*SOURCE org/mathpiper/scripts4/patterns/MakeVector.mpws
==========
*CMD --> --- defines a rule which uses patterns and predicate procedures to determine if it is true or not

*CALL
fn(arg1_, arg2_) --> expression
fn(arg1_PredicateFunction, arg2_) --> expression
fn(arg1_PredicateFunction, arg2_PredicateFunction) --> expression
fn(arg1_PredicateFunction, arg2_PredicateFunction)::(PredicateExpression) --> expression
arg1_ operator arg2_ --> expression
arg1_PredicateFunction operator arg2_ --> expression
arg1_PredicateFunction operator arg2_PredicateFunction --> expression
arg1_PredicateFunction operator arg2_PredicateFunction::(PredicateExpression) --> expression

*PARMS

{arg} -- an expression
{operator} -- an operator

*DESC
Mathematical calculations require versatile transformations on symbolic quantities.
Instead of trying to define all possible transformations, MathPiper provides a simple
and easy to use pattern matching scheme for manipulating expressions according to
user-defined rules. MathPiper itself is designed as a small core engine executing
a large library of rules to match and replace patterns.
One simple application of pattern-matching rules is to define new procedures. (This
is actually the only way MathPiper can learn about new procedures.) As an example,
let's define a procedure f that will evaluate factorials of non-negative integers.
We will define a predicate to check whether our argument is indeed a non-negative
integer, and we will use this predicate and the obvious recursion
f(n)=n*f(n-1) if n>0 and 1 if n=0 to evaluate the factorial.

We start with the simple termination condition, which is that f(n) should return
one if n is zero:

{10 ## f(0) --> 1;}

You can verify that this already works for input value zero, with f(0).

Now we come to the more complex line

20 ## f(n_IntegerGreaterThanZero?) --> n*f(n-1);

We realize we need a procedure GreaterThan?Zero, so we define this procedure, with
IntegerGreaterThanZero?(n_) --> (Integer?(n) &? n>?0);

You can verify that it works by trying f(5), which should return the same value as 5!.

In the above example we have first defined two "transformation rules" for a new
procedure f(). Then we realized that we need to define a predicate IntegerGreaterThanZero?().
A predicate equivalent to IntegerGreaterThanZero?() is actually already defined
in the standard library and it's called PositiveInteger?, so it was not necessary,
strictly speaking, to define our own predicate to do the same thing. We did it here
just for illustration purposes.

The first two lines recursively define a factorial procedure f(n)=n*(n-1)*...*1.
The rules are given precedence values 10 and 20, so the first rule will be applied
first. Incidentally, the factorial is also defined in the standard library as a
postfix operator ! and it is bound to an internal routine much faster than the
recursion in our example. The example does show how to create your own routine with
a few lines of code. One of the design goals of MathPiper was to allow precisely
that, definition of a new procedure with very little effort.

The operator --> defines a rule to be applied to a specific procedure. (The --> operation
cannot be applied to an atom.) The _n in the rule for IntegerGreaterThanZero?()
specifies that any object which happens to be the argument of that predicate is
matched and assigned to the local variable n. The expression to the right of --> can
use n (without the underscore) as a variable.

Now we consider the rules for the procedure f. The first rule just specifies that f(0)
should be replaced by 1 in any expression. The second rule is a little more involved.
n_IntegerGreaterThanZero? is a match for the argument of f, with the proviso that
the predicate IntegerGreaterThanZero?(n) should return True, otherwise the pattern
is not matched. The underscore operator is to be used only on the left hand side of
the rule definition operator -->.

There is another, slightly longer but equivalent way of writing the second rule:
20 ## f(n_)::(IntegerGreaterThanZero?(n)) --> n*f(n-1);

The underscore after the procedure object denotes a "postpredicate" that should return
True or Else there is no match. This predicate may be a complicated expression involving
several logical operations, unlike the simple checking of just one predicate in the
n_IntegerGreaterThanZero? construct. The postpredicate can also use the variable
n (without the underscore).

Precedence values for rules are given by a number followed by the ## infix operator
(and the transformation rule after it). This number determines the ordering of precedence
for the pattern matching rules, with 0 the lowest allowed precedence value, i.e.
rules with precedence 0 will be tried first. Multiple rules can have the same number:
this just means that it doesn't matter what order these patterns are tried in. If no
number is supplied, 0 is assumed. In our example, the rule f(0) --> 1 must be applied
earlier than the recursive rule, or Else the recursion will never terminate. But as
long as there are no other rules concerning the procedure f, the assignment of numbers
10 and 20 is arbitrary, and they could have been 500 and 501 just as well. It is
usually a good idea however to keep some space between these numbers, so you have
room to insert new transformation rules later on.

Predicates can be combined: for example, {IntegerGreaterThanZero?()} could also
have been defined as:
10 ## IntegerGreaterThanZero?(n_Integer?)::(n>?0) --> True;
20 ## IntegerGreaterThanZero?(n_) --> False;

The first rule specifies that if n is an integer, and is greater than zero, the
result is True, and the second rule states that otherwise (when the rule with
precedence 10 did not apply) the predicate returns False.

In the above example, the expression n > 0 is added after the pattern and allows
the pattern to match only if this predicate return True. This is a useful syntax
for defining rules with complicated predicates. There is no difference between the
rules F(n_PositiveInteger?) -->... and F(n_)::(PositiveInteger?(n)) --> ... except
that the first syntax is a little more concise.

The left hand side of a rule expression has the following form:
precedence ## pattern :: postpredicate --> replacement ;

The optional precedence must be a positive integer.
Some more examples of rules (not made clickable because their equivalents are already
in the basic MathPiper library):
10 ## x_ + 0 --> x;
20 ## x_ - x_ --> 0;
//ArcSin(Sin(x_)) --> x;

The last rule has no explicit precedence specified in it (the precedence zero will
be assigned automatically by the system). MathPiper will first try to match the pattern
as a template. Names followed by an underscore can match any one object:
a number, a procedure, a list, etc. MathPiper will assign the relevant variables as
local variables within the rule, and try the predicates as stated in the pattern.
The post predicate (defined after the pattern) is tried after all these matched.
As an example, the transformation rule x_ - x_ -->0 specifies that the two objects
at left and at right of the minus sign should be the same for this transformation
rule to apply.

*SEE :=

*SOURCE org/mathpiper/scripts4/patterns/lessthan_negative_negative_operator.mpws
==========
*CMD RemoveRepeated --- Remove repeated entries within a list
*STD
*CALL
        RemoveRepeated(list)

*PARMS

{list} -- list from which to remove repeated entries

*DESC

Removes entries that are repeated more than once in a row. RemoveRepeated does not remove all duplicate entries, only entries which are repeated more than once in a row. For example,  RemoveRepeated([1,2,2,2,3,4,5,5,4]) will return [1,2,3,4,5,4]. The additional 2's and 5 were removed, however, both 4's remain because they were separated with two 5's.

*E.G.

In> RemoveRepeated([1,2,2,3,3,3,4,4,4,4]);
Result: [1,2,3,4];

In> RemoveRepeated(["a","a","b","bb","b","c","cc","c","c"]);
Result: ["a","b","bb","b","c","cc","c"]

In> RemoveRepeated([1,2,1,2,1,2])
Result: [1,2,1,2,1,2]


*SOURCE org/mathpiper/scripts4/plots/RemoveRepeated.mpws
==========
*CMD Plot2D --- adaptive two-dimensional plotting
*STD
*CALL
        Plot2D(f(_x))
        Plot2D(f(_x), a::b)
        Plot2D(f(_x), a::b, option: value)
        Plot2D(f(_x), a::b, option: value, ...)
        Plot2D(list, ...)

*PARMS

{f(_x)} -- unevaluated expression containing one variable (procedure to be plotted)

{list} -- list of procedures to plot

{a}, {b} -- numbers, plotting range in the $x$ coordinate

{option} -- atom, option name

{value} -- atom, number or string (value of option)

*DESC
The routine {Plot2D} performs adaptive plotting of one or several procedures
of one variable in the specified range.
The result is presented as a line given by the equation $y=f(\_x)$.
Several procedures can be plotted at once.
Various plotting options can be specified.
Output can be directed to a plotting program (the default is to use
{data}) to a list of values.

The procedure parameter {f(_x)} must evaluate to a MathPiper expression containing
at most one variable. (The variable does not have to be called {_x}.)
Also, {NM(f(_x))} must evaluate to a real (not complex) numerical value when 
given a numerical value of the argument {_x}. If the procedure {f(_x)} does not 
satisfy these requirements, an error is raised.

Several procedures may be specified as a list and they do not have to depend on 
the same variable, for example, {{f(_x), g(_y)}}. The procedures will be plotted 
on the same graph using the same coordinate ranges.

If you have defined a procedure which accepts a number but does not
accept an undefined variable, {Plot2D} will fail to plot it.
Use {NumericProcedure} to overcome this difficulty.

Data files are created in a temporary directory {/tmp/plot.tmp/} unless otherwise requested.
File names
and other information is printed if {Verbose?()} returns {True} on using {Verbose()}.

The current algorithm uses Newton-Cotes quadratures and some heuristics for error 
estimation (see <*mathpiperdoc://Algo/3/1/*>). The initial grid of {points+1} 
points is refined between any grid points $a$, $b$ if the integral
$Integrate(x,a,b)f(_x)$ is not approximated to the given precision by
the existing grid.

Options are of the form {option: value}. Currently supported option names
are: "points", "precision", "depth", "output", "filename", "yrange". Option values
are either numbers or special unevaluated atoms such as {data}.
If you need to use the names of these atoms
in your script, strings can be used. Several option/value pairs may be specified 
(the procedure {Plot2D} has a variable number of arguments).

*        {yrange}: the range of ordinates to use for plotting, e.g.
{yrange=0::20}. If no range is specified, the default is usually to
leave the choice to the plotting backend. 
*        {points}: initial number of points (default 23) -- at least that
many points will be plotted. The initial grid of this many points will be
adaptively refined. 
*        {precision}: graphing precision (default $10^(-6)$). This is 
interpreted as the relative precision of computing the integral of 
$f(_x)-Minimum(f(_x))$ using the grid points. For a smooth, non-oscillating 
procedure this value should be roughly 1/(number of screen pixels in the plot).
*        {depth}: max. refinement depth, logarithmic (default 5) -- means 
there will be at most $2^depth$ extra points per initial grid point.
*        {output}: name of the plotting backend. Supported names: {data} (default).
The [data] backend will return the data as a list of pairs such as {[[x1,y1], [x2,y2], ...]}.
*        [filename]: specify name of the created data file. For example: [filename="data1.txt"].
The default is the name {"output.data"}.
Note that if several procedures are plotted, the data files will have a number 
appended to the given name, for example {data.txt1}, {data.txt2}.

Other options may be supported in the future.

The current implementation can deal with a singularity within the plotting range 
only if the procedure {f(_x)} returns {Infinity}, {-Infinity} or
{Undefined} at the singularity.
If the procedure {f(_x)} generates a numerical error and fails at a
singularity, {Plot2D} will fail if one of the grid points falls on the
singularity.
(All grid points are generated by bisection so in principle the
endpoints and the {points} parameter could be chosen to avoid numerical
singularities.)

*WIN32



*SEE Verbose, NumericProcedure, Plot3DS

*SOURCE org/mathpiper/scripts4/plots/_2d/plot2d.mpws
==========
*CMD Plot3DS --- three-dimensional (surface) plotting
*STD
*CALL
        Plot3DS(f(x,y))
        Plot3DS(f(x,y), a::b, c::d)
        Plot3DS(f(x,y), a::b, c::d, option: value)
        Plot3DS(f(x,y), a::b, c::d, option: value, ...)
        Plot3DS(list, ...)

*PARMS

{f(x,y)} -- unevaluated expression containing two variables (procedure to be plotted)

{list} -- list of procedures to plot

{a}, {b}, {c}, {d} -- numbers, plotting ranges in the $x$ and $y$ coordinates

{option} -- atom, option name

{value} -- atom, number or string (value of option)

*DESC
The routine {Plot3DS} performs adaptive plotting of a procedure
of two variables in the specified ranges.
The result is presented as a surface given by the equation $z=f(x,y)$.
Several procedures can be plotted at once, by giving a list of procedures.
Various plotting options can be specified.
Output can be directed to a plotting program (the default is to use
{data}), to a list of values.

The procedure parameter {f(x,y)} must evaluate to a MathPiper expression containing
at most two variables. (The variables do not have to be called {x} and {y}.)
Also, {NM(f(x,y))} must evaluate to a real (not complex) numerical value when given 
numerical values of the arguments {x}, {y}.
If the procedure {f(x,y)} does not satisfy these requirements, an error is raised.

Several procedures may be specified as a list but they have to depend on the same 
symbolic variables, for example, {[f(x,y), g(y,x)]}, but not {[f(x,y), g(a,b)]}.
The procedures will be plotted on the same graph using the same coordinate ranges.

If you have defined a procedure which accepts a number but does not
accept an undefined variable, {Plot3DS} will fail to plot it.
Use {NumericProcedure} to overcome this difficulty.

Data files are created in a temporary directory {/tmp/plot.tmp/} unless otherwise requested.
File names
and other information is printed if {Verbose?()} returns {True} on using {Verbose()}.

The current algorithm uses Newton-Cotes cubatures and some heuristics for error 
estimation (see <*mathpiperdoc://Algo/3/1/*>).
The initial rectangular grid of {xpoints+1}*{ypoints+1} points is refined within any 
rectangle where the integral
of $f(x,y)$ is not approximated to the given precision by
the existing grid.

Options are of the form {option: value}. Currently supported option names
are "points", "xpoints", "ypoints", "precision", "depth", "output", "filename", "xrange", 
"yrange", "zrange". Option values
are either numbers or special unevaluated atoms such as {data}.
If you need to use the names of these atoms
in your script, strings can be used (e.g. {output="data"}). Several option/value pairs 
may be specified (the procedure {Plot3DS} has a variable number of arguments).

*        {xrange}, {yrange}: optionally override coordinate ranges. Note that {xrange} 
is always the first variable and {yrange} the second variable, regardless of the actual variable names.
*        {zrange}: the range of the $z$ axis to use for plotting, e.g.
{zrange=0::20}. If no range is specified, the default is usually to
leave the choice to the plotting backend. Automatic choice based on actual values may
give visually inadequate plots if the procedure has a singularity.
*        {points}, {xpoints}, {ypoints}: initial number of points (default 10 each) -- at least that
many points will be plotted in each coordinate.
The initial grid of this many points will be
adaptively refined.
If {points} is specified, it serves as a default for both {xpoints} and {ypoints} this value may be overridden by {xpoints} and {ypoints} values.
*        {precision}: graphing precision (default $0.01$). This is interpreted as the relative precision of computing the integral of $f(x,y)-Minimum(f(x,y))$ using the grid points. For a smooth, non-oscillating procedure this value should be roughly 1/(number of screen pixels in the plot).
*        {depth}: max. refinement depth, logarithmic (default 3) -- means there will be at most $2^depth$ extra points per initial grid point (in each coordinate).
*        {output}: name of the plotting backend. Supported names: {data} (default).
The {data} backend will return the data as a list of triples such as {{{x1, y1, z1}, {x2, y2, z2}, ...}}.

Other options may be supported in the future.

The current implementation can deal with a singularity within the plotting range only if the procedure {f(x,y)} returns {Infinity}, {-Infinity} or
{Undefined} at the singularity.
If the procedure {f(x,y)} generates a numerical error and fails at a
singularity, {Plot3DS} will fail only if one of the grid points falls on the
singularity.
(All grid points are generated by bisection so in principle the
endpoints and the {xpoints}, {ypoints} parameters could be chosen to avoid numerical
singularities.)

The {filename} option is optional if using graphical backends, but can be used to specify the location of the created data file.

*WIN32

Same limitations as {Plot2D}.

*E.G. notest

In> Plot3DS(a*b^2)
Result: True;

In> Verbose(Plot3DS(Sin(x)*Cos(y),x: 0::20, y: 0::20,depth: 3))
        CachedConstant: Info: constant Pi is being 
          recalculated at precision 10
        CachedConstant: Info: constant Pi is being
          recalculated at precision 11
        Plot3DS: using 1699  points for procedure Sin(x)*Cos(y)
        Plot3DS: max. used 8 subdivisions for Sin(x)*Cos(y)
        Plot3DSdatafile: created file /tmp/plot.tmp/data1
Result: True;


*SEE Verbose, NumericProcedure, Plot2D

*SOURCE org/mathpiper/scripts4/plots/_3d/plot3ds.mpws
==========


*CMD AllSatisfy? --- Check if all elements of list [lst] satisfy predicate [pred]

*STD
*CALL
        AllSatisfy?(pred,lst)

*PARMS

{pred} -- the name of the predicate (as string, with quotes) to be tested

{lst} -- a list

*DESC

The command {AllSatisfy?} returns {True} if every element of the list {lst} satisfies the predicate {pred}. 
It returns {False} otherwise. It also returns {False} if {lst} is not a list, or if {pred} is not a predicate.

*E.G.


In> AllSatisfy?("Integer?",[1,0,-5])
Result> True 

In> AllSatisfy?("PositiveInteger?",[1,0,-5])
Result> False
    

*SOURCE org/mathpiper/scripts4/predicates/AllSatisfy_.mpws
==========
*CMD Boolean? --- test for a Boolean value
*STD
*CALL
        Boolean?(expression)

*PARMS

{expression} -- an expression

*DESC

Boolean? returns True if the argument is of a boolean type.
This means it has to be either True, False, or an expression involving
procedures that return a boolean result, e.g.
{=?}, {>?}, {<?}, {>=?}, {<=?}, {!=?}, {&?}, {!?}, {|?}.

*E.G.

In> Boolean?(a)
Result: False;

In> Boolean?(True)
Result: True;

In> Boolean?(a &? b)
Result: True;

*SEE True, False

*SOURCE org/mathpiper/scripts4/predicates/Boolean_.mpws
==========
*CMD Color? --- determines if a value of one of the color constants

*CALL
        Color?(color)

*PARMS

{k} -- a color constant

*DESC

Returns {True} if {color} is one of the color constants, and
{False} otherwise. A list of the currently defined color constants
can be obtained by clicking on the "View source code" link below.

*EXAMPLES
In> Color?(Orange) 
Result: True


*SOURCE org/mathpiper/scripts4/predicates/Color_.mpws
==========
*CMD Constant? --- test for a constant
*STD
*CALL
        Constant?(expr)

*PARMS

{expr} -- some expression

*DESC

{Constant?} returns {True} if the
expression is some constant or a procedure with constant arguments. It
does this by checking that no variables are referenced in the
expression. {Pi} is considered a constant.

*E.G.

In> Constant?(Cos(x))
Result: False;

In> Constant?(Cos(2))
Result: True;

In> Constant?(Cos(2+x))
Result: False;

*SEE Number?, Integer?, VarList, Variable?, UnderscoreConstant?, DefinedConstant?

*SOURCE org/mathpiper/scripts4/predicates/Constant_.mpws
==========
*CMD Diagonal? --- test for a diagonal matrix

*CALL
    Diagonal?(A)

*PARMS

{A} -- a matrix

*DESC

{Diagonal?(A)} returns {True} if {A} is a diagonal square matrix and {False} otherwise.

*E.G.
In> Diagonal?(IdentityMatrix(5))
Result: True;

In> Diagonal?(HilbertMatrix(5))
Result: False;

*SOURCE org/mathpiper/scripts4/predicates/Diagonal_.mpws
==========

*CMD Equation? --- Return true if [expr] is an Equation False otherwise

*STD
*CALL
        Equation?(expr)

*PARMS

{expr} -- mathematical expression

*DESC

This procedure returns {True} if MathPiper can determine that the expression is an equation.  
Otherwise, {False}.
Equations are defined by the property that they are of the form {a==b}.

*E.G.


In> Equation?(_x^2==4)

Result: True


In> Equation?(_x^2-4)

Result: False


*SOURCE org/mathpiper/scripts4/predicates/Equation_.mpws
==========
*CMD EvenFunction? --- Return true if function is an even function (False otherwise)

*STD
*CALL
        EvenFunction?(expression,variable)

*PARMS

{expression} -- mathematical expression
{variable} -- variable

*DESC

This procedure returns True if MathPiper can determine that the
function is even. Even procedures are
defined to be procedures that have the property:

$$ f(x) = f(-x) $$

{Cos(x)} is an example of an even function.

As a side note, one can decompose a function into an
even and an odd part:

$$ f(x) = f_even(x) + f_odd(x) $$

Where 

$$ f_even(x) = (f(x)+f(-x))/2 $$

and

$$ f_odd(x) = (f(x)-f(-x))/2 $$

*E.G.

In> EvenFunction?(Cos(b*x),x)
Result: True

In> EvenFunction?(Sin(b*x),x)
Result: False

In> EvenFunction?(1/x^2,x)
Result: True

In> EvenFunction?(1/x,x)
Result: False

*SEE OddFunction?, Sin, Cos

*SOURCE org/mathpiper/scripts4/predicates/EvenFunction_.mpws
==========
*CMD Even? --- test for an even integer
*STD
*CALL
        Even?(n)

*PARMS

{n} -- integer to test

*DESC

This procedure tests whether the integer "n" is even. An integer is
even if it is divisible by two. Hence the even numbers are 0, 2, 4, 6,
8, 10, etc., and -2, -4, -6, -8, -10, etc.

*E.G.

In> Even?(4);
Result: True;

In> Even?(-1);
Result: False;

*SEE Odd?, Integer?

*SOURCE org/mathpiper/scripts4/predicates/Even_.mpws
==========
*CMD FloatIsInt? --- test if a float is equivalent to an integer

*CALL
        
FloatIsInt?(float)

*PARMS

{float} -- floating point number to be tested

*DESC


{FloatIsInt?(float)} evaluates to True if {float} is equivalent to an integer value.

*E.G.

In> FloatIsInt?(1.0000)
Result: True

In> FloatIsInt?(1.0001)
Result: False

*SEE True, False

*SOURCE org/mathpiper/scripts4/predicates/FloatIsInt_.mpws
==========
*CMD HasExpressionArithmetic? --- check for expression containing a subexpression
*STD
*CALL
        HasExpressionArithmetic?(expr, x)

*PARMS

{expr} -- an expression

{x} -- a subexpression to be found

*DESC

{HasExpressionArithmetic?} is defined through {HasExpressionSome?} to look 
only at arithmetic operations {+}, {-}, {*}, {/}.

Note that since the operators "{+}" and "{-}" are prefix as well as infix 
operators, it is currently required to use {ToAtom("+")} to obtain the unevaluated atom "{+}".

*E.G.

In> HasExpressionArithmetic?(x+y*Cos(Ln(x)/x), z)
Result: False;

*SEE HasExpression?, HasExpressionSome?, ProcedureList, VarList, HasProcedure?

*SOURCE org/mathpiper/scripts4/predicates/HasExpressionArithmetic_.mpws
==========
*CMD HasExpressionSome? --- check for expression containing a subexpression
*STD
*CALL
        HasExpressionSome?(expr, x, list)

*PARMS

{expr} -- an expression

{x} -- a subexpression to be found

{list} -- list of procedure atoms to be considered "transparent"

*DESC

The command {HasExpressionSome?} does the same as {HasExpression?}, except 
it only looks at arguments of a given {list} of procedures. All other procedures 
become "opaque" (as if they do not contain anything).

Note that since the operators "{+}" and "{-}" are prefix as well as infix 
operators, it is currently required to use {ToAtom("+")} to obtain the unevaluated atom "{+}".

*E.G.

In> HasExpressionSome?([a+b*2,c/d],c/d,[List])
Result: True;

In> HasExpressionSome?([a+b*2,c/d],c,[List])
Result: False;

*SEE HasExpression?, HasExpressionArithmetic?, ProcedureList, VarList, HasProcedure?

*SOURCE org/mathpiper/scripts4/predicates/HasExpressionSome_.mpws
==========
*CMD HasExpression? --- check for expression containing a subexpression
*STD
*CALL
        HasExpression?(expr, x)

*PARMS

{expr} -- an expression

{x} -- a subexpression to be found



*DESC

The command {HasExpression?} returns {True} if the expression {expr} 
contains a literal subexpression {x}. The expression is recursively traversed.

Note that since the operators "{+}" and "{-}" are prefix as well as 
infix operators, it is currently required to use {ToAtom("+")} to obtain 
the unevaluated atom "{+}".

*E.G.

In> HasExpression?(_x+_y*Cos(Ln(_z)/_z), _z)
Result: True;

In> HasExpression?(_x+_y*Cos(Ln(_z)/_z), Ln(_z))
Result: True;

In> HasExpression?(_x+_y*Cos(Ln(_z)/_z), _z/Ln(_z))
Result: False;

In> HasExpression?(_x+_y*Cos(Ln(_z)/_z), Ln(_z)/_z)
Result: True

In> HasExpression?(_x+_y*Cos(Ln(_z)/_z), _z)
Result: True

In> HasExpression?(_x+_y*Cos(Ln(_z)/_z), 1/_z)
Result: False


*SEE HasExpressionArithmetic?, HasExpressionSome?, ProcedureList, VarList, HasProcedure?

*SOURCE org/mathpiper/scripts4/predicates/HasExpression_.mpws
==========
*CMD HasProcedureArithmetic? --- check for expression containing a procedure
*STD
*CALL
        HasProcedureArithmetic?(expr, func)

*PARMS

{expr} -- an expression

{func} -- a procedure atom to be found

*DESC

{HasProcedureArithmetic?} is defined through {HasProcedureSome?} to look 
only at arithmetic operations {+}, {-}, {*}, {/}.

Note that since the operators "{+}" and "{-}" are prefix as well as infix 
operators, it is currently required to use {ToAtom("+")} to obtain the 
unevaluated atom "{+}".

*E.G.

In> HasProcedureArithmetic?(x+y*Cos(Ln(x)/x), Cos)
Result: True;

In> HasProcedureArithmetic?(x+y*Cos(Ln(x)/x), Ln)
Result: False;

*SEE HasProcedure?, HasProcedureSome?, ProcedureList, VarList, HasExpression?

*SOURCE org/mathpiper/scripts4/predicates/HasProcedureArithmetic_.mpws
==========
*CMD HasProcedureSome? --- check for expression containing a procedure
*STD
*CALL
        HasProcedureSome?(expr, func, list)

*PARMS

{expr} -- an expression

{func} -- a procedure atom to be found

{list} -- list of procedure atoms to be considered "transparent"

*DESC

The command {HasProcedureSome?} does the same thing as {HasProcedure?}, 
except it only looks at arguments of a given {list} of procedures. 
Arguments of all other procedures become "opaque" (as if they do not 
contain anything).

Note that since the operators "{+}" and "{-}" are prefix as well as 
infix operators, it is currently required to use {ToAtom("+")} to 
obtain the unevaluated atom "{+}".

*E.G.

In> HasProcedureSome?([a+b*2,c/d],/,[List])
Result: True;

In> HasProcedureSome?([a+b*2,c/d],*,[List])
Result: False;

*SEE HasProcedure?, HasProcedureArithmetic?, ProcedureList, VarList, HasExpression?

*SOURCE org/mathpiper/scripts4/predicates/HasProcedureSome_.mpws
==========
*CMD HasProcedure? --- check for expression containing a procedure
*STD
*CALL
        HasProcedure?(expr, func)

*PARMS

{expr} -- an expression

{func} -- a procedure atom to be found

*DESC

The command {HasProcedure?} returns {True} if the expression {expr} contains 
a procedure {func}. The expression is recursively traversed.

Note that since the operators "{+}" and "{-}" are prefix as well as infix 
operators, it is currently required to use {ToAtom("+")} to obtain the 
unevaluated atom "{+}".

*E.G.

In> HasProcedure?(x+y*Cos(Ln(z)/z), Ln)
Result: True;

In> HasProcedure?(x+y*Cos(Ln(z)/z), Sin)
Result: False;

*SEE HasProcedureArithmetic?, HasProcedureSome?, ProcedureList, VarList, HasExpression?

*SOURCE org/mathpiper/scripts4/predicates/HasProcedure_.mpws
==========
*CMD Infinity? --- test for an infinity
*STD
*CALL
        Infinity?(expr)

*PARMS

{expr} -- expression to test

*DESC

This procedure tests whether {expr} is an infinity. This is only the
case if {expr} is either {Infinity} or {-Infinity}.

*E.G.

In> Infinity?(10^1000);
Result: False;

In> Infinity?(-Infinity);
Result: True;

*SEE Integer?

*SOURCE org/mathpiper/scripts4/predicates/Infinity_.mpws
==========
*CMD ListHasProcedure? --- test for one of the elements of a list to contain a procedure
*STD
*CALL
        ListHasProcedure?( list, func )

*PARMS

{list} - a list of expressions

{func} - a procedure atom to be found

*DESC

Given a list of expressions and and a procedure name, this command returns 
{True} if the list contains the procedure name.

*E.G.
In> lst := [Ln(x),Sinh(a*x),ArcTan(3/x)]
Result: [Ln(x),Sinh(a*x),ArcTan(3/x)]

In> ListHasProcedure?(lst,Sqrt)
Result: False

In> ListHasProcedure?(lst,Ln)
Result: True

In> ListHasProcedure?(lst,Sinh)
Result: True

In> ListHasProcedure?(lst,ArcTan)
Result: True
*SEE HasProcedure?

*SOURCE org/mathpiper/scripts4/predicates/ListHasProcedure_.mpws
==========
*CMD LowerTriangular? --- test for a lower triangular matrix
*STD
*CALL
        LowerTriangular?(A)

*PARMS

{A} -- a matrix

*DESC

A lower triangular matrix is a square matrix which has all zero entries above the diagonal.

{LowerTriangular?(A)} returns {True} if {A} is a lower triangular matrix and {False} otherwise.

*E.G.
In> LowerTriangular?(IdentityMatrix(5))
Result: True

In> LowerTriangular?([[1,2],[0,1]])
Result: False

A non-square matrix cannot be triangular:

In> LowerTriangular?([[1,2,3],[0,1,2]])
Result: False

*SEE UpperTriangular?, Diagonal?

*SOURCE org/mathpiper/scripts4/predicates/LowerTriangular_.mpws
==========
*CMD Monomial? --- determine if [expr] is a Monomial
*STD
*CALL
        Monomial?(expr)

*PARMS
{expr} -- an expression

*DESC
This procedure returns {True} if {expr} satisfies the definition of a {Monomial}.
Otherwise, {False}.
A {Monomial} is defined to be a single term, consisting of a product of numbers
and variables.

*E.G.

In> Monomial?(24)
Result: True


In> Monomial?(24*a*x^2*y^3)
Result: True


In> Monomial?(24*a*x^2*y^3/15)
Result: True


In> Monomial?(24*a*x^2*y^3/15+1)
Result: False
    

*SOURCE org/mathpiper/scripts4/predicates/Monomial_.mpws
==========
*CMD NegativeInteger? --- test for a negative integer
*STD
*CALL
        NegativeInteger?(n)

*PARMS

{n} -- integer to test

*DESC

This procedure tests whether the integer {n} is (strictly)
negative. The negative integers are -1, -2, -3, -4, -5, etc. If
{n} is not a integer, the procedure returns {False}.

*E.G.

In> NegativeInteger?(31);
Result: False;

In> NegativeInteger?(-2);
Result: True;

*SEE PositiveInteger?, NonZeroInteger?, NegativeNumber?

*SOURCE org/mathpiper/scripts4/predicates/NegativeInteger_.mpws
==========
*CMD NegativeNumber? --- test for a negative number
*STD
*CALL
        NegativeNumber?(n)

*PARMS

{n} -- number to test

*DESC

{NegativeNumber?(n)} evaluates to {True} if $n$ is (strictly) negative, i.e.
if $n<0$. If {n} is not a number, the procedures return {False}. 

*E.G.

In> NegativeNumber?(6);
Result: False;

In> NegativeNumber?(-2.5);
Result: True;

*SEE Number?, PositiveNumber?, NotZero?, NegativeInteger?, NegativeReal?

*SOURCE org/mathpiper/scripts4/predicates/NegativeNumber_.mpws
==========
*CMD NegativeReal? --- test for a numerically negative value
*STD
*CALL
        NegativeReal?(expr)

*PARMS

[expr] -- expression to test

*DESC

This procedure tries to approximate [expr] numerically. It returns [True] if this approximation is negative. In case no
approximation can be found, the procedure returns [False]. Note that round-off errors may cause incorrect
results.

*E.G.

In> NegativeReal?(Sin(1)-3/4);
Result: False;

In> NegativeReal?(Sin(1)-6/7);
Result: True;

In> NegativeReal?(Exp(x));
Result: False;

The last result is because [Exp(x)] cannot be
numerically approximated if [x] is not known. Hence
MathPiper can not determine the sign of this expression.

*SEE PositiveReal?, NegativeNumber?, NM

*SOURCE org/mathpiper/scripts4/predicates/NegativeReal_.mpws
==========
*CMD NonNegativeInteger? --- tests if a number is a positive integer

*CALL

NonNegativeInteger?(n)

*PARMS

{n} -- number to be tested

*DESC


{NonNegativeInteger?(n)} evaluates to True if {n} is a positive integer value, or is equal to 0. If {n} is not a number or is not an integer, the procedure will evaluate to {False}.

*E.G.

In> NonNegativeInteger?(1)
Result: True

In> NonNegativeInteger?(1.0001)
Result: False

In> NonNegativeInteger?(0)
Result: True

*SEE Number?, NegativeNumber?, NegativeInteger?, NonNegativeNumber?, PositiveNumber? 

*SOURCE org/mathpiper/scripts4/predicates/NonNegativeInteger_.mpws
==========
*CMD NonNegativeNumber? --- tests if a number is a positive or 0

*CALL
        
NonNegativeNumber?(n)

*PARMS

{n} -- number to be tested

*DESC


{NonNegativeNumber?(n)} evaluates to True if {n} is a positive value, or is equal to 0. If {n} is not a number, the procedure will evaluate to {False}.

*E.G.

In> NonNegativeNumber?(1)
Result: True

In> NonNegativeNumber?(1.0001)
Result: True

In> NonNegativeNumber?(0)
Result: True

In> NonNegativeNumber?(-1)
Result: False

*SEE Number?, NegativeNumber?, NegativeInteger?, NonNegativeInteger?, PositiveNumber? 

*SOURCE org/mathpiper/scripts4/predicates/NonNegativeNumber_.mpws
==========
*CMD NonZeroInteger? --- test for a nonzero integer
*STD
*CALL
        NonZeroInteger?(n)

*PARMS

{n} -- integer to test

*DESC

This procedure tests whether the integer {n} is not zero. If {n} is
not an integer, the result is {False}.

*E.G.

In> NonZeroInteger?(0)
Result: False;

In> NonZeroInteger?(-2)
Result: True;

*SEE PositiveInteger?, NegativeInteger?, NotZero?

*SOURCE org/mathpiper/scripts4/predicates/NonZeroInteger_.mpws
==========

*CMD NoneSatisfy? --- Check if NO element of list [lst] satisfies predicate [pred]

*STD
*CALL
        NoneSatisfy?(pred,lst)

*PARMS

{pred} -- the name of the predicate (as string, with quotes) to be tested

{lst} -- a list

*DESC

The command {NoneSatisfy?} returns {True} if NO element of the list {lst} satisfies 
the predicate {pred}. It returns {False} if at least one element of the list 
satisfies the predicate. It also returns {True} if {lst} is not a list, or if 
{pred} is not a predicate.

*E.G.


In> NoneSatisfy?("NegativeInteger?",[1,0,5])
Result: True

In> NoneSatisfy?("PositiveInteger?",[-1,0,5])
Result: False
    

*SOURCE org/mathpiper/scripts4/predicates/NoneSatisfy_.mpws
==========
*CMD NotZero? --- test for a nonzero number
*STD
*CALL
        NotZero?(n)

*PARMS

{n} -- number to test

*DESC

{NotZero?(n)} evaluates to {True} if {n} is not zero. In case {n} is not a
number, the procedure returns {False}.

*E.G.

In> NotZero?(3.25);
Result: True;

In> NotZero?(0);
Result: False;

*SEE Number?, PositiveNumber?, NegativeNumber?, NonZeroInteger?

*SOURCE org/mathpiper/scripts4/predicates/NotZero_.mpws
==========
*CMD NumericList? --- test for a list of numbers
*STD
*CALL
        NumericList?([list])

*PARMS

{{list}} -- a list

*DESC
Returns {True} when called on a list of numbers or expressions that evaluate 
to numbers using {NM()}. Returns {False} otherwise.

*EXAMPLES
In> NumericList?([1,2,3]) 
Result: True

In> NumericList?(123) 
Result: False

In> NumericList?([123]) 
Result: True

*SEE NM, Number?

*SOURCE org/mathpiper/scripts4/predicates/NumericList_.mpws
==========
*CMD OddFunction? --- Return true if function is an odd function (False otherwise)

*STD
*CALL
        OddFunction?(expression,variable)

*PARMS

{expression} -- mathematical expression
{variable} -- variable

*DESC

This procedure returns True if MathPiper can determine that the
function is odd.  Odd procedures have the property:

$$ f(x) = -f(-x) $$

{Sin(x)} is an example of an odd function.

As a side note, one can decompose a function into an
even and an odd part:

$$ f(x) = f_even(x) + f_odd(x) $$

Where 

$$ f_even(x) = (f(x)+f(-x))/2 $$

and

$$ f_odd(x) = (f(x)-f(-x))/2 $$

*E.G.

In> OddFunction?(Cos(b*x),x)
Result: False

In> OddFunction?(Sin(b*x),x)
Result: True

In> OddFunction?(1/x,x)
Result: True

In> OddFunction?(1/x^2,x)
Result: False

*SEE EvenFunction?, Sin, Cos

*SOURCE org/mathpiper/scripts4/predicates/OddFunction_.mpws
==========
*CMD Odd? --- test for an odd integer
*STD
*CALL
        Odd?(n)

*PARMS

{n} -- integer to test

*DESC

This procedure tests whether the integer "n" is odd. An integer is
odd if it is not divisible by two. Hence the odd numbers are 1, 3, 5,
7, 9, etc., and -1, -3, -5, -7, -9, etc.

*E.G.

In> Odd?(4);
Result: False;

In> Odd?(-1);
Result: True;

*SEE Even?, Integer?

*SOURCE org/mathpiper/scripts4/predicates/Odd_.mpws
==========

*CMD PolynomialOverIntegers? --- Check if [expr] is a polynomial in variable [var] all of whose coefficients are integers

*STD
*CALL
    PolynomialOverIntegers?(expr,var)

*PARMS

{expr} -- an algebraic expression which may be a polynomial

{var} -- a variable name which might be used in {expr}

*DESC

The command {PolynomialOverIntegers?} returns {True} if {expr} is a 
polynomial in {var} and all of its coefficients are integers.
It returns {False} if {expr} is not a polynomial in {var} or if any 
of its coefficients are not integers.

This can be important, since many factoring theorems are applicable 
to such polynomials but not others.

*E.G.


In> PolynomialOverIntegers?(2*x^3-3*x^2+5*x-14,x)
Result: True 


In> PolynomialOverIntegers?(2.0*x^3-3*x^2+5*x-14,x)
Result: False


In> PolynomialOverIntegers?(y^2-4)
Result: True
        NOTE: if variable name is omitted, a reasonable default is taken.


In> PolynomialOverIntegers?(x^2-a^2)
Result: False
        NOTE: the unbound variable 'a' need not be an integer.


*SOURCE org/mathpiper/scripts4/predicates/PolynomialOverIntegers_.mpws
==========

*CMD Polynomial? --- Check if [expr] is a polynomial in variable [var] if [var] is specified.

*STD
*CALL
    Polynomial?(expr,var)
or
    Polynomial?(expr)

*PARMS

{expr} -- an algebraic expression which may be a polynomial

{var}  -- a variable name which might be used in {expr}

*DESC

The command {Polynomial?} returns {True} if {expr} is (or could be) a polynomial in {var}.
If {var} is not specified, a heuristic algorithm (which may be wrong!) is used to select a
likely variable name from among the list of "variables" returned by VarList(expr).
If you would rather not have an algorithm selecting the variable name, specify it as an
argument to the procedure. It returns {False} if {expr} is not likely to be a polynomial 
in {var}.

*E.G.

In> Polynomial?(2*x^3-3*x^2+5*x-14,x)
Result: True 

In> Polynomial?(2*x^3-3*x^2+5*x-14)
Result: True

In> Polynomial?(y^2-4)
Result: True
        NOTE: if variable name is omitted, a reasonable default is taken.


*SOURCE org/mathpiper/scripts4/predicates/Polynomial_.mpws
==========
*CMD PositiveInteger? --- test for a positive integer
*STD
*CALL
        PositiveInteger?(n)

*PARMS

{n} -- integer to test

*DESC

This procedure tests whether the integer {n} is (strictly) positive. The
positive integers are 1, 2, 3, 4, 5, etc. If {n} is not a integer, the
procedure returns {False}.

*E.G.

In> PositiveInteger?(31);
Result: True;

In> PositiveInteger?(-2);
Result: False;

*SEE NegativeInteger?, NonZeroInteger?, PositiveNumber?

*SOURCE org/mathpiper/scripts4/predicates/PositiveInteger_.mpws
==========
*CMD PositiveNumber? --- test for a positive number
*STD
*CALL
        PositiveNumber?(n)

*PARMS

{n} -- number to test

*DESC

{PositiveNumber?(n)} evaluates to {True} if $n$ is (strictly) positive, i.e.
if $n>0$. If {n} is not a number the procedure returns {False}.

*E.G.

In> PositiveNumber?(6);
Result: True;

In> PositiveNumber?(-2.5);
Result: False;

*SEE Number?, NegativeNumber?, NotZero?, PositiveInteger?, PositiveReal?

*SOURCE org/mathpiper/scripts4/predicates/PositiveNumber_.mpws
==========
*CMD PositiveReal? --- test for a numerically positive value
*STD
*CALL
        PositiveReal?(expr)

*PARMS

{expr} -- expression to test

*DESC

This procedure tries to approximate "expr" numerically. It returns 
{True} if this approximation is positive. In case no approximation 
can be found, the procedure returns {False}. Note that round-off 
errors may cause incorrect
results.

*E.G.

In> PositiveReal?(Sin(1)-3/4);
Result: True;

In> PositiveReal?(Sin(1)-6/7);
Result: False;

In> PositiveReal?(Exp(x));
Result: False;

The last result is because [Exp(x)] cannot be
numerically approximated if [x] is not known. Hence
MathPiper can not determine the sign of this expression.

*SEE NegativeReal?, PositiveNumber?, NM

*SOURCE org/mathpiper/scripts4/predicates/PositiveReal_.mpws
==========

*CMD RationalFunction? --- test for a Rational function
*STD
*CALL
        RationalFunction?(expr)
        RationalFunction?(expr,var)
        RationalFunction?(expr,vars)

*PARMS

{expr} -- expression to test
{var}  -- (optional) variable
{vars} -- (optional) a list of variables

*DESC

This procedure tests whether the expression {expr} is a Rational
Function of the variable {var}.  If a list of variables {vars} is
provided, the test is made w.r.t.  all the variables in the list, and
returns True if any one of them succeeds.  If {var} is omitted, the
test is made w.r.t. the list VarList(expr).

*E.G.

In> RationalFunction?(3,x)  
Result: False

In> RationalFunction?(3)      
Result: False;

In> RationalFunction?(3.5,x)
Result:  False

In> RationalFunction?(3.5)
Result:  False 

In> RationalFunction?(3/5,x)
Result:  False 

In> RationalFunction?(3/5)
Result:  False 

In> RationalFunction?(x,y)
Result:  False 

In> RationalFunction?(x)
Result:  False 

In> RationalFunction?(x/y,x)
Result:  False 

In> RationalFunction?(x/y,y)
Result:  True

In> RationalFunction?(x/y)
Result:  True 

In> RationalFunction?(x/5,x)
Result:  False 

In> RationalFunction?(x/5)
Result:  False 

In> RationalFunction?(5/x,x)
Result:  True 

In> RationalFunction?(-5/x,x)
Result:  True 

In> RationalFunction?(5/x)
Result:  True 

In> RationalFunction?(-5/x)
Result:  True 

In> RationalFunction?(5/x,y)
Result:  False 

In> RationalFunction?(5/x,[y])
Result:  False 

In> RationalFunction?(5/x,[y,x])
Result:  False

In> RationalFunction?(5/y)
Result:  True 

In> RationalFunction?(1-1/x,x)
Result:  False 

In> RationalFunction?(1-1/x)
Result:  False


*SOURCE org/mathpiper/scripts4/predicates/RationalFunction_.mpws
==========
*CMD Rational? --- test whether argument is a rational
*STD
*CALL
        Rational?(expr)

*PARMS

{expr} -- expression to test

*DESC

This commands tests whether the expression "expr" is a rational
number, i.e. an integer or a fraction of integers.

*EXAMPLES
Rational?(5) -> True

Rational?(2/7) -> True

Rational?(0.5) -> False

Rational?('a/'b) -> False

Rational?('x + 1/'x) -> False

*SEE Numerator, Denominator

*SOURCE org/mathpiper/scripts4/predicates/Rational_.mpws
==========
*CMD SumOfTerms? --- check for expression being a sum of terms in variable

*STD
*CALL
        SumOfTerms?(var,expr)

*PARMS

{var} -- a variable name

{expr} -- an expression to be tested

*DESC

The command {SumOfTerms?} returns {True} if the expression {expr} can be 
considered to be a "sum of terms" in the given variable {var}.  The criteria
are reasonable but somewhat arbitrary.  The criteria were selected after
a lot of experimentation, specifically to aid the logic used in Integration.

The criteria for {expr} to be a sum of terms in {var} are:
     o  {expr} is a function of variable {var}
     o  {expr} can best be described as a sum (or difference) of two or more
        procedures of {var}  OR
        {expr} is a monomial in {var} (this latter is to simplify the logic)
     o  {expr} is not better described as a product of procedures of {var}
     o  {expr} is not better described as a quotient of procedures of {var}
        (i.e., is a rational function)

Note that the last three criteria are somewhat subjective!  

*E.G.
In> SumOfTerms?(x,23)
Result> False

In> SumOfTerms?(x,23*x)
Result> True

In> SumOfTerms?(x,5*y)
Result> False

In> SumOfTerms?(x,a*x^2-b*x-c/x)
Result> True

In> SumOfTerms?(x,Sin(x))
Result> False

In> SumOfTerms?(x,Sin(x)+Exp(x))
Result> True

In> SumOfTerms?(x,d*(x^2-1))
Result> True

In> SumOfTerms?(x,(x^2-1)*d)
Result> True

In> SumOfTerms?(x,(x^2-1)/d)
Result> True

In> SumOfTerms?(x,d/(x^2-1))
Result> False

In> SumOfTerms?(x,(x^2-1)*(x^2+1))
Result> False

In> SumOfTerms?(x,(x^2-1)/(x^2+1))
    Result> False    
    

*SOURCE org/mathpiper/scripts4/predicates/SumOfTerms_.mpws
==========
*CMD UpperTriangular? --- test for an upper triangular matrix
*STD
*CALL
        UpperTriangular?(A)

*PARMS

{A} -- a matrix

*DESC

An upper triangular matrix is a square matrix which has all zero entries below the diagonal.

{UpperTriangular?(A)} returns {True} if {A} is an upper triangular matrix and {False} otherwise.

*E.G.
In> UpperTriangular?(IdentityMatrix(5))
Result: True;

In> UpperTriangular?([[1,2],[0,1]])
Result: True;

A non-square matrix cannot be triangular:

In> UpperTriangular?([[1,2,3],[0,1,2]])
Result: False;

*SEE LowerTriangular?, Diagonal?

*SOURCE org/mathpiper/scripts4/predicates/UpperTriangular_.mpws
==========
*CMD ZeroVector? --- test whether list contains only zeroes
*STD
*CALL
        ZeroVector?(list)

*PARMS

{list} -- list to compare against the zero vector

*DESC

The only argument given to {ZeroVector?} should be
a list. The result is {True} if the list contains
only zeroes and {False} otherwise.

*E.G.

In> ZeroVector?([0, x, 0]);
Result: False;

In> ZeroVector?([x-x, 1 - Differentiate(x) x]);
Result: True;

*SEE List?, ZeroVector

*SOURCE org/mathpiper/scripts4/predicates/ZeroVector_.mpws
==========
*CMD Zero? --- test whether argument is zero
*STD
*CALL
        Zero?(n)

*PARMS

{n} -- number to test

*DESC

{Zero?(n)} evaluates to {True} if
"n" is zero. In case "n" is not a number, the procedure returns
{False}.

*EXAMPLES
Zero?(3.25) -> False

Zero?(0) -> True

Zero?('x) -> False

*SEE Number?, NotZero?

*SOURCE org/mathpiper/scripts4/predicates/Zero_.mpws
==========
*CMD Scalar? --- test for a scalar
*STD
*CALL

        Scalar?(expr)

*PARMS

{expr} -- a mathematical object

*DESC

{Scalar?} returns {True} if {expr} is a scalar, {False} otherwise.
Something is considered to be a scalar if it's not a list.

*E.G.
In> Scalar?(7)
Result: True;

In> Scalar?(Sin(x)+x)
Result: True;

In> Scalar?([x,y])
Result: False;

*SEE List?, Vector?, Matrix?

*SOURCE org/mathpiper/scripts4/predicates/matrix.mpws
==========
*CMD Vector? --- test for a vector
*STD
*CALL

        Vector?(expr)

        Vector?(pred,expr)

*PARMS

{expr} -- expression to test

{pred} -- predicate test (e.g. Number?, Integer?, ...)

*DESC

{Vector?(expr)} returns {True} if {expr} is a vector, {False} otherwise.
Something is considered to be a vector if it's a list of scalars.
{Vector?(pred,expr)} returns {True} if {expr} is a vector and if the
predicate test {pred} returns {True} when applied to every element of
the vector {expr}, {False} otherwise.

*E.G.
In> Vector?([_a,_b,_c])
Result: True;

In> Vector?([_a,[_b],_c])
Result: False;

In> Vector?(Integer?,[1,2,3])
Result: True;

In> Vector?(Integer?,[1,2.5,3])
Result: False;

*SEE List?, Scalar?, Matrix?

*SOURCE org/mathpiper/scripts4/predicates/matrix.mpws
==========
*CMD Matrix? --- test for a matrix
*STD
*CALL
        Matrix?(expr)

        Matrix?(pred,expr)

*PARMS

{expr} -- expression to test

{pred} -- predicate test (e.g. Number?, Integer?, ...)

*DESC

{Matrix?(expr)} returns {True} if {expr} is a matrix, {False} otherwise.
Something is considered to be a matrix if it's a list of vectors of equal
length.
{Matrix?(pred,expr)} returns {True} if {expr} is a matrix and if the
predicate test {pred} returns {True} when applied to every element of
the matrix {expr}, {False} otherwise.

*E.G.

In> Matrix?(1)
Result: False;

In> Matrix?([1,2])
Result: False;

In> Matrix?([[1,2],[3,4]])
Result: True;

In> Matrix?(Rational?,[[1,2],[3,4]])
Result: False;

In> Matrix?(Rational?,[[1/2,2/3],[3/4,4/5]])
Result: True;

*SEE List?, Vector?

*SOURCE org/mathpiper/scripts4/predicates/matrix.mpws
==========
*CMD SquareMatrix? --- test for a square matrix
*STD
*CALL
        SquareMatrix?(expr)

        SquareMatrix?(pred,expr)

*PARMS

{expr} -- expression to test

{pred} -- predicate test (e.g. Number?, Integer?, ...)

*DESC

{SquareMatrix?(expr)} returns {True} if {expr} is a square matrix,
{False} otherwise. Something is considered to be a square matrix if
it's a matrix having the same number of rows and columns.
{Matrix?(pred,expr)} returns {True} if {expr} is a square matrix and
if the predicate test {pred} returns {True} when applied to every
element of the matrix {expr}, {False} otherwise.

*E.G.

In> SquareMatrix?([[1,2],[3,4]]);
Result: True;

In> SquareMatrix?([[1,2,3],[4,5,6]]);
Result: False;

In> SquareMatrix?(Boolean?,[[1,2],[3,4]]);
Result: False;

In> SquareMatrix?(Boolean?,[[True,False],[False,True]]);
Result: True;

*SEE Matrix?

*SOURCE org/mathpiper/scripts4/predicates/matrix.mpws
==========
*CMD Manipulate --- manually manipulate expressions and solve equations

*CALL
    Manipulate(expression)

*PARMS
{expression} -- an expression

*DESC
A GUI application is shown that enables the manual manipulation of an expression.

 
*EXAMPLES
In> Manipulate('(8*x - 2 == -9 + 7*x))


/%mathpiper

rewriteRules := [];

ruleName := "Identity q_ + 0";
rule := [];
rule["RuleName"] := ruleName;
rule["Head"] := '( q_ +\$ 0 );
rule["Body"] := ''( q );
rule["DescriptionObjectLevel"] := ''("Eliminate additive identity.");
rule["DescriptionMetaLevel"] := "";
rule["ManualSequence"] := 1;
rule["HeadLatex"] :=  "q\\_ \\textcolor{green}{+} 0";
rule["BodyLatex"] := "q";
rewriteRules[ruleName] := rule;

ruleName := "Identity q_ * 1";
rule := [];
rule["RuleName"] := ruleName;
rule["Head"] := '( q_ *\$ 1 );
rule["Body"] := ''( q );
rule["DescriptionObjectLevel"] := ''("Eliminate Multiplicative identity.");
rule["DescriptionMetaLevel"] := "";
rule["ManualSequence"] := 2;
rule["HeadLatex"] :=  "q\\_ \\textcolor{green}{*} 1";
rule["BodyLatex"] := "q";
rewriteRules[ruleName] := rule;

ruleName := "Identity q_ * 0";
rule := [];
rule["RuleName"] := ruleName;
rule["Head"] := '( q_ *\$ 0 );
rule["Body"] := ''( 0 );
rule["DescriptionObjectLevel"] := ''("Multiply by Zero");
rule["DescriptionMetaLevel"] := "";
rule["ManualSequence"] := 3;
rule["HeadLatex"] :=  "q\\_ \\textcolor{green}{*} 0";
rule["BodyLatex"] := "0";
rewriteRules[ruleName] := rule;

Manipulate('((-1)*4 + (-1)*6)*_x == (-20), RewriteRules:rewriteRules, TabTitle:"Test");

/%/mathpiper


/%mathpiper

rewriteRules := [];


ruleName := "Or";
rule := [];
rule["RuleName"] := ruleName;
rule["Head"] := '( q_ |?$ r_ );
rule["Body"] := ''( q |? r );
rule["DescriptionObjectLevel"] := ''("None");
rule["DescriptionMetaLevel"] := "";
rule["ManualSequence"] := 1;
rule["HeadLatex"] :=  "q\\_\\text{ } \\textcolor{orange}{\\text{\|}?}\\text{ } r\\_";
rule["BodyLatex"] := "\\text{True or False}";
rewriteRules[ruleName] := rule;

ruleName := "And";
rule := [];
rule["RuleName"] := ruleName;
rule["Head"] := '( q_ &?$ r_ );
rule["Body"] := ''( q &? r );
rule["DescriptionObjectLevel"] := ''("None");
rule["DescriptionMetaLevel"] := "";
rule["ManualSequence"] := 1;
rule["HeadLatex"] :=  "q\\_\\text{ } \\textcolor{orange}{\\text{\\&}?}\\text{ } r\\_";
rule["BodyLatex"] := "\\text{True or False}";
rewriteRules[ruleName] := rule;

ruleName := "Not";
rule := [];
rule["RuleName"] := ruleName;
rule["Head"] := '( !?$ q_ );
rule["Body"] := ''( !? q );
rule["DescriptionObjectLevel"] := ''("None");
rule["DescriptionMetaLevel"] := "";
rule["ManualSequence"] := 1;
rule["HeadLatex"] :=  "\\textcolor{orange}{\\text{!}?}\\text{ } q\\_";
rule["BodyLatex"] := "\\text{True or False}";
rewriteRules[ruleName] := rule;


Manipulate('((!?$ False |?$ True) &?$ False |?$ True &?$ (True |?$ True)), RewriteRules:rewriteRules, TabTitle:"Test", Code:True);
/%/mathpiper

*SEE StepsView

*SOURCE org/mathpiper/scripts4/presston/Manipulate.mpws
==========
*CMD SolveSteps --- produce the steps that are needed to solve an equation

*CALL
    SolveSteps(equation, unknown)

*PARMS
{equation} -- an equation

{unknown} -- the variable to solve for


*DESC
Produce the steps that are needed to solve an equation. Returns the steps in a list.
Note: only equations that have a single occurrence of the unknown to be
solved for are currently supported.

 
*EXAMPLES
In> SolveSteps( ((- _a) * _b )/ _c + _d == _e , _a)

*SEE StepsView

*SOURCE org/mathpiper/scripts4/presston/SolveSteps.mpws
==========
*CMD StepsView --- create a graphics view of mathematical operation steps

*CALL
    StepsView(listOfSteps, option, option, ...)

*PARMS
{listOfSteps} -- a list of mathematical operation steps

{Options:}

{ShowTree} -- if True, include an expression tree with each step
{Scale} -- sets the size of the output


*DESC
Creates a graphics view of mathematical operation steps. 

Right click on the images that are displayed to save them.
 
*EXAMPLES
In> Symbols(a,b,c,d,e,f) 
Result: True

In> Show(StepsView(SolveSteps( ((- a) * b )/ c + d == e, a), ShowTree: True)) 
Result: class javax.swing.JFrame

In> Show(StepsView(SolveSteps( ((- a) * b )/ c + d == e, a), ShowTree: True, Scale: 2.1)) 
Result: class javax.swing.JFrame

In> Show(StepsView(SolveSteps( ((- a) * b )/ c + 2*d + 7 == e, a), ShowTree: True)) 
Result: class javax.swing.JFrame

In> Show(StepsView(SolveSteps( 7/b == c, b), ShowTree: True)) 
Result: class javax.swing.JFrame

In> Show(StepsView(SolveSteps( ((- a) * b^+f)/c+d == e, b), ShowTree: True)) 
Result: class javax.swing.JFrame

In> Show(StepsView(SolveSteps( ((- a) * b^2)/c+d == e, b), ShowTree: True)) 
Result: class javax.swing.JFrame

*SEE Show, SolveSteps

*SOURCE org/mathpiper/scripts4/presston/StepsView.mpws
==========
*CMD CDF --- cumulative distribution procedure
*STD
*CALL
        CDF(dist,x)

*PARMS
{dist} -- a distribution type

{x} -- a value of random variable

*DESC
The cumulative distribution procedure (CDF) (or just distribution procedure) describes the 
probability distribution of a real-valued random variable X. For every real number x, 
the CDF of X represents the probability that the random variable X takes on a value less 
than or equal to x.

*EXAMPLES
In> CDF(BernoulliDistribution(_x), -2) 
Result: 0

In> CDF(BernoulliDistribution(_x), 0.5) 
Result: _x

In> CDF(BernoulliDistribution(_x), 2) 
Result: 1

*SEE PDF, Expectation

*SOURCE org/mathpiper/scripts4/probability/CDF.mpws
==========
*CMD Expectation --- expectation procedure
*STD
*CALL
        Expectation(p)
        Expectation(p,n)

*PARMS
{p} -- number, probability of an event in a single trial

{n} -- number of trials

*EXAMPLES
In> Expectation(BernoulliDistribution(0)) 
Result: 1

In> Expectation(BernoulliDistribution(.3)) 
Result: 0.7

In> Expectation(BernoulliDistribution(1)) 
Result: 0

*SEE CDF, PDF

*SOURCE org/mathpiper/scripts4/probability/Expectation.mpws
==========
*CMD PDF --- probability density procedure
*STD
*CALL
        PDF(dist,x)

*PARMS
{dist} -- a distribution type

{x} -- a value of random variable

*DESC
{PDF}
returns the density procedure at point $x$.

The probability density procedure (PDF) of a continuous distribution is defined as the 
derivative of the (cumulative) distribution procedure.

*EXAMPLES
In> NM(PDF(ContinuousUniformDistribution(1.2, 2), 2)) 
Result: 1.25

In> NM(PDF(ContinuousUniformDistribution(1.3, 2), 2)) 
Result: 1.428571429

In> NM(PDF(ContinuousUniformDistribution(1.3, 3), 2)) 
Result: 0.5882352941

*SEE CDF, PMF, Expectation

*SOURCE org/mathpiper/scripts4/probability/PDF.mpws
==========
*CMD PMF --- probability mass procedure
*STD
*CALL
        PMF(dist,x)

*PARMS
{dist} -- a distribution type

{x} -- a value of random variable

*DESC
{PMF} returns the
probability for a random variable with distribution {dist} to take a
value of {x}.

*EXAMPLES
In> NM(PMF(BernoulliDistribution(.4), -2)) 
Result: 0

In> NM(PMF(BernoulliDistribution(.4), 1)) 
Result: 0.6

In> NM(PMF(BernoulliDistribution(.4), 2)) 
Result: 0

*SEE CDF, PDF, Expectation

*SOURCE org/mathpiper/scripts4/probability/PMF.mpws
==========
*CMD Apply --- apply a procedure to arguments
*STD
*CALL
        Apply(fn, arglist)

*PARMS

{fn} -- procedure to apply

{arglist} -- list of arguments

*DESC

This procedure applies the procedure "fn" to the arguments in
"arglist" and returns the result. The first parameter "fn" can
either be a string containing the name of a procedure or a pure
procedure. Pure procedures, modeled after lambda-expressions, have the
form "{varlist,body}", where "varlist" is the list of formal
parameters. Upon application, the formal parameters are assigned the
values in "arglist" (the second parameter of {Apply}) and the "body" is evaluated.

Another way to define a pure procedure is with the Lambda construct.
Here, instead of passing in "{varlist,body}", one can pass in
"Lambda(varlist,body)". Lambda has the advantage that its arguments
are not evaluated (using lists can have undesirable effects because
lists are evaluated). Lambda can be used everywhere a pure procedure
is expected, in principle, because the procedure Apply is the only procedure
dealing with pure procedures. So all places where a pure procedure can
be passed in will also accept Lambda.

An shorthand for {Apply} is provided by the {@} operator.

*EXAMPLES
In> Apply("+", [5,9]) 
Result: 14

In> Apply('[[x,y], x-y^2], [Cos(_a), Sin(_a)]) 
Result: Cos(_a) - Sin(_a)^2

In> Apply(Lambda([x,y], x-y^2), [Cos(_a), Sin(_a)]) 
Result: Cos(_a) - Sin(_a)^2
*SEE Map, MapSingle, @, Lambda

*SOURCE org/mathpiper/scripts4/procedural/Apply.mpws
==========
*CMD NumericProcedure --- make wrapper for numeric procedures
*STD
*CALL
        NumericProcedure("newname","funcname", [arglist])

*PARMS
{"newname"} -- name of new procedure

{"funcname"} -- name of an existing procedure

{arglist} -- symbolic list of arguments

*DESC
This procedure will define a procedure named "newname"
with the same arguments as an existing procedure named "funcname". The new procedure 
will evaluate and return the expression "funcname(arglist)" only when
all items in the argument list {arglist} are numbers, and return unevaluated otherwise.

This can be useful when plotting procedures defined through other MathPiper routines 
that cannot return unevaluated.

If the numerical calculation does not return a number (for example,
it might return the atom {nan}, "not a number", for some arguments),
then the new procedure will return {Undefined}.

This operator can help the user to program in the style of procedureal programming languages such as Miranda or Haskell.


*EXAMPLES
PKHG suggestion:

-  /%mathpiper,title="" 
-  f(x) := Decide( Number?(x), SinN(x),Sin(x)); 
-  NumericProcedure("f1", "f", ["x"]); 
-  Echo("indererminate arg _a --> ",f1(_a)); 
-  Echo("f1(0) = ",f1(0)," and f1(1) = ",f1(1)); 
-  Plot2D(f1(_x), 0 -> 1); //gives graphic! 
- 
-       /%output,sequence="33",timestamp="2013-10-27 11:45:44.214",preserve="false" 
-       Result: class org.jfree.chart.ChartPanel 
- 
-       Side Effects: 
-       indererminate arg _a --> f1(_a)  
-       f1(0) = 0  and f1(1) = 0.841470984807895 
/%/output

--------------------------------------------------------------------------------

In> f(x) := NM(Sin(x)) 
Result: True

In> NumericProcedure("f1", "f", ["x"]) 
Result: True

In> f1(_a) 
Result: f1(_a)

In> f1(0) 
Result: 0

Suppose we need to define a complicated procedure [t(x)]
which cannot be evaluated unless [x] is a number:

In> t(x) := Decide(x<=?0.5, 2*x, 2*(1-x)) 
Result: True

In> t(0.2) 
Result: 0.4

In> t(x) 
Result: Exception
Exception: Error: The variable <x> does not have a value assigned to it. Starting at index 2.

Then, we can use [NumericProcedure()] to define a wrapper [t1(x)] around 
[t(x)] which will not try to evaluate [t(x)] unless [x] is a number.

In> NumericProcedure("t1", "t", ["x"]) 
Result: True

In> t1("x") 
Result: t1("x")

In> t1(0.2) 
Result: 0.4

Now we can plot the procedure.

In> Plot2D(t1(_x), -0.1 :: 1.1) 
Result: class org.jfree.chart.ChartPanel

*SEE RuleEvaluateArguments

*SOURCE org/mathpiper/scripts4/procedural/NumericProcedure.mpws
==========
*CMD \\ --- apply a post procedure

*CALL
expression \\ procedure_name

*PARMS

{expression} -- an expression

{procedure_name} -- the name of a single argument procedure

*DESC
Apply a single argument procedure to the result of the expression
that is to the left of this operator

*EXAMPLES
In> 1/2 \\ NM 
Result: 0.5

*SEE /@

*SOURCE org/mathpiper/scripts4/procedural/backslash_backslash_operator.mpws
==========
*CMD .. --- construct a list of consecutive integers

*STD

*CALL
        n .. m

*PARMS

{n} -- integer. the first entry in the list

{m} -- integer, the last entry in the list

*DESC

This command returns the list {[n, n+1, n+2, ..., m]}. If {m} is
smaller than {n}, the empty list is returned. Note that the
{..} operator should be surrounded by spaces to keep the
parser happy, if "n" is a number. So one should write "{1 .. 4}" instead of "{1..4}".

This operator can help the user to program in the style of functional programming 
languages such as Miranda or Haskell.

*EXAMPLES
In> 1 .. 4 
Result: [1,2,3,4]

In> 7 .. 2 
Result: [7,6,5,4,3,2]

*SEE BuildList

*SOURCE org/mathpiper/scripts4/procedural/dot_dot_operator.mpws
==========
*CMD /@ --- apply a procedure to all entries in a list
*STD
*CALL
        fn /@ list

*PARMS

{fn} -- procedure to apply

{list} -- list of arguments

*DESC
This procedure is a shorthand for {MapSingle}. It
successively applies the procedure "fn" to all the entries in
"list" and returns a list contains the results. The parameter "fn"
must be a string containing the name of a procedure.

This operator can help the user to program in the style of functional 
programming languages such as Miranda or Haskell.

*EXAMPLES
In> "Sin" /@ [_a,3] 
Result: [Sin(_a),Sin(3)]

In> "Sin" /@ [2,4,NM(Pi,10), Pi] 
Result: [Sin(2),Sin(4),Sin(3.141592654),Sin(Pi)]

In> "SinN" /@ [2,4,NM(Pi,16)] 
Result: [0.9092974269,-0.7568024961,0.0000000003906125890]

In> Lambda([a],Sin(a)*a) /@ [_a,4] 
Result: [Sin(_a)*_a,4*Sin(4)]

*SEE MapSingle, Map, MapArgs, \\

*SOURCE org/mathpiper/scripts4/procedural/slash_atsign_operator.mpws
==========
*CMD Distance --- returns the distance between two points
*STD
*CALL
        Distance(p1, p2)
*PARMS

{p1} -- the first point

{p2} -- the second point

*DESC

This procedure calculates the distance between two points using the 
distance formula.

*E.G.


In> PointA := Point(2,3)
Result: [2,3]
        

In> PointB := Point(6,8)
Result: [6,8]
        

In> Distance(PointA, PointB)
Result: Sqrt(41)

*SEE Point?, Point, Midpoint, Slope, Segment

*SOURCE org/mathpiper/scripts4/proposed/geometry/Distance.mpws
==========
*CMD Midpoint --- returns a Point which represents the midpoint between two points
*STD
*CALL
        Midpoint(p1, p2)
        Midpoint(s)
*PARMS

{p1} -- the first point

{p2} -- the second point

{s} -- a segment

*DESC

This procedure calculates the midpoint between two points using the 
midpoint formula.

*E.G.


In> PointA := Point(2,3)
Result: [2,3]
        

In> PointB := Point(6,8)
Result: [6,8]
        

In> Midpoint(PointA, PointB)
Result: [4,11/2]


In> Midpoint(Segment(Point(0,0), Point(3,4)))
Result: [3/2,2]

*SEE Point?, Point, Distance, Slope, Segment

*SOURCE org/mathpiper/scripts4/proposed/geometry/Midpoint.mpws
==========
*CMD Point --- return a list which contains a point
*STD
*CALL
        Point(x, y)
        Point(x, y, z)
*PARMS

{x} -- x coordinate of the point

{y} -- y coordinatte of the point

{z} -- z coordinate of the point

*DESC

Creates either a 2D point or a 3D point.

*E.G.


In> Point(5,2)
Result: [5,2]

*SEE Point?, Midpoint, Distance, Slope, Segment

*SOURCE org/mathpiper/scripts4/proposed/geometry/Point.mpws
==========
*CMD Point? --- test for a point
*STD
*CALL
        Point?(p)
*PARMS

{p} -- point to test


*DESC

Tests if a value is a point.

*E.G.


In> p := Point(2,3)
Result: [2,3]
        

In> Point?(p)
Result: True
        

In> Point?(4)
Result: False
        
*SEE Point, Midpoint, Distance, Slope, Segment

*SOURCE org/mathpiper/scripts4/proposed/geometry/Point_.mpws
==========
*CMD Segment --- returns a list which contains the endpoints of a segment
*STD
*CALL
        Segment(p1, p2)
*PARMS

{p1} -- the first endpoint

{p2} -- the second endpoint

*DESC

This procedure returns a list which represents a segment by its endpoints.

*E.G.


In> PointA := Point(2,3)
Result: [2,3]
        

In> PointB := Point(6,8)
Result: [6,8]
        

In> Segment(PointA,PointB)
Result: [[2,3],[6,8]]

*SEE Point?, Point, Distance, Slope

*SOURCE org/mathpiper/scripts4/proposed/geometry/Segment.mpws
==========
*CMD Segment? --- test for a segment
*STD
*CALL
        Segment?(s)
*PARMS

{s} -- segment to test


*DESC

Tests if a value is a segment.

*E.G.


In> Segment?(Segment(Point(0,0), Point(3,4)))
Result: True
        

In> Segment?([3,4])
Result: False
        
*SEE Point, Midpoint, Distance, Slope, Segment

*SOURCE org/mathpiper/scripts4/proposed/geometry/Segment_.mpws
==========
*CMD Slope --- returns the slope of a line which is represented by two points
*STD
*CALL
        Slope(p1, p2)
        Slope(Segment(p1, p2))
*PARMS

{p1} -- the first point

{p2} -- the second point

*DESC

This procedure calculates the slope between two points or of a 
segment using the slope formula.

*E.G.


In> PointA := Point(2,3)
Result: [2,3]
        

In> PointB := Point(6,8)
Result: [6,8]
        

In> Slope(PointA,PointB)
Result: 5/4


In> s := Segment(PointA,PointB)
Result: [[2,3],[6,8]]
        

In> Slope(s)
Result: 5/4

*SEE Point?, Point, Distance, Midpoint, Segment

*SOURCE org/mathpiper/scripts4/proposed/geometry/Slope.mpws
==========
*CMD BooleanList --- returns a list that contains boolean values

*CALL
        BooleanList(elements, integerBitPattern)

*PARMS
{elements} -- an integer that contains the desired number of elements in the returned list.

{integerBitPattern} -- a integer that (when converted to binary) has a bit pattern that matches the desired boolean pattern.

*DESC
Returns a list that contains boolean values that match the binary equivalent of the integer in {integerBitPattern}. 
The list is padded with leading {False} values to match the specified number of elements, if needed.

*E.G.
In> BooleanList(8, 5)
Result: [False,False,False,False,False,True,False,True]

*SEE BooleanLists, TruthTable


*SOURCE org/mathpiper/scripts4/proposed/logic/BooleanList.mpws
==========
*CMD BooleanLists --- returns a list that contains lists that hold a sequence of boolean values

*CALL
        BooleanLists(elements)

*PARMS
{elements} -- an integer that contains the desired number of boolean lists in the returned list.


*DESC
Returns a list that contains lists that hold a sequence of boolean values. The first list in the sequence 
contains all {False} values and the rest of the lists contain patterns of boolean values up through 
all {True} values.

*E.G.
In> BooleanLists(2)
Result: [[False,False],[False,True],[True,False],[True,True]]

*SEE BooleanList, TruthTable


*SOURCE org/mathpiper/scripts4/proposed/logic/BooleanLists.mpws
==========
*CMD Subexpressions --- returns a list that contains all of the subexpressions in an expression

*CALL
        Subexpressions(expression)

*PARMS
{expression} -- an expression.

*DESC
Returns a list that contains all of the subexpressions in an expression. The list does not contain any duplicates 
and the subexpressions are arranged in order from shortest to longest.

*E.G.
In> Subexpressions(_a*_b+_c)
Result: [_a,_b,_c,_a*_b,_a*_b+_c]

*SEE TruthTable


*SOURCE org/mathpiper/scripts4/proposed/logic/Subexpressions.mpws
==========
*CMD TruthTable --- returns a list that contains a truth table for a boolean expression

*CALL
        TruthTable(booleanExpression)

*PARMS
{booleanExpression} -- a boolean expression.

*DESC
Returns a list that contains a truth table for a boolean expression. The truth table is returned as a 
list of lists.

*E.G.
In> za := TruthTable(_a &? _b)
Result: [[_a,_b,_a &? _b],[True,True,True],[True,False,False],[False,True,False],[False,False,False]]

//Substitute T and F for True and False.
In> zb := (za /: [True -> 'T, False -> 'F])
Result: [[a,b,a &? b],[T,T,T],[T,F,F],[F,T,F],[F,F,F]]

//View the table in traditional mathematics format.
In> ViewMath(zb)
Result: class javax.swing.JFrame 

In> za2 := TruthTable(0 &? _b)
Result: [[_b,0 &? _b],[True,0],[False,False]]

In> zb := (za2 /: [True -> 'T, False -> 'F])
Result: [[_b,0 &? _b],[T,0],[F,F]]


Tautology example

In> TruthTable(ObjectToMeta('((!?(!?(p &? q) &? !?(p &? r)) |? (!?(p &? (q |? r)))))))
Result: [[_p,_q,_r,_q |? _r,_p &? _q,_p &? _r, !? (_p &? _q), !? (_p &? _r),_p &? (_q |? _r), !? (_p &? (_q |? _r)), !? (_p &? _q) &?  !? (_p &? _r), !? ( !? (_p &? _q) &?  !? (_p &? _r)), !? ( !? (_p &? _q) &?  !? (_p &? _r)) |?  !? (_p &? (_q |? _r))],[True,True,True,True,True,True,False,False,True,False,False,True,True],[True,True,False,True,True,False,False,True,True,False,False,True,True],[True,False,True,True,False,True,True,False,True,False,False,True,True],[True,False,False,False,False,False,True,True,False,True,True,False,True],[False,True,True,True,False,False,True,True,False,True,True,False,True],[False,True,False,True,False,False,True,True,False,True,True,False,True],[False,False,True,True,False,False,True,True,False,True,True,False,True],[False,False,False,False,False,False,True,True,False,True,True,False,True]]


*SEE Subexpressions, BooleanList, BooleanLists


*SOURCE org/mathpiper/scripts4/proposed/logic/TruthTable.mpws
==========
*CMD CombinationsList --- return all of the combinations from a given list taken r at a time
*CALL
        CombinationsList(list,r)

*PARMS
{list} -- a list of elements

{r} -- the combinations from {list} are to be taken {r} at a time

*DESC
This procedure returns a list which contains all of the combinations of the elements in a 
given list taken r elements at a time.

*E.G.

In> CombinationsList([1,2,3],2)
Result: [[1,2],[1,3],[2,3]]

*SEE Combinations, PermutationsList, Permutations

*SOURCE org/mathpiper/scripts4/proposed/miscellaneous/CombinationsList.mpws
==========

*CMD DisassembleExpression --- returns a list describing composition of an expression

*STD
*CALL
        DisassembleExpression(expr)
        DisassembleExpression(expr,vars)

*PARMS

{expr} -- an expression

{vars} -- a list of variable names

*DESC

This procedure is primarily used to succinctly describe the components of a
polynomial, but it can also be used with some non-polynomial expressions.  

The command {DisassembleExpression(expr)} returns a list composed of three elements:

    1. a list of the variable names in the expression
    
    2. a list of the powers of each variable in each term
    
    3. a list of the coefficients of these powers in each term
    
This list-of-lists comprises in essence a sparse database containing a 
complete representation of the expression.  Any procedure which needs to 
examine and process the terms of an expression, in sequence, can use
{DisassembleExpression} as a starting point.

If the first form, {DisassembleExpression(expr)}, is used, MathPiper will
employ the procedure "MultiExpressionList" to try to extract the names of all the
"variables" in the expression -- which may or may not result in
the list you would prefer to get.  In particular, if {expr} contains
"parameters" in addition to "variables", MathPiper cannot distinguish them,
and considers them all to be "variables".
This is where the user should employ the second form, in which a preferred set
of variables is explicitly given.  See the examples below.

The pair of procedures, {DisassembleExpression} and {ReassembleListTerms}, 
together constitute a foundation for the analysis of polynomials and -- more
generally -- any expressions which can be regarded as sum or difference of terms.

*E.G.

In> uu:=ExpandBrackets((x+1)^4)
Result: x^4+4*x^3+6*x^2+4*x+1


In> DisassembleExpression(uu)
Result: [[x],[[4],[3],[2],[1],[0]],[1,4,6,4,1]]
    clear signature of binomial expansion in coefficients list


In> vv:=ExpandBrackets((x+y)^4)
Result: x^4+4*x^3*y+6*x^2*y^2+4*x*y^3+y^4


In> DisassembleExpression(vv)
Result: [[x,y],[[4,0],[3,1],[2,2],[1,3],[0,4]],[1,4,6,4,1]]
    same signature


In> vv:=ExpandBrackets((a*x+b*y)^4)
Result: a^4*x^4+4*a^3*x^3*b*y+6*a^2*x^2*b^2*y^2+4*a*x*b^3*y^3+b^4*y^4


In> DisassembleExpression(vv)
Result: [[a,x,b,y],[[4,4,0,0],[3,3,1,1],[2,2,2,2],[1,1,3,3],[0,0,4,4]],[1,4,6,4,1]]
    parameters [a,b] mistaken for variables, but binomial signature still visible


In> DisassembleExpression(vv,[x,y])
Result: [[x,y],[[4,0],[3,1],[2,2],[1,3],[0,4]],[a^4,4*b*a^3,6*b^2*a^2,4*b^3*a,b^4]]
    user guidance helps distinguish parameters from variables,
    but binomial signature still visible


In> ww:=x+2*Sqrt(x)+1
Result: x+2*Sqrt(x)+1


In> DisassembleExpression(ww)
Result: [[x,Sqrt(x)],[[1,0],[0,1],[0,0]],[1,2,1]]
    [MultiExpressionList] identified as "variables" both [x] and
    [Sqrt(x)] -- we call the latter a [quasi-variable].  See documentation for
    [ReassembleListTerms] for an example of how this can be used to perform
    automatic substitution of variables.

*SEE ReassembleListTerms

*SOURCE org/mathpiper/scripts4/proposed/miscellaneous/DisassembleExpression.mpws
==========
*CMD EchoAppend! --- prints items into a protected list
*STD
*CALL
        EchoAppend!(item,item,item,...)

*PARMS

{item} -- the items to be printed


*DESC

If passed a single item, {EchoAppend!} will evaluate it and append it to 
?echoAppendList, followed by a newline.

If {EchoAppend!} is called with a variable number of arguments, they will all
be appended and finally a newline will be appended.

If no arguments are passed to {EchoAppend!}, it will simply append a newline.

{EchoAppend!} always returns {True}.

*E.G.
In> ?echoAppendList := [];
Result: []

In> EchoAppend!(1,"Hello",1/2)
Result: [1,"Hello",1/2,"
"]

In> ?echoAppendList
Result: [1,"Hello",1/2,"
"]
 

*SEE Echo

*SOURCE org/mathpiper/scripts4/proposed/miscellaneous/EchoAppend!.mpws
==========
*CMD ElementCount --- counts the number of elements in a list or nested list
*CALL
        ElementCount(list)

*PARMS
{list} -- a list or nested list

*DESC
Counts the number of elements in a list or nested list.

*E.G.

In> ElementCount([1,2,3,4])
Result: 4


In> ElementCount([1,2,[3,4],5,6])
Result: 6

*SOURCE org/mathpiper/scripts4/proposed/miscellaneous/ElementCount.mpws
==========
*CMD ListOfLists? --- determine if [list] is a list of lists
*STD
*CALL
        List?(list)

*PARMS
{expr} -- a list

*DESC
This procedure returns {True} if {list} is a list of lists and {False} otherwise.

*E.G.
In> ListOfLists?(aa);
Result: False

In> ListOfLists?([1,2,3])
Result: False

In> ListOfLists?([[1,2],[3,4],[5,6]])
Result: True
    

*SOURCE org/mathpiper/scripts4/proposed/miscellaneous/ListOfLists_.mpws
==========
*CMD LocalCreate --- create a string that contains a call to the procedure "Local" 
*CALL
    LocalCreate()

    
*DESC
This procedure is used to create a call to the procedure "Local" using all of the global
variables that are currently assigned as arguments. It is useful for adding a call to 
the procedure "Local" as the last part of the following procedure definition process:

1) Define the procedure.
2) Test the procedure for correct operation.
3) Unassign all global variables.
4) Call the procedure once.
5) Call LocalCreate().
6) Paste the generated call to the procedure "Local" into the top of the procedure definition.


*E.G.
In> Unassign(All)
Result: True

In> arg1 := 3
Result: 3

In> arg2 := 5
Result: 5

In> State()
Result: [arg1:3,arg2:5]

In> LocalCreate()
Result: True
Side Effects:
Local(arg2, arg1);

*SOURCE org/mathpiper/scripts4/proposed/miscellaneous/LocalCreate.mpws
==========
*CMD NumberLinePrintZoom --- zooms into the number line
*STD
*CALL
        NumberLinePrintZoom(low_number, high_number, divisions, depth)

*PARMS

{low_value} -- lowest number in the zoom range

{high_value} -- highest number in the zoom range

{divisions} -- how many parts to divide the range into

{depth} -- continue the zooming process to depth levels

*DESC

This procedure allows sections of the number line to be displayed.  If rational numbers are
passed to low_number and high_number, rational numbers are displayed and if decimal
numbers are passed to low_number and high_number, decimal numbers are displayed.

*E.G. notest

In> NumberLinePrintZoom(0/1,1/1,8,1)
Result: True
Side Effects:
0   1/8   1/4   3/8   1/2   5/8   3/4   7/8   1

In> NumberLinePrintZoom(0/1,1/1,10,1)
Result: True
Side Effects:
0   1/10   1/5   3/10   2/5   1/2   3/5   7/10   4/5   9/10   1

In> NumberLinePrintZoom(0/1,1/1,20,1)
Result: True
Side Effects:
0   1/20   1/10   3/20   1/5   1/4   3/10   7/20   2/5   9/20   1/2   11/20   3/5   13/20   7/10   3/4   4/5   17/20   9/10   19/20   1

In> NumberLinePrintZoom(0/1,1/1,8,4)
Result: True
Side Effects:
0   1/8   1/4   3/8   1/2   5/8   3/4   7/8   1   
                          |
----------------------------------------------------------------
1/2   33/64   17/32   35/64   9/16   37/64   19/32   39/64   5/8   
    |
--------------------------------------------------------------------------------
1/2   257/512   129/256   259/512   65/128   261/512   131/256   263/512   33/64   
                                                                         |
--------------------------------------------------------------------------------------------------
263/512   2105/4096   1053/2048   2107/4096   527/1024   2109/4096   1055/2048   2111/4096   33/64  



In> NumberLinePrintZoom(0.0,1.0,8,1)
Result: True
Side Effects:
0.0   0.125   0.250   0.375   0.500   0.625   0.750   0.875   1.000

In> NumberLinePrintZoom(0.0,1.0,10,1)
Result: True
Side Effects:
0.0   0.1   0.2   0.3   0.4   0.5   0.6   0.7   0.8   0.9   1.0

In> NumberLinePrintZoom(0.0,1.0,20,1)
Result: True
Side Effects:
0.0   0.05   0.10   0.15   0.20   0.25   0.30   0.35   0.40   0.45   0.50   0.55   0.60   0.65   0.70   0.75   0.80   0.85   0.90   0.95   1.00

In> NM(NumberLinePrintZoom(0.0,1.0,8,4),6)
Result: True
Side Effects:
0.0   0.125   0.250   0.375   0.500   0.625   0.750   0.875   1.000   
                                    |
---------------------------------------------------------------------------------------------
0.500   0.515625   0.531250   0.546875   0.562500   0.578125   0.593750   0.609375   0.625000   
                                       |
------------------------------------------------------------------------------------------------
0.546875   0.548828   0.550781   0.552734   0.554687   0.556640   0.558593   0.560546   0.562499   
                                                                           |
------------------------------------------------------------------------------------------------
0.558593   0.558837   0.559081   0.559325   0.559569   0.559813   0.560057   0.560301   0.560545


*SOURCE org/mathpiper/scripts4/proposed/miscellaneous/NumberLinePrintZoom.mpws
==========
*CMD OptionsToAssociationList --- converts an options list into an associative list
*CALL
        OptionsToAssociationList(optionsList)

*PARMS
{optionsList} -- an options list to be converted into an associative list

*DESC
This procedure converts a list of options in the form of {name: value, name: value}
into an associative list.

*E.G.
In> OptionsToAssociationList([a: 1, b: 2])
Result> [["b",2],["a",1]]


*SOURCE org/mathpiper/scripts4/proposed/miscellaneous/OptionsToAssociationList.mpws
==========
*CMD PadLeft --- converts a number into a string which has a specified width
*STD
*CALL
        PadLeft(number,stringWidth)
        PadLeft(number,stringWidth, padValue)

*PARMS

{number} -- an integer or a decimal number to convert to a string

{stringWidth} -- the width of the string

{padValue} a value to use as the pad instead of 0

*DESC

This procedure converts a number into a string which has a specified width.  If the number
would normally be converted into a string with fewer characters than this width, zero (or
 {padValue} is added to the left side of the string to make it the specified width.

*E.G.
/%mathpiper,title=""

Echo(PadLeft(.1,3));
Echo(PadLeft(20,3));
Echo(PadLeft(5,3));
Echo(PadLeft(5,3,"_"));

/%/mathpiper

    /%output,preserve="false"
      Result: True
      
      Side Effects:
      0.1
      020
      005
      __5
.   /%/output

*SOURCE org/mathpiper/scripts4/proposed/miscellaneous/PadLeft.mpws
==========

*CMD PolynomialCurveFit --- create a polynomial that approximates a set of data points

*CALL
        PolynomialCurveFit(data, var, numberOfCoefficients)

*PARMS

{data} -- the data in [[x1, y1], [x2, y2], ..., [xn, yn]] format
{var} -- the polynomial variable (example: _x)
{numberOfEoefficients} -- the number of coefficients in the polynomial.

*DESC
This procedure creates a polynomial that approximates a set of data points.

*E.G.

In> aa := PolynomialCurveFit(NM(BuildList([xx,Sin(xx`rad)], xx, 0, 3, .1)), _x, 2)
Result: -0.04662836748 + 1.31216376 * _x +  -0.418997742 * _x^2


*SOURCE org/mathpiper/scripts4/proposed/miscellaneous/PolynomialCurveFit.mpws
==========
*CMD RandomBooleanExpression --- generate a random boolean expression

*CALL
    RandomBooleanExpression(depth, booleanTerms?)

*PARMS

{depth} -- the maximum depth of the expression's tree

{booleanTerms?} -- use boolean constants instead of integer constants

*DESC

This procedure generates random boolean expressions that
have a specified maximum depth. The operators in the
expressions are meta-level versions of their object-level
counterparts that don't evaluate their operands.

*E.G.
RandomBooleanExpression(3, False)
Result: 7 <=?\$ 9 &?\$ (8 >?\$ 9 |?\$ 7 >=?\$ 6)

In> RandomBooleanExpression(3, True)
Result: True |?\$ False &?\$ (False |?\$ True)


*SOURCE org/mathpiper/scripts4/proposed/miscellaneous/RandomBooleanExpression.mpws
==========

*CMD ResassembleListTerms --- returns a list of the terms in an expression

*STD
*CALL
        ResassembleListTerms(disassembly)

*PARMS

{disassembly} -- a disassembly list generated by {DisassembleExpression}

*DESC

After an expression (usually, but not always, a polynomial) has been disassembled
by the procedure {DisassembleExpression}, the procedure 
{ReassembleListTerms} converts this into a list of the individual terms
in the expression.  

This is useful in itself, because a list of terms can be processed term-by-term
in any desired manner.

But also, the items in the disassembly may be transformed in various ways before
being reassembled.  This can facilitate automatic transformations of
polynomials or expressions into forms more convenient for further processing.

See the examples below.

The pair of procedures, {DisassembleExpression} and {ReassembleListTerms}, 
together constitute a foundation for the analysis of polynomials and -- more
generally -- any expressions which can be regarded as sum or difference of terms.

*E.G.
    

In> ww:=x+2*Sqrt(x)+1
Result: x+2*Sqrt(x)+1
    This expression is really a disguised quadratic


In> ex:=DisassembleExpression(ww)
Result: [[x,Sqrt(x)],[[1,0],[0,1],[0,0]],[1,2,1]]
    The disassembly has recognized Sqrt(x) as a quasi-variable


In> exx:=Substitute([x,Sqrt(x)],[t^2,t])ex
Result: [[t^2,t],[[1,0],[0,1],[0,0]],[1,2,1]]
    An algorithm could observe the list [x,Sqrt(x)] and automatically
    perform the substitution to make a change-of-variables


In> Sum(ReassembleListTerms(exx))
Result: t^2+2*t+1
    The expression has now been transformed into an obvious quadratic,
    which can now be solved.


*SEE DisassembleExpression

*SOURCE org/mathpiper/scripts4/proposed/miscellaneous/ReassembleListTerms.mpws
==========
*CMD StringToList --- converts a string into a list
*STD
*CALL
        StringToList(string)

*PARMS

{string} -- a string to be converted into a list

*DESC

This procedure takes each character in a string and places it into a list.

*E.G.
In> StringToList("Hello")
Result: ["H","e","l","l","o"]

*SEE ListToString

*SOURCE org/mathpiper/scripts4/proposed/miscellaneous/StringToList.mpws
==========
*CMD StringToNumber --- Convert a base-10 number in string form to its numeric value
*STD
*CALL
        StringToNumber(numberString)

*PARMS

{numberString} -- a decimal (base-10) number represented as a string

*DESC

{StringToNumber} Converts the string representation of a number into the value of that number.



*E.G.


In> Number?("1234")
Result: False
    

In> StringToNumber("1234")
Result: 1234
    

In> Number?(%)
Result: True
    

In> StringToNumber("0.12345678")
Result: 0.12345678
    

In> StringToNumber("0.12345678E4")
Result: 1234.5678


*SOURCE org/mathpiper/scripts4/proposed/miscellaneous/StringToNumber.mpws
==========
*CMD UnderscoreConstants --- list of underscore constants appearing in an expression (with duplicates)

*CALL
        UnderscoreConstants(expression)

*PARMS

{expression} -- an expression


*DESC

The command {UnderscoreConstants(expression)} returns a list of all underscore 
constants (without duplicates) that appear in the expression {expression}.


*E.G.

In> UnderscoreConstants(_a + _b - _c / _a)
Result: [_a,_b,_c,_a]

*SEE UnderscoreConstantsAll, VarList, VarListAll

*SOURCE org/mathpiper/scripts4/proposed/miscellaneous/UnderscoreConstants.mpws
==========
*CMD UnderscoreConstantsAll --- list of underscore constants appearing in an expression (with duplicates)

*CALL
        UnderscoreConstantsAll(expression)

*PARMS

{expression} -- an expression


*DESC

The command {UnderscoreConstantsAll(expression)} returns a list of all underscore 
constants (including duplicates) that appear in the expression {expression}.


*E.G.

In> UnderscoreConstantsAll(_a + _b - _c / _a)
Result: [_a,_b,_c,_a]

*SEE UnderscoreConstants, VarList, VarListAll

*SOURCE org/mathpiper/scripts4/proposed/miscellaneous/UnderscoreConstantsAll.mpws
==========
*CMD VariablesDump --- output the names of the passed-in variables along with their values 
*CALL
    VariablesDump(var1, var2, ...)

    
*DESC
This procedure is used to generate a dump of the specified variables.

*PARMS
{var} -- the name of a variable (either within or not within double quotes)

*E.G.
In> numberOfPeople := 4
Result: 4

In> costPerPerson := 8
Result: 8

In> VariablesDump(numberOfPeople, costPerPerson)
Result: True
Side Effects:
numberOfPeople: 4
costPerPerson: 8


*SOURCE org/mathpiper/scripts4/proposed/miscellaneous/VariablesDump.mpws
==========
*CMD VariablesReport --- output a description of the passed-in variables along with their values 
*CALL
    VariablesReport(var1, var2, ...)

    
*DESC
This procedure is used to generate a quick report that consists of the names
of variables separated into separate words along with the values of these variables.
The output is provided as a side effect.

*PARMS
{var} -- the name of a variable (either within or not within double quotes)

*E.G.
In> numberOfPeople := 4
Result: 4

In> costPerPerson := 8
Result: 8

In> VariablesReport(numberOfPeople, costPerPerson)
Result: True
Side Effects:
Number of people: 4
Cost per person: 8


*SOURCE org/mathpiper/scripts4/proposed/miscellaneous/VariablesReport.mpws
==========
*CMD VerifyNumeric --- numerically evaluates two expressions to indicate if they may be equivalent or not
*STD
*CALL
        Verify(symbolicExpression1,symbolicExpression2,variableAssignmentList)
    
    Verify(numericExpression1,numericExpression2)

*PARMS
{symbolicExpression1} -- a symbolic expression

{symbolicExpression2} -- a symbolic expression

{variableAssignmentList} -- a list which contains variable assignments in the form {b: 7,a: 4}

{numericExpression1} -- a numeric expression

{numericExpression2} -- a numeric expression

*DESC
The symbolic expression version of this procedure numerically evaluates two symbolic expressions to indicate if
they may be equivalent or not. The values to set the variables to are contained in {variableAssignmentList}.

The numeric expression version of this procedure evaluates two numeric expressions to indicate if they are
equivalent or not.

*E.G.

In> VerifyNumeric((72*a^3*b^5)^(1/2), 6*a*b^2*(2*a*b)^(1/2), [b: 7,a: 4])
Result: 0.000000
Side Effects:
a->4 b->7 

Sqrt(72*a^3*b^5) -> 8800.378174 

6*a*b^2*Sqrt(2*a*b) -> 8800.378174 

Difference between the numeric values: 0.000000 




In> VerifyNumeric(.5,1/2)
Result: 0.0
Side Effects:
.5 -> 0.5 

1/2 -> 0.5 

Difference between the numeric values: 0.0 



*SOURCE org/mathpiper/scripts4/proposed/miscellaneous/VerifyNumeric.mpws
==========
*CMD ∠ --- number in polar form

*CALL
    magnitude ∠ angle

*PARMS

{magnitude} -- a number
{angle} -- a number between 0 and 360 (units are degrees)

*DESC
Represents a number in polar form.


*E.G.
In> 3∠30
Result: 3∠30


*SOURCE org/mathpiper/scripts4/proposed/miscellaneous/angle_operator.mpws
==========
*CMD /`` --- list injection

*CALL
        /`` [..., @@aList, ...]
        /`` {...; @@aList; ...;}

*PARMS

{aList} -- list to inject

*DESC

Any variable prefixed by "@@" is first substituted into an expression using {/`} macro substitution,
and then is 'pulled' into the parent container, instead of staying as a list its conents become a part
of the container. 

Any variable prefixed by "@" is substituted into an expression using normal {/`} macro substitution.

This interacts well with MathPiper's Blank Sequence pattern matching, allowing complex substitutions to procedures to be obtained

*E.G.
In> aList := [1, 2, 3]
Result: [1,2,3]

Note the difference between /` and /`` in the following examples

In> /` [0, @aList]
Result: [0,[1, 2, 3]]

In> /`` [0, @@aList]
Result: [0,1,2,3]


The same operator works with a List as a parent and a Sequence

In> bList := [Hold(index--), Hold(Echo(index))]
Result: [index--,Echo(index)]

In> /`` '{index := 10; @@bList;}
Result: {
  index := 10;

  index--;

  Echo(index);
}


The following uses /`` to define Sequence concatenation globally:

In> {a___;} + {b___;} --> /`` ' {@@a; @@b;}
Result: True

In> aSequence := '{index := 10; index++;}
Result: {
  index := 10;

  index++;
}

In> bSequence := '{index--; Echo(index);}
Result: {
  index--;

  Echo(index);
}

In> aSequence + bSequence
Result: {
  index := 10;

  index++;

  index--;

  Echo(index);
}


Finally, converting a common While loop into a For loop. Note how /`` interacts with @ as well as @@

In> code := '{index := 10; Echo(index); While(index <=? 20) { Echo(index); index++; } Echo(index);}
Result: {
  index := 10;

  Echo(index);

  While(index <=? 20)
  {
    Echo(index);

    index++;
  }

  Echo(index);
}

In> whileMatchRule := '{a___; predicateVar_ := initValue_Number?; b___; While(predicateVar_ <=? endValue_Number?) {c___; increment_;} d___;}
Result: {
  a___;

  predicateVar_ := initValue_Number?;

  b___;

  While(predicateVar_ <=? endValue_Number?)
  {
    c___;

    increment_;
  }

  d___;
}

In> SubstitutePosition(code, "", whileMatchRule, ' /`` ' {@@a; @@b; For(@predicateVar := @initValue, @predicateVar <=? @endValue, @increment) { @@c; } @@d; })
Result: {
  Echo(index);

  For(index := 10,index <=? 20,index++ )
  {
    Echo(index);
  }

  Echo(index);
}

*SEE /`

*SOURCE org/mathpiper/scripts4/proposed/miscellaneous/backquote_backquote_operator.mpws
==========
*CMD NotationCongruent --- takes a magnitude and replaces all SI units with their congruent counterparts.

*CALL
        NotationCongruent(magnitude)

*PARMS

{magnitude}    -- A number or a number with units


*DESC

The {NotationCongruent} procedure takes a {magnitude}, a number or a 
number with a unit, and converts all SI units, if they are present, to
their SI congruent form by removing all prefixed units and multiplying
the number part of the {magnitude} by the appropriate factor. All SI 
units will be reduced to a prefixless form except grams which will be 
reduced to kg per the SI convention. All non-SI units will remain 
unchanged. If the {magnitude} passed to {NotationCongruent} has no SI 
units or no units at all, then the {magnitude} will be returned unchanged


*EXAMPLES
In> NotationCongruent(15`(mA)) 
Result: 0.015`A

In> NotationCongruent(15.3) 
Result: 15.3

In> NotationCongruent(42`ft) 
Result: 42`ft

In> NotationCongruent(31231`(g*mA/(nm * hour))) 
Result: 31231000`((A * kg) / (m * hour))

In> NotationCongruent(4`dag) 
Result: 0.04`kg

*SEE NotationEngineering, NotationScientific, NotationStandard


*SOURCE org/mathpiper/scripts4/proposed/notation/NotationCongruent.mpws
==========

*CMD NotationEngineering --- takes a magnitude and replaces all SI units with their congruent counterparts.

*CALL
        NotationEngineering(magnitude)

*PARMS

{magnitude}    -- A number with at least one SI unit


*DESC

{NotationEngineering} takes a {magnitude} that must contain at least one 
SI unit. {NotationEngineering} transforms all SI units into their 
prefixless counterparts and multiplies the value of the {magnitude} by
the appropriate factor. {NotationEngineering} then multiplies the value
by a factor that places the value between -1000 and 1000 exclusive. An
appropriate prefix is then added to the left most SI unit in the
magnitude}'s unit expression tree.


*EXAMPLES
In> NotationEngineering(13200.23`nm) 
Result: 13.20023`μm

In> NotationEngineering(23.5`(km^2)) 
Result: 23.5`(Mm * m)

In> NotationEngineering(44000.3`(1/Ω)) 
Result: 44.0003`(1 / mΩ)

*SEE NotationCongruent, NotationScientific, NotationStandard


*SOURCE org/mathpiper/scripts4/proposed/notation/NotationEngineering.mpws
==========
*CMD NotationScientific --- takes a magnitude, replaces SI units with prefixless counterparts and puts  the value into scientific notation.

*CALL
        NotationScientific(magnitude)

*PARMS

{magnitude}    -- A number or number with units


*DESC

{NotationScientific} accepts a {magnitude}, a number or a number with
units, and replaces all instances of SI units in {magnitude} with 
prefixless counterparts and multiplies the value by the appropriate 
factor. The value is then placed into "E" scientific form. If no SI units
are present or no units are present at all in {magnitude}, then the value 
will still be transformed into "E" form notation. The mantissa (number to 
the left of "E") will always  be a number between -10 and 10 exclusive, 
and the exponent (number to the left of "E") will always be an integer. 

*EXAMPLES
In> NotationScientific(1`mA) 
Result: 1e-3`A

In> NotationScientific(137.32`(ft/nm)) 
Result: 1.3732e11`(ft / m)

In> NotationScientific(179402.320) 
Result: 1.7940232e5

In> NotationScientific(100`kilogram) 
Result: 1e5`gram

In> NotationScientific(1002320`mile) 
Result: 1.00232e6`mile

*SEE NotationEngineering, NotationCongruent, NotationStandard


*SOURCE org/mathpiper/scripts4/proposed/notation/NotationScientific.mpws
==========
*CMD NotationStandard --- takes a magnitude and replaces all SI units with their prefixless counterparts.

*CALL
        NotationStandard(magnitude)

*PARMS

{magnitude}    -- A number or a number with units


*DESC

The {NotationStandard} procedure takes a {magnitude}, a number or a 
number with a unit, and converts all SI units, if they are present, to
their prefixless form by removing all prefixed units and multiplying the
number part of the {magnitude} by the appropriate factor. All SI  units 
will be reduced to a prefixless. All non-SI units will remain  unchanged.
If the {magnitude} passed to {NotationStandard} has no SI  units or no 
units at all, then the {magnitude} will be returned unchanged

*EXAMPLES
In> NotationStandard(15`(mA)) 
Result: 0.015`A

In> NotationStandard(15.3) 
Result: 15.3

In> NotationStandard(42`ft) 
Result: 42`ft

In> NotationStandard(31231`(g*mA/(nm * hour))) 
Result: 31231000000`((A * g) / (m * hour))

In> NotationStandard(4`dag) 
Result: 40`g

*SEE NotationCongruent, NotationScientific, NotationEngineering


*SOURCE org/mathpiper/scripts4/proposed/notation/NotationStandard.mpws
==========
*CMD ViewPlotter --- open a floating instance of the MathPiper Plotter.

*CALL
    ViewPlotter()

*DESC
Open a floating (undocked) instance of the MathPiper Plotter

 
*E.G.
In> ViewPlotter()
Result: class org.mathpiper.ui.gui.worksheets.PlotPanel


*SEE PlotterView, PlotterPoint


*SOURCE org/mathpiper/scripts4/proposed/plotter/Plotter.mpws
==========
*CMD PlotterClear --- clears the MathPiper Plotter.

*CALL
    PlotterClear()

*DESC
clears the most recently opened instance of the MathPiper Plotter of all existing plotted points.

 
*E.G.
In> PlotterClear()
Result: Null


*SEE PlotterPoint, PlotterDelete


*SOURCE org/mathpiper/scripts4/proposed/plotter/Plotter.mpws
==========
*CMD PlotterPoint --- places a point on the MathPiper Plotter.

*CALL
    PlotterPoint(label, x, y)

*PARMS

{label} -- the name of the point to be plotted

{x} -- specified x-axis coordinate

{y} -- specified y-axis coordinate

*DESC
places a point with label {label} at the specified {x} and {y} coordinates on the most recently opened instance of the MathPiper Plotter.

 
*E.G.
In> PlotterPoint("A1", 1, 1)
Result: Null


*SEE PlotterSetColor, PlotterSetLabel, PlotterDelete, PlotterClear, PlotterShowLabel


*SOURCE org/mathpiper/scripts4/proposed/plotter/Plotter.mpws
==========
*CMD PlotterDelete --- deletes a point on the MathPiper Plotter.

*CALL
    PlotterDelete(label)

*PARMS

{label} -- the name of the point to be deleted

*DESC
deletes a point with label {label} from the most recently opened instance of the MathPiper Plotter.

 
*E.G.
In> PlotterDelete("A1")
Result: Null


*SEE PlotterClear, PlotterPoint


*SOURCE org/mathpiper/scripts4/proposed/plotter/Plotter.mpws
==========
*CMD PlotterSetColor --- changes the color of a point on the MathPiper Plotter.

*CALL
    PlotterSetColor(label, red, green, blue)

*PARMS

{label} -- the name of the point to be deleted

{red} -- the red value of color to be set (0-255)

{green} -- the green value of color to be set (0-255)

{blue} -- the blue value of color to be set (0-255)

*DESC
set the {red}, {green}, and {blue} color values of an existing point labeled {label} on the most recently opened instance of the MathPiper Plotter.

 
*E.G.
In> PlotterSetColor("A1", 255, 0, 0)
Result: Null

In> PlotterSetColor("A1", 0, 255, 0)
Result: Null

In> PlotterSetColor("A1", 130, 120, 255)
Result: Null


*SEE PlotterSetLabel, PlotterShowLabel, PlotterPoint


*SOURCE org/mathpiper/scripts4/proposed/plotter/Plotter.mpws
==========
*CMD PlotterShowLabel --- changes visibility of point labels on the MathPiper Plotter.

*CALL
    PlotterShowLabel(label, showLabel?)

*PARMS

{label} -- the name of the point to be selected

{showLabel?} -- state of label visibility

*DESC
changes the visibility of an existing point's label {label} on the most recently opened instance of the MathPiper Plotter.

 
*E.G.
In> PlotterShowLabel("A1", False)
Result: Null

In> PlotterShowLabel("A1", True)
Result: Null



*SEE PlotterSetLabel, PlotterPoint


*SOURCE org/mathpiper/scripts4/proposed/plotter/Plotter.mpws
==========
*CMD PlotterSetLabel --- change the label of a MathPiper Plotter point.

*CALL
    PlotterSetLabel(oldLabel, newLabel)

*PARMS

{oldLabel} -- label of existing MathPiper Plotter point

{newLabel} -- label to replace {oldLabel}

*DESC
changes the label of an existing point from {oldLabel} to {newLabel} on the most recently opened instance of the MathPiper Plotter.

 
*E.G.
In> PlotterSetLabel("A1", "B1")
Result: Null


*SEE PlotterShowLabel, PlotterSetColor, PlotterPoint


*SOURCE org/mathpiper/scripts4/proposed/plotter/Plotter.mpws
==========
*CMD AlphaToChiSquareScore --- calculates the chi square score of a given alpha probability
*STD
*CALL
        AlphaToChiSquareScore(alphaProbability, degreesOfFreedom)

*PARMS
{alphaProbability} -- an alpha probability
{degreesOfFreedom} -- the degrees of freedom

*DESC
This procedure calculates the chi square score of a given probability.

*E.G.
In> AlphaToChiSquareScore(.1,4)
Result: 7.779440287

*SEE ChiSquareScoreToAlpha, ChiSquareTest

*SOURCE org/mathpiper/scripts4/proposed/statistics/AlphaToChiSquareScore.mpws
==========
*CMD AnovaCompleteRandomizedBlock --- performs an ANOVA completely randomized block analysis

*CALL
        AnovaCompletelyRandomizedBlock(2dMatrix,alpha)

*PARMS
{2dMatrix} -- a two dimensional matrix which contain the data to be analyzed

{alpha} -- the alpha value to use in the analysis.

*DESC
This procedure performs an ANOVA completely randomized block analysis.  The various values that are
calculated during the analysis are returned in an association list and these
values are listed in the keys of the returned list (see the examples section).

If the {html} key is passed to the {ViewHtml} procedure, the results of the analysis
are displayed in a graphcs window as rendered HTML.

*E.G.
/%mathpiper,scope="nobuild",subtype="manual_test"

alpha := .05;

factor1List := [10.2,8.5,8.4,10.5,9.0,8.1];

factor2List := [11.6,12.0,9.2,10.3,9.9,12.5];

factor3List := [8.1,9.0,10.7,9.1,10.5,9.5];

Echo(anovaBlock := AnovaCompletelyRandomizedBlock([factor1List,factor2List,factor3List], alpha));

NewLine();

Echo("F-Score of the block: ", anovaBlock["fScoreBlock"]);

ViewHtml(anovaBlock["html"]);

/%/mathpiper

    /%output,preserve="false"
      Result: True
      
      Side Effects:
      ["criticalFScoreBlock",3.325834530] ["fScoreBlock",0.08045614890] ["criticalFScore",4.102821015] ["fScore",3.078377024] 
      ["meanSquareBlock",0.1418888884] ["meanSquareWithin",1.763555556] ["meanSquareBetween",5.428888905] ["sumOfSquaresTotal",29.20277781] 
      ["sumOfSquaresBlock",0.7094444419] ["sumOfSquaresBetween",10.85777781] ["sumOfSquaresWithin",17.63555556] ["html",java.lang.String] 
      
      F-Score of the block: 0.08045614890 
      
.   /%/output

*SEE ViewHtml, ScheffeTest

*SOURCE org/mathpiper/scripts4/proposed/statistics/AnovaCompletelyRandomizedBlock.mpws
==========
*CMD AnovaSingleFactor --- performs an ANOVA single factor analysis

*CALL
        AnovaSingleFactor(listOfLists,alpha)

*PARMS
{listOfLists} -- a list which contains lists which contain the data to be analyzed

{alpha} -- the alpha value to use in the analysis.

*DESC
This procedure performs an ANOVA single factor analysis.  The various values that are
calculated during the analysis are returned in an association list and these
values are listed in the keys of the returned list (see the examples section).

If the {html} key is passed to the {ViewHtml} procedure, the results of the analysis
are displayed in a graphcs window as rendered HTML.

*E.G.
/%mathpiper,scope="nobuild",subtype="manual_test"

alpha := .05;

factor1List := [10.2,8.5,8.4,10.5,9.0,8.1];

factor2List := [11.6,12.0,9.2,10.3,9.9,12.5];

factor3List := [8.1,9.0,10.7,9.1,10.5,9.5];

Echo(anova := AnovaSingleFactor([factor1List,factor2List,factor3List], alpha));

NewLine();

Echo("F-Score of the data: ", anova["fScore"]);

ViewHtml(anova["html"]);

/%/mathpiper

    /%output,preserve="false"
      Result: True
      
      Side Effects:
      ["criticalFScore",3.682320344] ["fScore",4.438993381] ["meanSquareWithin",1.22300000] 
      ["meanSquareBetween",5.428888905] ["degreesOfFreedomWithin",15] ["degreesOfFreedomBetween",2] 
      ["sumOfSquaresTotal",29.20277781] ["sumOfSquaresBetween",10.85777781] 
      ["sumOfSquaresWithin",18.34500000] ["html",java.lang.String] 
      
      F-Score of the data: 4.438993381 
      
.   /%/output

*SEE ViewHtml, ScheffeTest

*SOURCE org/mathpiper/scripts4/proposed/statistics/AnovaSingleFactor.mpws
==========
*CMD BinomialDistributionMean --- the mean of a binomial distribution
*STD
*CALL
        BinomialDistributionMean(p,n)

*PARMS
{p} -- number, the probability of a success in a single trial

{n} -- number of trials

*DESC
This procedure calculates the mean of a binomial distribution. 

*E.G.
In> BinomialDistributionMean(.3,5)
Result: 1.5

*SEE BinomialDistributionStandardDeviation

*SOURCE org/mathpiper/scripts4/proposed/statistics/BinomialDistributionMean.mpws
==========
*CMD BinomialDistributionStandardDeviation --- the standard deviation of a binomial distribution
*STD
*CALL
        BinomialDistributionStandardDeviation(p,n)

*PARMS
{p} -- number, the probability of a success in a single trial

{n} -- number of trials

*DESC
This procedure calculates the standard deviation of a binomial distribution. 

*E.G.
In> BinomialDistributionStandardDeviation(.3,5)
Result: 1.05

*SEE BinomialDistributionMean

*SOURCE org/mathpiper/scripts4/proposed/statistics/BinomialDistributionStandardDeviation.mpws
==========
*CMD ChiSquareScoreToAlpha --- calculates the alpha probability of a chi square score
*STD
*CALL
        ChiSquareScoreToAlpha(chiSquareScore, degreesOfFreedom)

*PARMS
{chiSquareScore} -- a chi square score
{degreesOfFreedom} -- the degrees of freedom

*DESC
This procedure calculates the alpha probability of a chi square score.

*E.G.
In> ChiSquareScoreToAlpha(7.779,4)
Result: 0.1000175159

*SEE AlphaToChiSquareScore, ChiSquareTest

*SOURCE org/mathpiper/scripts4/proposed/statistics/ChiSquareScoreToAlpha.mpws
==========
*CMD CoefficientOfDetermination --- calculates the correlation coefficient between two lists of values
*STD
*CALL
        CoefficientOfDetermination(xList,yList)

*PARMS

{xList} -- the list of domain values
{yList} -- the list of range values

*DESC
This procedure calculates the correlation coefficient between two lists of values.

*E.G.
/%mathpiper

x := [4,3,5,2,3,4,3];
y := [83,86,92,78,82,95,80];

CoefficientOfDetermination(x,y);

/%/mathpiper

    /%output,preserve="false"
      Result: 0.7766185090
.   /%/output

*SOURCE org/mathpiper/scripts4/proposed/statistics/CoefficientOfDetermination.mpws
==========
*CMD ConfidenceIntervalOfTheMean --- calculates a confidence interval
*STD
*CALL
        ConfidenceIntervalOfTheMean(sampleMean,standardDeviation,standardDeviationIsKnown,sampleSize,confidenceLevel)
*PARMS
{sampleMean} -- the mean of the sample
{standardDeviation} -- the standard deviation of the sample
{standardDeviationIsKnown} -- True or False
{sampleSize} -- the size of the sample
{confidenceLevel} -- the desired confidence level

*DESC
This procedure calculates a confidence interval for a mean.  It returns an association list
which contains the lower limit, the upper limit, and either the critical Z score or the t value.
If the sample size is <30 or {standardDeviationIsKnown} is False, then
Student's t-distribution is used during the calculation.

If the procedure is run in verbose mode, it returns additional information as a side effect.

*E.G.

In> result := ConfidenceIntervalOfTheMean(78.25,37.50,True,32,.90)
Result: [["lowerLimit",67.34605578],["upperLimit",89.15394422],["criticalZScore",1.644853952]]


In> result["upperLimit"]
Result: 89.15394422


In> result := ConfidenceIntervalOfTheMean(78.25,37.50,False,25,.90)
Result: [["lowerLimit",65.41838440],["upperLimit",91.08161560],["criticalTScore",1.710882080]]


In> result["criticalTScore"]
Result: 1.710882080


In> result := Verbose(ConfidenceIntervalOfTheMean(78.25,37.50,True,32,.90))
Result: [["lowerLimit",67.34605578],["upperLimit",89.15394422],["criticalZScore",1.644853952]]
Side Effects:
Using the normal distribution.
Critical Z-Score: 1.644853952 
Standard error of the mean: 6.629126073 

*SEE ConfidenceIntervalOfTheProportion, Verbose, Association

*SOURCE org/mathpiper/scripts4/proposed/statistics/ConfidenceIntervalOfTheMean.mpws
==========
*CMD ConfidenceIntervalOfTheProportion --- calculates a confidence interval for a proportion
*STD
*CALL
        ConfidenceIntervalOfTheProportion(numberOfSuccesses,sampleSize,confidenceLevel)
*PARMS
{numberOfSuccesses} -- the number of successes in the sample
{sampleSize} -- the size of the sample
{confidenceLevel} -- the desired confidence level

*DESC

This procedure calculates a confidence interval for a proportion.  It returns an association list
which contains the lower limit, the upper limit, and the critical Z score.

*E.G.

In> ConfidenceIntervalOfTheProportion(110,175,.90)
Result: [["lowerLimit",0.5684923463],["upperLimit",0.6886505109],["criticalZScore",1.644853952]]

*SEE ConfidenceIntervalOfTheMean, Verbose, Association

*SOURCE org/mathpiper/scripts4/proposed/statistics/ConfidenceIntervalOfTheProportion.mpws
==========
*CMD ConfidenceLevelToZScore --- calculates the z-score for a given confidence level
*STD
*CALL
        ConfidenceLevelToZScore(probability)

*PARMS

{probability} -- a probability value

*DESC

This procedure calculates the z-score for a given confidence level.

*E.G.
In> ConfidenceLevelToZScore(.90)
Result: 1.644853952

*SEE NormalDistribution,ZScoreToProbability,ProbabilityToZScore

*SOURCE org/mathpiper/scripts4/proposed/statistics/ConfidenceLevelToZScore.mpws
==========
*CMD ControlChartConstants --- returns the control chart constants A2 d2 D3 D4
*STD
*CALL
        ControlChartConstants(n)

*PARMS

{n} -- subgroup size (2 - 20)

*DESC
Returns the control chart constants $A_2, d_2, D_3, D_4$.

*E.G.

In> ControlChartConstants(2)
Result: [["A2",1.880],["d2",1.128],["D3",0.000],["D4",3.267]]


In> ControlChartConstants(2)["A2"]
Result: 1.880


*SOURCE org/mathpiper/scripts4/proposed/statistics/ControlChartConstants.mpws
==========
*CMD CorrelationCoefficient --- calculates the correlation coefficient between two lists of values
*STD
*CALL
        CorrelationCoefficient(xList,yList)

*PARMS

{xList} -- the list of domain values
{yList} -- the list of range values

*DESC
This procedure calculates the correlation coefficient between two lists of values.

*E.G.
/%mathpiper

x := [4,3,5,2,3,4,3];
y := [83,86,92,78,82,95,80];

CorrelationCoefficient(x,y);

/%/mathpiper

    /%output,preserve="false"
      Result: 0.7766185090
.   /%/output

*SEE CorrelationMatrix

*SOURCE org/mathpiper/scripts4/proposed/statistics/CorrelationCoefficient.mpws
==========
*CMD CorrelationMatrix --- creates a correlation matrix
*STD
*CALL
        CorrelationMatrix(listOfLists)

*PARMS

{listOfLists} -- a list of lists which contains data to be correlated

*DESC
Creates a correlation coefficient matrix from a list of lists which contain data values.
The first element in each list is the title for the data in that list.  The
CorrelationCoefficient procedure is used to calculate the individual correlations.

*E.G.
/%mathpiper

dataLists :=[
["Age",25,16,8,23,31,19,15,31,21,26,24,25,36,45,16,23,31,53,11,33],
["Level",1,2,2,3,4,4,4,5,1,1,5,5,4,4,4,1,2,2,3,2],
["Score",78,66,78,89,87,90,98,76,56,72,84,87,69,87,88,92,97,69,79,69],
];

CorrelationMatrix(dataLists);

/%/mathpiper

    /%output,preserve="false"
      Result: [["","Age","Level","Score"],["Age",1,0.056,-0.15],["Level",0.056,1,0.39],["Score",-0.15,0.39,1]]
.   /%/output

*SEE CorrelationCoefficient

*SOURCE org/mathpiper/scripts4/proposed/statistics/CorrelationMatrix.mpws
==========
*CMD D2Value --- converts average range $\bar[R]$ into estimated standard deviation $\hat[\sigma]_x$
*STD
*CALL
        D2Value(k,n)

*PARMS

{k} -- the number of times each part was measured (sample size, 1 - 15) or 0 to obtain a d2 control limits constant
{n} -- the number of parts measured (number of samples, 2 - 15)

*DESC
Converts average range $\bar{R}$ into estimated standard deviation $\hat{\sigma}_x$.  If k is set to 0,
the d2 control limits constant is returned.

*E.G.
In> D2Value(4,7);
Result: 2.736

In> D2Value(0,2)
Result: 1.128

*SOURCE org/mathpiper/scripts4/proposed/statistics/D2Value.mpws
==========
*CMD ErrorFunction --- a special function which occurs in probability statistics and partial differential equations
*STD
*CALL
        ErrorFunction(a)

*PARMS

{a} -- a measurement value

*DESC

When the results of a series of measurements are described by a normal distribution 
with standard deviation \scriptstyle\sigma and expected value 0, then 
${erf}\,\left(\,\frac{a}{\sigma \sqrt{2}}\,\right)$
is the probability that the error of a single measurement lies between -a and +a, 
for positive a. http://en.wikipedia.org/wiki/Error_function.

*E.G.
In> ErrorFunction(1)
Result: 0.8427006898

*SEE NormalDistribution

*SOURCE org/mathpiper/scripts4/proposed/statistics/ErrorFunction.mpws
==========
*CMD Mode --- calculates the mode of a list of values
*STD
*CALL
        Mode(list)

*PARMS

{list} -- list of values

*DESC

This procedure calculates the mode of a list of values.  The mode is the value
that occurs most frequently.

*E.G.

In> Mode([73,94,80,37,57,94,40,21,94,26])
Result: 94

*SEE Mean, WeightedMean, Median, Mode, GeometricMean

*SOURCE org/mathpiper/scripts4/proposed/statistics/Mode.mpws
==========
*CMD Permutations --- number of permutations
*STD
*CALL
    Permutations(n)
    Permutations(n, r)

*PARMS

{n} -- integer - total number of objects
{r} -- integer - number of objects chosen

*DESC

In combinatorics, this procedure is thought of as being the number of ways
to choose "r" objects out of a total of "n" objects if order is taken into account.

The single parameter version of the procedure is a convenience procedure for
calculating the number of ways to choose "n" objects out of "n" objects.

*E.G.

In> Permutations(5)
Result> 120


In> Permutations(10,3)
Result> 720

*SEE PermutationsList, Combinations, CombinationsList, LeviCivita

*SOURCE org/mathpiper/scripts4/proposed/statistics/Permutations.mpws
==========
*CMD ProbabilityToZScore --- calculates the z-score for a given probability
*STD
*CALL
        ProbabilityToZScore(probability)

*PARMS

{probability} -- a probability value

*DESC

This procedure calculates the z-score for a given probability.

*E.G.
In> ProbabilityToZScore(.90)
Result: 1.281551244

*SEE NormalDistribution,ZScoreToProbability,ValueToZScore,ZScoreToValue,ConfidenceLevelToZScore

*SOURCE org/mathpiper/scripts4/proposed/statistics/ProbabilityToZScore.mpws
==========
*CMD Quartile --- returns all of the quartiles and the interquartile range of a list of values
*STD
*CALL
        Quartile(list)

*PARMS

{list} -- a list which contains values

*DESC
Returns all of the quartiles and the interquartile range of a list of values.  The first
value in the returned list is the first quartile, the second value is the second quartile,
the third value is the third quartile, and the fourth value is the interquartile range.

*E.G.
/%mathpiper,title=""

samples := [
438,413,444,468,445,472,474,454,455,449,
450,450,450,459,466,470,457,441,450,445,
487,430,446,450,456,433,455,459,423,455,
451,437,444,453,434,454,448,435,432,441,
452,465,466,473,471,464,478,446,459,464,
441,444,458,454,437,443,465,435,444,457,
444,471,471,458,459,449,462,460,445,437,
461,453,452,438,445,435,454,428,454,434,
432,431,455,447,454,435,425,449,449,452,
471,458,445,463,423,451,440,442,441,439
];

NM(Quartile(samples));

/%/mathpiper

    /%output,preserve="false"
      Result: [441,450,458.5,17.5]
.   /%/output


*SOURCE org/mathpiper/scripts4/proposed/statistics/Quartile.mpws
==========
*CMD RandomPick --- randomly pick an element from a list
*STD
*CALL
        RandomPick(list)

*PARMS

{list} -- a list which contains elements

*DESC
Randomly picks an element from the given list.  

*E.G.

In> RandomPick([HEADS, TAILS])
Result: HEADS


In> RandomPick([DOOR1, DOOR2, DOOR3])
Result: DOOR2


In> RandomPick([DOG, CAT, BIRD, MOUSE, TURTLE])
Result: BIRD


In> RandomPick([23,56,87,92,15])
Result: 56

*SEE RandomPickWeighted, RandomPickVector

*SOURCE org/mathpiper/scripts4/proposed/statistics/RandomPick.mpws
==========
*CMD RandomPickVector --- returns a given number of randomly picked elements from a given list
*STD
*CALL
        RandomPickVector(list,count)

*PARMS

{list} -- a list which contains elements

{count} -- an integer which indicates how many elements to return

*DESC
Randomly picks {count} elements from the given list.

*E.G.

In> RandomPickVector([ONE,TWO,THREE],7);
Result: [THREE,ONE,THREE,THREE,ONE,TWO,TWO]

*SEE RandomPick, RandomPickWeighted

*SOURCE org/mathpiper/scripts4/proposed/statistics/RandomPickVector.mpws
==========
*CMD RandomPickWeighted --- randomly pick an element from a list using a given weight
*STD
*CALL
        RandomPickWeighted(list)

*PARMS

{list} -- a list which contains elements and their respective weights

*DESC
Randomly picks an element from the given list with a probability which is determined by the element's weight. 

*E.G.

In> RandomPickWeighted([[_HEADS,1/2],[_TAILS,1/2]]);
Result: _HEADS


In> RandomPickWeighted([[_HEADS,.5],[_TAILS,.5]]);
Result: _TAILS


In> RandomPickWeighted([[_DOOR1,2/8], [_DOOR2,1/8], [_DOOR3,5/8]])
Result: _DOOR1


In> RandomPickWeighted([[_DOG,.2], [_CAT,.3], [_BIRD,.1], [_MOUSE,.15], [_TURTLE,.25]])
Result: _TURTLE


In> RandomPickWeighted([[23,5/32],[56,10/32],[87,8/32],[92,6/32],[15,3/32]])
Result: 15

*SEE RandomPick, RandomPickVector

*SOURCE org/mathpiper/scripts4/proposed/statistics/RandomPickWeighted.mpws
==========
*CMD Range --- calculates the Range of a list of values
*STD
*CALL
        Range(list)

*PARMS

{list} -- list of values

*DESC

This procedure calculates the Range of a list of values.  The Range is the value
that occurs most frequently.

*E.G.

In> Range([2,3,4,3,4,5,5])
Result: 3

*SEE Mean, WeightedMean, Median, GeometricMean

*SOURCE org/mathpiper/scripts4/proposed/statistics/Range.mpws
==========
*CMD RegressionLine --- calculates the correlation coefficient between two lists of values
*STD
*CALL
        RegressionLine(xList,yList)

*PARMS

{xList} -- the list of domain values
{yList} -- the list of range values

*DESC
This procedure calculates the correlation coefficient between two lists of values.

*E.G.
/%mathpiper

x := [4,3,5,2,3,4,3];
y := [83,86,92,78,82,95,80];

RegressionLine(x,y);

/%/mathpiper

    /%output,preserve="false"
      Result: 0.7766185090
.   /%/output

*SOURCE org/mathpiper/scripts4/proposed/statistics/RegressionLine.mpws
==========
*CMD RegressionLineConfidenceInterval --- calculates the correlation coefficient between two lists of values
*STD
*CALL
        RegressionLineConfidenceInterval(xList,yList,xValue,confidenceLevel)

*PARMS

{xList} -- the list of domain values
{yList} -- the list of range values
{xValue} -- a value of x to calculate the confidence interval around
{confidenceLevel} -- the desired level of confidence

*DESC
This procedure calculates the correlation coefficient between two lists of values.

*E.G.
/%mathpiper,title="Confidence interval for the regression line."
xList := 1 .. 10;
yList := [5,6,10,6,11,13,9,12,15,17];
RegressionLineConfidenceInterval(xList,yList,8,.95);
/%/mathpiper

    /%output,preserve="false"
      Result: [["lower",51.59027286],["upper",55.49882230]]
.   /%/output


*SOURCE org/mathpiper/scripts4/proposed/statistics/RegressionLineConfidenceLevel.mpws
==========
*CMD Repeat --- loop a specified number of times or loop indefinitely
*STD
*CALL
        Repeat(count) body
        Repeat() body

*PARMS

{count} -- a positive integer, the number of times to loop

{body} -- expression to loop over

*DESC

The first version of Repeat executes {body} the number of times
which are specified by {count}.  The second version
executes {body} indefinitely and the only way to exit the loop
is to execute the Break procedure inside of {body}.

Repeat returns the number of times it looped as a result.

*E.G.
/%mathpiper

Repeat(4)
[
    Echo("Hello");
];

/%/mathpiper

    /%output,preserve="false"
      Result: 4

      Side Effects:
      Hello
      Hello
      Hello
      Hello
.   /%/output



/%mathpiper

x := 1;

loopCount := Repeat()
[
    Echo(x);

    Decide(x = 3, Break());

    x := x + 1;
];

Echo("Loop count: ", loopCount);

/%/mathpiper

    /%output,preserve="false"
      Result: True

      Side Effects:
      1
      2
      3
      Loop count: 2
.   /%/output

*SEE While, For, ForEach, Break, Continue

*SOURCE org/mathpiper/scripts4/proposed/statistics/Repeat.mpws
==========
*CMD Sample --- takes a random sample of elements from a list
*STD
*CALL
        Sample(list,sampleSize)

*PARMS
{list} -- a list of elements
{sampleSize} -- the size of the sample to take from the list

*DESC
This procedure takes a random sample of items from a list and returns
a list which contains the sample.

*E.G.

In> Sample([_a,_b,_c,_d,_e,_f,_g],3)
Result: [_a,_c,_g]


*SOURCE org/mathpiper/scripts4/proposed/statistics/Sample.mpws
==========
*CMD SampleSizeForTheMean --- calculates the sample size for the mean
*STD
*CALL
        SampleSizeForTheMean(standardDeviation,confidenceLevel,marginOfError)
*PARMS
{standardDeviation} -- the standard deviation of the sample
{confidenceLevel} -- the desired level of confidence
{marginOfError} -- the desired margin of error

*DESC
This procedure calculates the minimum sample size for the mean to provide
a specific margin of error for a given confidence level.

*E.G.

In> SampleSizeForTheMean(37.50,.95,8)
Result: 84.40706911

*SOURCE org/mathpiper/scripts4/proposed/statistics/SampleSizeForTheMean.mpws
==========
*CMD SampleSizeForTheProportion --- calculates the sample size for the proportion
*STD
*CALL
        SampleSizeForTheProportion(probabilityOfSuccess,confidenceLevel,marginOfError)
*PARMS
{probabilityOfSuccess} -- the probability of success for the sample
{confidenceLevel} -- the desired confidence level
{marginOfError} -- the desired margin of error

*DESC
This procedure calculates the minimum sample size for the proportion to provide
a specific margin of error for a given confidence level.

*E.G.

In> SampleSizeForTheProportion(.5,.99,.06)
Result: 460.7567390

*SOURCE org/mathpiper/scripts4/proposed/statistics/SampleSizeForTheProportion.mpws
==========
*CMD ScheffeTest --- performs a Scheffe pairwise analysis

*CALL
        ScheffeTest(listOfLists,alpha)

*PARMS
{listOfLists} -- a list which contains lists which contain the data to be analyzed

{alpha} -- the alpha value to use in the analysis.

*DESC
This procedure performs a Scheffe pairwise analysis.  The various values that are
calculated during the analysis are returned in an association list and these
values are listed in the keys of the returned list (see the examples section).

If the {html} key is passed to the {ViewHtml} procedure, the results of the analysis
are displayed in a graphcs window as rendered HTML.

*E.G.
/%mathpiper,scope="nobuild",subtype="manual_test"

alpha := .05;

data1List := [10.2,8.5,8.4,10.5,9.0,8.1];

data2List := [11.6,12.0,9.2,10.3,9.9,12.5];

data3List := [8.1,9.0,10.7,9.1,10.5,9.5];

Echo(scheffeResult := ScheffeTest([data1List,data2List,data3List], alpha));

Echo("Scheffe statistic of the first pair: ", scheffeResult["scheffeStatistic"]);

ViewHtml(scheffeResult["html"]);

/%/mathpiper

    /%output,preserve="false"
      Result: True
      
      Side Effects:
      ["scheffeStatisticCalculated",7.364640688] 
      ["summary",
      [["pair3",[["pair",[2,3]],["scheffeStatistic",5.039520331],["conclusion","No Difference"]]],
      ["pair2",[["pair",[1,3]],["scheffeStatistic",0.3297901324],["conclusion","No Difference"]]],
      ["pair1",[["pair",[1,2]],["scheffeStatistic",7.947669691],["conclusion","Difference"]]]]] 
      ["html",java.lang.String]
      
      Scheffe statistic of the first pair: 7.364640688 
      
.   /%/output

*SEE ViewHtml,AnovaSingleFactor

*SOURCE org/mathpiper/scripts4/proposed/statistics/ScheffeTest.mpws
==========
*CMD Shuffle --- randomly shuffles the elements in a list
*STD
*CALL
        Shuffle(list)

*PARMS

{list} -- a list of elements

*DESC
This procedure takes a list of elements and shuffles them.  A new
list with the shuffled elements is returned.

*E.G.

In> Shuffle([1,2,3,4,5])
Result: [5,1,2,4,3]


In> Shuffle([one,two,three])
Result: [two,three,one]


*SOURCE org/mathpiper/scripts4/proposed/statistics/Shuffle.mpws
==========
*CMD StandardErrorOfTheEstimate --- calculates the correlation coefficient between two lists of values
*STD
*CALL
        StandardErrorOfTheEstimate(xList,yList)

*PARMS

{xList} -- the list of domain values
{yList} -- the list of range values

*DESC
This procedure calculates the correlation coefficient between two lists of values.

*E.G.
/%mathpiper

x := [4,3,5,2,3,4,3];
y := [83,86,92,78,82,95,80];

StandardErrorOfTheEstimate(x,y);

/%/mathpiper

    /%output,preserve="false"
      Result: 0.7766185090
.   /%/output

*SOURCE org/mathpiper/scripts4/proposed/statistics/StandardErrorOfTheEstimate.mpws
==========
*CMD StandardErrorOfTheMean --- calculates the standard error of the mean
*STD
*CALL
        StandardErrorOfTheMean(sigma,sampleSize)

*PARMS
{sigma} -- the standard deviation of the population
{sampleSize} -- the size of the sample

*DESC
This procedure calculates the standard error of the mean.

*E.G.

In> NM(StandardErrorOfTheMean(1.44,2))
Result: 1.018233765


*SOURCE org/mathpiper/scripts4/proposed/statistics/StandardErrorOfTheMean.mpws
==========
*CMD StandardErrorOfTheProportion --- calculates the standard error of the proportion
*STD
*CALL
        StandardErrorOfTheProportion(meanOfSampleProportions,sampleSize)

*PARMS
{meanOfSampleProportions} -- the mean of the sample proportions
{sampleSize} -- the size of the proportion samples

*DESC
This procedure calculates the standard error of the proportion.

*E.G.

In> NM(StandardErrorOfTheProportion(.164,150))
Result: 0.030232873941

*SOURCE org/mathpiper/scripts4/proposed/statistics/StandardErrorOfTheProportion.mpws
==========
*CMD StandardErrorOfTheSlope --- calculates the correlation coefficient between two lists of values
*STD
*CALL
        StandardErrorOfTheSlope(xList,yList)

*PARMS

{xList} -- the list of domain values
{yList} -- the list of range values

*DESC
This procedure calculates the correlation coefficient between two lists of values.

*E.G.
/%mathpiper

x := [4,3,5,2,3,4,3];
y := [83,86,92,78,82,95,80];

StandardErrorOfTheSlope(x,y);

/%/mathpiper

    /%output,preserve="false"
      Result: 1.813835715
.   /%/output

*SOURCE org/mathpiper/scripts4/proposed/statistics/StandardErrorOfTheSlope.mpws
==========
*CMD ValueToZScore --- calculates the z-score of a numerical value
*STD
*CALL
        ValueToZScore(numericalValue,mean,standardDeviation)

*PARMS

{numericalValue} -- a numerical value
{mean} -- the mean
{standardDeviation} -- the standard deviation

*DESC
This procedure calculates the z-score for a given numerical value.

*E.G.

In> NM(ValueToZScore(4.74,5,.332))
Result: -0.7831325301

*SEE ZScoreToValue,ZScoreToProbability,ProbabilityToZScore,ConfidenceLevelToZScore

*SOURCE org/mathpiper/scripts4/proposed/statistics/ValueToZScore.mpws
==========
*CMD WeightedMean --- weighted mean
*STD
*CALL 
        WeightedMean([[value, weight],...])

*PARMS

{value} -- a value.

{weight} -- the weight to associate with the value.

*DESC 
This procedure allows more weight to be associated with certain values and
less weight to others when calculating their mean.

*E.G.
In>  WeightedMean([[92,50], [87,40], [76,10]])
Result: 442/5

In>  NM(WeightedMean([[92,50], [87,40], [76,10]]))
Result: 88.4

*SEE Mean, Median, Mode, GeometricMean

*SOURCE org/mathpiper/scripts4/proposed/statistics/WeightedMean.mpws
==========
*CMD ZScoreToProbability --- calculates the probability of a given z-score
*STD
*CALL
        ZScoreToProbability(z_score)

*PARMS

{z_score} -- a z-score value

*DESC

This procedure calculates the probability of a given z-score.

*E.G.
In> ZScoreToProbability(1.08)
Result: 0.8599289100

*SEE NormalDistribution,ProbabilityToZScore,ValueToZScore,ZScoreToValue,ConfidenceLevelToZScore

*SOURCE org/mathpiper/scripts4/proposed/statistics/ZScoreToProbability.mpws
==========
*CMD ZScoreToValue --- calculates the numerical value for a given z-score
*STD
*CALL
        ZScoreToValue(zScore,mean,standardDeviation)

*PARMS

{zScore} -- a z score
{mean} -- the mean
{standardDeviation} -- the standard deviation

*DESC
This procedure calculates the numerical value for a given z-score.

*E.G.

In> NM(ZScoreToValue(1,5,1))
Result: 6

*SEE ValueToZScore,ZScoreToProbability,ProbabilityToZScore,ConfidenceLevelToZScore

*SOURCE org/mathpiper/scripts4/proposed/statistics/ZScoreToValue.mpws
==========
*CMD Copy --- makes a deep copy of an expression

*CALL
    Copy(expression)

*PARMS

{expression} -- expression to be copied

*DESC

Makes a deep copy of an expression.

*E.G.
In> Copy('(a + b))
Result: a + b

*SEE FlatCopy

*SOURCE org/mathpiper/scripts4/proposed/treeutilities/Copy.mpws
==========
*CMD HighlightPattern --- highlights all subtrees of an expression tree that match the given pattern

*CALL
    HighlightPattern(expression, pattern)

*PARMS

{expression} -- expression tree to be highlighted

{pattern} -- pattern to match against subtrees

*DESC

Highlights all subtrees of an expression tree that
match the given pattern by setting metadata on the
subtrees. Highlighting metadata is only applied to
the dominant node because the tree viewer will
highlight a node's subtree if its dominant node is
highlighted.

*E.G.
In> result := HighlightPattern('(1+2-3), a_Integer?)
Result: (1 + 2) - 3

In> MetaEntries(result[1][1])
Result: ["HighlightColor":"ORANGE"]

*SEE Mark, MarkAll

*SOURCE org/mathpiper/scripts4/proposed/treeutilities/HighlightPattern.mpws
==========
*CMD Mark --- highlights a subtree of an expression tree at the given position if it matches the given pattern

*CALL
    Mark(expression, position, pattern, color)

*PARMS

{expression} -- expression tree to be highlighted

{position} -- position of the subtree

{pattern} -- pattern to match against subtrees

{color} -- the highlighting color

*DESC

Highlights a subtree of an expression tree at the
given position if it matches the given pattern.
Highlighting metadata is only applied to the
dominant node because the tree viewer will
highlight a node's subtree if its dominant node is
highlighted.

*E.G.
In> result := Mark('(1+2+3), "1", a_ + b_, "BLUE")
Result: (1 + 2) + 3

In> MetaEntries(result[1])
Result: ["HighlightNodeShape":"RECTANGLE","HighlightColor":"BLUE"]

*SEE HighlightPattern, MarkAll

*SOURCE org/mathpiper/scripts4/proposed/treeutilities/Mark.mpws
==========
*CMD MarkAll --- highlights a subtree of an expression tree at the given position if it matches the given pattern

*CALL
    MarkAll(expression, position, pattern, color)

*PARMS

{expression} -- expression tree to be highlighted

{position} -- position of the subtree

{pattern} -- pattern to match against subtrees

{color} -- the highlighting color

*DESC

Highlights a subtree of an expression tree at the
given position if it matches the given pattern.
Highlighting metadata is applied to the
dominant node and all nodes that are underneath it.
This is useful for expression viewers other than
the tree viewer.

*E.G.
In> result := MarkAll('(1+2+3), "1", a_ + b_, "BLUE")
Result: (1 + 2) + 3

In> MetaEntries(result[1][0])
Result: ["HighlightNodeShape":"RECTANGLE","HighlightColor":"BLUE"]

*SEE HighlightPattern, Mark

*SOURCE org/mathpiper/scripts4/proposed/treeutilities/MarkAll.mpws
==========
*CMD NodePathDistance --- determine the path distance between two nodes

*CALL
    NodePathDistance(node1Position, node2Position)

*PARMS

{node1Position} -- position of the first node

{node2Position} -- position of the second node


*DESC

Determine the path distance between two nodes.

*E.G.
In> NodePathDistance("1,1","1,2,2") 
Result: 3

*SEE SymbolPathDistanceTotal

*SOURCE org/mathpiper/scripts4/proposed/treeutilities/NodePathDistance.mpws
==========
*CMD OccurrencesCount --- counts the number of occurrences of a subexpression that are in an expression

*CALL
    OccurrencesCount(expression, subexpression)

*PARMS

{expression} -- an expression

{subexpression} -- a subexpression

*DESC

Counts the number of occurrences of a subexpression that are in an expression.

*E.G.
In> OccurrencesCount('(a + _b*c / _b - c), _b)
Result: 2

*SEE Contains?

*SOURCE org/mathpiper/scripts4/proposed/treeutilities/OccurrencesCount.mpws
==========
*CMD PositionGet --- return the subexpression at the given position in the given expression

*CALL
    PositionGet(expression, position)

*PARMS

{expression} -- an expression

{predicate} -- an expression tree position in string or list form

*DESC

return the subexpression at the given position in the given expression.

*E.G.
In> PositionGet('(2 + (_b*_c) / _b - 3), "1,2")
Result: (_b*_c)/_b

In> PositionGet('(2 + (_b*_c) / _b - 3), [1,2])
Result: (_b*_c)/_b

*SEE SubstitutePosition

*SOURCE org/mathpiper/scripts4/proposed/treeutilities/PositionGet.mpws
==========
*CMD PositionStringToList --- convert the string version of an expression tree position list into a list

*CALL
    PositionStringToList(positionString)

*PARMS

{positionString} -- a position list in string form

*DESC

Convert the string version of an expression tree position list into a list

*E.G.
In> PositionStringToList("1,2,1,2")
Result: [1,2,1,2]

*SEE ListToString

*SOURCE org/mathpiper/scripts4/proposed/treeutilities/PositionStringToList.mpws
==========
*CMD PositionsLeaves --- return the positions of all the leaves in an expression tree

*CALL
    PositionsLeaves(expression)

*PARMS

{expression} -- an expression

*DESC

Return the positions of all the leaves in an expression tree.

*E.G.
In> PositionsLeaves('(2 + (_b*_c) / _b - 3))
Result: ["2","1,1","1,2,2","1,2,1,1","1,2,1,2"]

*SOURCE org/mathpiper/scripts4/proposed/treeutilities/PositionsLeaves.mpws
==========
*CMD PositionsPattern --- returns a list of expression tree positions that match the given pattern

*CALL
    PositionsPattern(expression, pattern)

*PARMS

{expression} -- an expression

{pattern} -- a pattern

*DESC

Returns a list of expression tree positions that
match the given pattern.

Note: PositionsPattern does not handle patterns
such as ToAtom("+") and q_Integer? correctly yet.

*E.G.
In> PositionsPattern('(2 + (b*c) / b - 3*d + e*f), q_*r_)
Result: ["2","1,2","1,1,2,1"]

In> PositionsPattern('(2 + (b*c) / b - 3*d), q_*r_)
Result: ["2","1,2,1"]

In> PositionsPattern('(2 + (_b*c) / _b - 3), q_Integer?)
Result: []

In> PositionsPattern2('(2 + (_b*c) / _b - 3), q_Integer?)
Result: ["1,1","2"]

*SEE PositionsPredicate, ValuesPattern

*SOURCE org/mathpiper/scripts4/proposed/treeutilities/PositionsPattern.mpws
==========
*CMD PositionsPredicate --- returns a list of expression tree positions that match the given predicate

*CALL
    PositionsPredicate(expression, predicate)

*PARMS

{expression} -- an expression

{predicate} -- a predicate

*DESC

Returns a list of expression tree positions that
match the given predicate.

*E.G.
In> PositionsPredicate('(2 + (_b*_c) / _b - 3), "Integer?")
Result: ["2","1,1"]

In> PositionsPredicate('(2 + (_b*_c) / _b - 3), Lambda([x], Integer?(x)))
Result: ["2","1,1"]

*SEE PositionsPattern

*SOURCE org/mathpiper/scripts4/proposed/treeutilities/PositionsPredicate.mpws
==========
*CMD SubstitutePosition --- replace a subexpression at a given position if it matches the given pattern

*CALL
    SubstitutePosition(expression, position, pattern, replacement)
    SubstitutePosition(expression, position, pattern, replacement, variables)

*PARMS

{expression} -- an expression

{position} -- an expression tree position in string form

{pattern} -- a rule pattern (the head of a rule)

{replacement} -- replacement expression (the body of a rule)

{variables} -- an empty association list that matched variable values will be placed into

*DESC

Replace a subexpression at a given position if it matches the given pattern. If an empty
association list is passed in as the 5th argument, the values of matched variables
will be placed into it. The key for each matched variable is the variable
name followed by an underscore. So the key for variable 'q' would be 'q_'.

If the replacement is frozen with the {''} freeze operator, or with
the {Freeze} procedure, then the argument of this operator or procedure is
used as the replacement expression.

*E.G.
In> SubstitutePosition('(2 + (_b*_c) / _b - 3), "1,1", q_Integer?, '(q*2))
Result: (4 + (_b*_c)/_b) - 3

In> SubstitutePosition('(2 + (_b*_c) / _b - 3), "1,1", q_Integer?, ''(q*2))
Result: (4 + (_b*_c)/_b) - 3



/%mathpiper

patternVariables := [];

result := SubstitutePosition('(2 + (_b*_c) / _b - 3), "1,1", q_Integer?, '(q*2), patternVariables);

q := patternVariables[q_];

Echo("result: " + result + Nl() + "q: " + q);

/%/mathpiper

    /%output,mpversion=".231",preserve="false"
      Result: True
      
      Side Effects:
      result: (4 + (_b*_c)/_b) - 3
      q: 2
      
.   /%/output

*SEE PositionGet

*SOURCE org/mathpiper/scripts4/proposed/treeutilities/SubstitutePosition.mpws
==========
*CMD SubtreesPattern --- returns a list of subtrees that match the given pattern

*CALL
    SubtreesPattern(expression, pattern)

*PARMS

{expression} -- an expression

{predicate} -- a rule pattern

*DESC

Returns a list of subtrees that match the given pattern.

*E.G.
SubtreesPattern('(2 + (_b*_c) / (_d * 3)), q_ * r_)
Result: ["_b * _c","_d * 3"]

*SEE PositionsPattern

*SOURCE org/mathpiper/scripts4/proposed/treeutilities/SubtreesPattern.mpws
==========
*CMD SymbolPathDistanceTotal --- determine the total path distance between all copies of a specified symbol

*CALL
    SymbolPathDistanceTotal(expression, symbol)

*PARMS

{expression} -- an expression

{symbol} -- a symbol that is present in the expression in 0 or more places

*DESC

Determine the total path distance between all copies of a specified symbol.

*E.G.
In> SymbolPathDistanceTotal('( a+b/c-x*d+a/e), 'a)
Result: 5

*SEE NodePathDistance

*SOURCE org/mathpiper/scripts4/proposed/treeutilities/SymbolPathDistanceTotal.mpws
==========
*CMD TreeDepth --- determine the depth of an expression tree

*CALL
    TreeDepth(expression)

*PARMS

{expression} -- an expression

*DESC

Determine the depth of an expression tree.

*E.G.
In> TreeDepth('(2 + (_b*_c) / _b - 3))
Result: 4

*SOURCE org/mathpiper/scripts4/proposed/treeutilities/TreeDepth.mpws
==========
*CMD RabinMiller --- Rabin-Miller test for a prime number
*CALL
        RabinMiller(n)

*PARMS

{n} -- integer to test

*DESC

This procedure checks whether $n$, which should be a positive integer,
is a prime number using the Rabin-Miller test. A number $n$ is a prime number if it is only divisible
by 1 and itself. As a special case, 1 is not considered a prime number.
The first prime numbers are 2, 3, 5, ...

*EXAMPLES
In> RabinMiller(3) 
Result: True

In> RabinMiller(4) 
Result: False

In> RabinMiller(1) 
Result: False

In> RabinMiller(11238) 
Result: False

In> RabinMiller(11239) 
Result: True

*SEE Prime?

*SOURCE org/mathpiper/scripts4/rabinmiller/RabinMiller.mpws
==========
*CMD RandomInteger --- generate a random integer

*STD

*CALL
        RandomInteger(upper_bound)
        RandomInteger(lower_bound, upper_bound)

*PARMS

{lower_bound} -- the smallest integer that can be generated

{upper_bound} -- the largest integer that can be generated


*DESC

The single argument version of this procedure generates a random integer between
1 and the given upper bound integer (inclusive).  The two argument version of
the procedure generates a random integer between a lower bound integer and an
upper bound integer (both inclusive).

*EXAMPLES
In> RandomInteger(5) 
Result> 4

In> Repeat(10) Write(RandomInteger(5),,) 
Result> 10 
Side Effects>4,3,5,1,2,2,3,5,3,3,

In> RandomInteger(5,10) 
Result: 5

In> Repeat(10) Write(RandomInteger(5, 10),,) 
Result: 10 
Side Effects: 
8,9,9,5,6,8,9,10,8,7,

*SEE Random, RandomPoly, RandomIntegerList, RandomIntegerMatrix

*SOURCE org/mathpiper/scripts4/random/RandomInteger.mpws
==========
*CMD RandomIntegerList --- generate a vector of random integers

*STD

*CALL
        RandomIntegerList(nr, from, to)

*PARMS

{nr} -- number of integers to generate

{from} -- lower bound

{to} -- upper bound

*DESC

This procedure generates a list with "nr" random integers. All
entries lie between "from" and "to", including the boundaries, and
are uniformly distributed in this interval.

*EXAMPLES
In> RandomIntegerList(4,-3,3) 
Result: [0,3,2,-2]

In> RandomIntegerList(8,20,30) 
Result: [24,28,25,28,27,28,26,28]

*SEE Random, RandomPoly, RandomInteger, RandomIntegerMatrix

*SOURCE org/mathpiper/scripts4/random/RandomIntegerList.mpws
==========
*CMD RandomIntegerMatrix --- generate a matrix of random integers

*STD

*CALL
        RandomIntegerMatrix(rows,cols,from,to)

*PARMS

{rows} -- number of rows in matrix

{cols} -- number of cols in matrix

{from} -- lower bound

{to} -- upper bound

*DESC

This procedure generates a {rows x cols} matrix of random integers. All
entries lie between "from" and "to", including the boundaries, and
are uniformly distributed in this interval.

*EXAMPLES
In> RandomIntegerMatrix(5,5,-2^10,2^10) 
Result: [[-342,-342,-342,-342,-342],[-342,-342,-342,-342,-342],[-342,-342,-342,-342,-342],[-342,-342,-342,-342,-342],[-342,-342,-342,-342,-342]]

In> UnparseMath2D( RandomIntegerMatrix(5,5,-2^10,2^10) ) 
Result: True 
Side Effects: 
/                                          \ 
| ( 530 ) ( 530 ) ( 530 ) ( 530 ) ( 530 )  | 
|                                          | 
| ( 530 ) ( 530 ) ( 530 ) ( 530 ) ( 530 )  | 
|                                          | 
| ( 530 ) ( 530 ) ( 530 ) ( 530 ) ( 530 )  | 
|                                          | 
| ( 530 ) ( 530 ) ( 530 ) ( 530 ) ( 530 )  | 
|                                          | 
| ( 530 ) ( 530 ) ( 530 ) ( 530 ) ( 530 )  | 
\                                          /

*SEE RandomPoly, Random, RandomInteger, RandomIntegerList

*SOURCE org/mathpiper/scripts4/random/RandomIntegerMatrix.mpws
==========
*CMD RandomPoly --- construct a random polynomial
*STD
*CALL
        RandomPoly(var,deg,coefmin,coefmax)

*PARMS

{var} -- free variable for resulting univariate polynomial

{deg} -- degree of resulting univariate polynomial

{coefmin} -- minimum value for coefficients

{coefmax} -- maximum value for coefficients

*DESC

RandomPoly generates a random polynomial in variable "var", of
degree "deg", with integer coefficients ranging from "coefmin" to
"coefmax" (inclusive). The coefficients are uniformly distributed in
this interval, and are independent of each other.

*EXAMPLES
In> RandomPoly(x,3,-10,10) 
Result: 3*x^3+10*x^2-4*x-6

In> RandomPoly(x,3,-10,10) 
Result: -2*x^3-8*x^2+8
*SEE Random, RandomInteger, RandomIntegerList, RandomIntegerMatrix

*SOURCE org/mathpiper/scripts4/random/RandomPoly.mpws
==========
*CMD Random, RandomSeed --- (pseudo-) random number generator
*STD
*CALL
        Random()
        RandomSeed(init)

*PARMS
{init} -- positive integer, initial random seed

*DESC

The procedure {Random} returns a random number, uniformly distributed in the
interval between 0 and 1. The same sequence of random numbers is
generated in every MathPiper session.

The random number generator can be initialized by calling {RandomSeed} with an integer value.
Each seed value will result in the same sequence of pseudo-random numbers.

*SEE RandomInteger, RandomPoly, Rng, Random, RandomIntegerList, RandomIntegerMatrix

*SOURCE org/mathpiper/scripts4/random/random.mpws
==========
*CMD RngCreate --- manipulate random number generators as objects
*CMD RngSeed --- manipulate random number generators as objects
*CMD Rng --- manipulate random number generators as objects
*STD
*CALL
        RngCreate()
        RngCreate(init)
        RngCreate(option: value,...)
        RngSeed(r, init)
        Rng(r)
        
*PARMS
{init} -- integer, initial seed value

{option} -- atom, option name

{value} -- atom, option value

{r} -- a list, RNG object

*DESC
These commands are an object-oriented interface to (pseudo-)random number generators (RNGs).

{RngCreate} returns a list which is a well-formed RNG object.
Its value should be saved in a variable and used to call {Rng} and {RngSeed}.

{Rng(r)} returns a floating-point random number between 0 and 1 and updates the RNG object {r}.
(Currently, the Gaussian option makes a RNG return a <i>complex</i> random number instead of a real random number.)

{RngSeed(r,init)} re-initializes the RNG object {r} with the seed value {init}.
The seed value should be a positive integer.

The {RngCreate} procedure accepts several options as arguments.
Currently the following options are available:

*        {seed} -- specify initial seed value, must be a positive integer
*        {dist} -- specify the distribution of the random number; currently {flat} and {gauss} are implemented, and the default is the flat (uniform) distribution
*        {engine} -- specify the RNG engine; currently {default} and {advanced} are available ("advanced" is slower but has much longer period)

If the initial seed is not specified, the value of 76544321 will be used.

The {gauss} option will create a RNG object that generates pairs of Gaussian distributed random numbers as a complex random number.
The real and the imaginary parts of this number are independent random numbers taken from a Gaussian (i.e. "normal") distribution with unit variance.

For the Gaussian distribution, the Box-Muller transform method is used.
A good description of this method, along with the proof that the method
generates normally distributed random numbers, can be found in Knuth, 
"The Art of Computer Programming", Volume 2 (Seminumerical algorithms, third 
edition), section 3.4.1 

Note that unlike the global {Random} procedure, the RNG objects created with {RngCreate} are independent RNGs and do not affect each other.
They generate independent streams of pseudo-random numbers.
However, the {Random} procedure is slightly faster.

*E.G.

In> r1:=RngCreate(seed: 1,dist: gauss)
Result: ["GaussianRNGDist","RNGEngineLCG2",[1]]

In> Rng(r1)
Result: Complex(-1.6668466417,0.228904004);

In> Rng(r1);
Result: Complex(0.0279296109,-0.5382405341);
The second RNG gives a uniform distribution (default option) but uses a more complicated algorithm:

In> [r2:=RngCreate(engine: advanced);Rng(r2);]
Result: 0.3653615377;
The generator [r1] can be re-initialized with seed 1 again to obtain the same sequence:

In> RngSeed(r1, 1)
Result: True;

In> Rng(r1)
Result: Complex(-1.6668466417,0.228904004);
        

*SEE Random, RandomInteger, RandomIntegerList, RandomIntegerMatrix

*SOURCE org/mathpiper/scripts4/random/random.mpws
==========
*CMD BubbleSort --- sort a list
*STD
*CALL
        BubbleSort(list, compare)

*PARMS

{list} -- list to sort

{compare} -- procedure used to compare elements of {list}

*DESC

This command returns {list} after it is sorted using {compare} to
compare elements. The procedure {compare} should accept two arguments,
which will be elements of {list}, and compare them. It should return
{True} if in the sorted list the second argument
should come after the first one, and {False}
otherwise.  The procedure {compare} can either be a string which
contains the name of a procedure or a pure procedure.

The procedure {BubbleSort} uses the so-called "bubble sort" algorithm to do the
sorting by swapping elements that are out of order. This algorithm is easy to
implement, though it is not particularly fast. The sorting time is proportional
to $n^2$ where $n$ is the length of the list.

The original {list} is left unmodified.

*EXAMPLES
In> BubbleSort([4,7,23,53,-2,1], ">?") 
Result: [53,23,7,4,1,-2]

In> BubbleSort([3,5,2],Lambda([x,y],x<?y)) 
Result: [2,3,5]

*SEE HeapSort, Lambda

*SOURCE org/mathpiper/scripts4/sorting/BubbleSort.mpws
==========
*CMD BubbleSortIndexed --- sort a list
*STD
*CALL
        BubbleSortIndexed(list, compare)

*PARMS

{list} -- list to sort

{compare} -- procedure used to compare elements of {list}

*DESC

This command returns {list} after it is sorted using {compare} to
compare elements. The procedure {compare} should accept two arguments,
which will be elements of {list}, and compare them. It should return
{True} if in the sorted list the second argument
should come after the first one, and {False}
otherwise.  The procedure {compare} can either be a string which
contains the name of a procedure or a pure procedure.

The procedure {BubbleSortIndexed} uses the so-called "bubble sort" algorithm to do the
sorting by swapping elements that are out of order. This algorithm is easy to
implement, though it is not particularly fast. The sorting time is proportional
to $n^2$ where $n$ is the length of the list.

An {IndexedSort}, performs the same action as a "regular" sort, but also
return an Index list, which gives the order that the sorted items 
had in the original list before sorting.

The original {list} is left unmodified.

*EXAMPLES
In> BubbleSortIndexed([-1,88,4,7,23,53,-2,1], ">?") 
Result: [[88,53,23,7,4,1,-1,-2],[2,6,5,4,3,8,1,7]]

In> BubbleSortIndexed([-1,88,4,7,23,53,-2,1], Lambda([x,y],x<?y)) 
Result: [[-2,-1,1,4,7,23,53,88],[7,1,8,3,4,5,6,2]]
*SEE HeapSort, Lambda

*SOURCE org/mathpiper/scripts4/sorting/BubbleSortIndexed.mpws
==========
*CMD HeapSort --- sort a list
*STD
*CALL
        HeapSort(list, compare)

*PARMS

{list} -- list to sort

{compare} -- procedure used to compare elements of {list}

*DESC

This command returns {list} after it is sorted using {compare} to
compare elements. The procedure {compare} should accept two arguments,
which will be elements of {list}, and compare them. It should return
{True} if in the sorted list the second argument
should come after the first one, and {False}
otherwise.  The procedure {compare} can either be a string which
contains the name of a procedure or a pure procedure.

The procedure {HeapSort} uses a recursive algorithm "heapsort" and is much
faster for large lists. The sorting time is proportional to $n*Ln(n)$ where $n$
is the length of the list.

The original {list} is left unmodified.

*EXAMPLES
In> HeapSort([4,7,23,53,-2,1], ">?") 
Result: [53,23,7,4,1,-2]

In> HeapSort([3,5,2],Lambda([x,y],x<?y)) 
Result: [2,3,5]

*SEE HeapSortIndexed, BubbleSort, BubbleSortIndexed, Lambda

*SOURCE org/mathpiper/scripts4/sorting/HeapSort.mpws
==========
*CMD HeapSortIndexed --- sort a list
*STD
*CALL
        HeapSortIndexed(list, compare)

*PARMS

{list} -- list to sort

{compare} -- procedure used to compare elements of {list}

*DESC

This command returns {list} after it is sorted using {compare} to
compare elements. The procedure {compare} should accept two arguments,
which will be elements of {list}, and compare them. It should return
{True} if in the sorted list the second argument
should come after the first one, and {False}
otherwise.  The procedure {compare} can either be a string which
contains the name of a procedure or a pure procedure.

The procedure {HeapSortIndexed} uses a recursive algorithm "heapsort" and is much
faster than {BubbleSortIndexed} for large lists. The sorting time is proportional 
to $n*Ln(n)$, where $n$ is the length of the list.

An {IndexedSort}, performs the same action as a "regular" sort, but also
return an Index list, which gives the order that the sorted items 
had in the original list before sorting.

The original {list} is left unmodified.


*EXAMPLES
In> HeapSortIndexed([-1,88,4,7,23,53,-2,1], ">?") 
Result: [[88,53,23,7,4,1,-1,-2],[2,6,5,4,3,8,1,7]]

In> HeapSortIndexed([-1,88,4,7,23,53,-2,1], Lambda([x,y],x<?y)) 
Result: [[-2,-1,1,4,7,23,53,88],[7,1,8,3,4,5,6,2]]
*SEE BubbleSort, Lambda

*SOURCE org/mathpiper/scripts4/sorting/HeapSortIndexed.mpws
==========
*CMD SmallSort --- sort a small list

*CALL
        SmallSort(list, first, last, compare)

*PARMS

{list} -- list to sort

{first} -- index of where to begin sorting the elements of {list}

{last} -- index of where to stop sorting the elements of {list}

{compare} -- procedure used to compare elements of {list}


*DESC

This command returns {list} after it is sorted using {compare} to
compare elements. It is used to speed up the final steps of a {HeapSort}.
The procedure requires four arguments.

The first argument is the list to be sorted. {SmallSort} is for lists of three 
or less elements. For a larger list, use {HeapSort}.

The second argument is the position in the list in which to begin sorting the elements.

The third argument is the position in the list to stop sorting the elements.

The fourth argument is the compare procedure which should be used to sort the list.
The compare procedure can either be a string which contains the name of a procedure 
or a pure procedure.

The original {list} is left unmodified.


*EXAMPLES
In> SmallSort([3,1,2], 1, 3, "<?") 
Result: [1,2,3]

In> SmallSort([3,1,2], 1, 3, ">?") 
Result: [3,2,1]
*SEE SmallSortIndexed, HeapSort, HeapSortIndexed

*SOURCE org/mathpiper/scripts4/sorting/SmallSort.mpws
==========
*CMD Sort --- sort a list, using specified compare(a,b) operator.
*STD
*CALL
        Sort(list)
        Sort(list,compare)
        SortIndexed(list)
        SortIndexed(list,compare)        

*PARMS

{list}    -- list of items to sort

{compare} -- a comparison operator, according to which items are sorted

*DESC

The first form of the {Sort} command simply sorts all the
objects in {list}, according to the default comparison 
operator {"<?"}.

The second form allows the user to input also a chosen comparison 
operator, {compare}, to be used instead of the default.  The procedure 
{compare} should accept two arguments, which will be elements of {list},
and compare them. It should return {True} if in the sorted list the 
second argument should come after the first one, and {False}
otherwise.  The procedure {compare} can either be a string which
contains the name of a procedure or a pure procedure.

The third and fourth forms, {SortIndexed}, do the same, but also
return an Index list, which tells the order that the sorted items 
had in the original list before sorting.

The Sort and SortIndexed procedures will use BubbleSort when the list
contains fewer than 20 elements, and HeapSort for longer lists.  
This is because BubbleSort tends to be faster for short lists, and 
HeapSort tends to be faster for long lists.  The choice of the number
20 as the division point is heuristic and somewhat arbitrary.

In all cases, the original {list} is left unmodified.

*EXAMPLES
In> L:= [7,-6,8,-3,10,5,-5,3,-6,5,10,3] 
Result: [7,-6,8,-3,10,5,-5,3,-6,5,10,3]

In> Sort(L) 
Result: [-6,-6,-5,-3,3,3,5,5,7,8,10,10]

In> Sort(L,">?") 
Result: [10,10,8,7,5,5,3,3,-3,-5,-6,-6]

In> SortIndexed(L) 
Result: [[-6,-6,-5,-3,3,3,5,5,7,8,10,10],[2,9,7,4,12,8,6,10,1,3,11,5]]

In> SortIndexed(L,">?") 
Result: [[10,10,8,7,5,5,3,3,-3,-5,-6,-6],[5,11,3,1,6,10,12,8,4,7,9,2]]

In> L2:=RandomIntegerList(100,-500,500) 
Result: [-123,-459,156,-492,-313, .. , 351,-459,76,27,-144,-80,-91]

In> T:=Time() LS:=BubbleSort(L2,"<?") 
Result: 0.621

In> T:=Time() LS:=HeapSort(L2,"<?") 
Result: 0.146

*SEE BubbleSort, HeapSort, BubbleSortIndexed, HeapSortIndexed

*SOURCE org/mathpiper/scripts4/sorting/Sort.mpws
==========
*CMD Gamma --- Euler's Gamma function
*STD
*CALL
        Gamma(x)

*PARMS

{x} -- expression

{number} -- expression that can be evaluated to a number

*DESC

{Gamma(x)} is an interface to Euler's Gamma function $Gamma(x)$. It returns exact values on integer 
and half-integer arguments. {NM(Gamma(x)} takes a numeric parameter and always returns a floating-point 
number in the current precision.

Note that Euler's constant $gamma<=>0.57722$ is the lowercase {gamma} in MathPiper.

*EXAMPLES
In> NM(Gamma(1.3),10) 
Result: 0.8974706967

In> Gamma(1.5) 
Result: Sqrt(Pi)/2

In> NM(Gamma(1.5),10) 
Result: 0.8862269263

*SEE NM, gamma

*SOURCE org/mathpiper/scripts4/specfunc/Gamma.mpws
==========
*CMD GeometricMean --- calculates the mean of a list of values
*STD
*CALL
        GeometricMean(list)

*PARMS

{list} -- list of values

*DESC

This procedure calculates the geometric mean of a list of values.

*EXAMPLES
In> GeometricMean([73,94,80,37,56,94,40,21,7,24]) 
Result: 15088528001433600^(1/10)

In> NM(GeometricMean([73,94,80,37,56,94,40,21,7,24])) 
Result: 41.48247758
*SEE Mean, WeightedMean, Median, Mode

*SOURCE org/mathpiper/scripts4/statistics/GeometricMean.mpws
==========
*CMD Mean --- calculates the mean of a list of values
*STD
*CALL
        Mean(list)

*PARMS

{list} -- list of values

*DESC

This procedure calculates the mean of a list of values.

*EXAMPLES
In> Mean([73,94,80,37,56,94,40,21,7,24]) 
Result: 263/5

In> NM(Mean([73,94,80,37,56,94,40,21,7,24])) 
Result: 52.6
*SEE WeightedMean, Median, Mode, GeometricMean

*SOURCE org/mathpiper/scripts4/statistics/Mean.mpws
==========
*CMD Median --- calculates the median of a list of values
*STD
*CALL
        Median(list)

*PARMS

{list} -- list of values

*DESC

This procedure calculates the median of a list of values.

*EXAMPLES
In> Median([73,94,80,37,57,94,40,21,7,26]) 
Result: 97/2

In> NM(Median([73,94,80,37,57,94,40,21,7,26])) 
Result: 48.5
*SEE WeightedMean, Mean, Mode, GeometricMean

*SOURCE org/mathpiper/scripts4/statistics/Median.mpws
==========
*CMD StandardDeviation --- calculates the standard deviation of a list of values
*STD
*CALL
        StandardDeviation(list)

*PARMS

{list} -- list of values

*DESC

This procedure calculates the standard deviation of a list of values.

*EXAMPLES
In> StandardDeviation([73,94,80,37,57,94,40,21,7,26]) 
Result: Sqrt(88009/90)

In> NM(StandardDeviation([73,94,80,37,57,94,40,21,7,26])) 
Result: 31.27103737
*SEE Variance, UnbiasedVariance

*SOURCE org/mathpiper/scripts4/statistics/StandardDeviation.mpws
==========
*CMD UnbiasedVariance --- calculates the unbiased variance of a list of values
*STD
*CALL
        UnbiasedVariance(list)

*PARMS

{list} -- list of values

*DESC

This procedure calculates the unbiased variance of a list of values.

*EXAMPLES
In> UnbiasedVariance([73,94,80,37,57,94,40,21,7,26]) 
Result: 88009/90

In> NM(UnbiasedVariance([73,94,80,37,57,94,40,21,7,26])) 
Result: 977.8777778
*SEE Variance, StandardDeviation

*SOURCE org/mathpiper/scripts4/statistics/UnbiasedVariance.mpws
==========
*CMD Variance --- calculates the variance of a list of values
*STD
*CALL
        Variance(list)

*PARMS

{list} -- list of values

*DESC

This procedure calculates the variance of a list of values.

*EXAMPLES
In> Variance([73,94,80,37,57,94,40,21,7,26]) 
Result: 88009/100

In> NM(Variance([73,94,80,37,57,94,40,21,7,26])) 
Result: 880.09
*SEE UnbiasedVariance, StandardDeviation

*SOURCE org/mathpiper/scripts4/statistics/Variance.mpws
==========
*CMD BernoulliDistribution --- Bernoulli distribution
*STD
*CALL 
        BernoulliDistribution(p)

*PARMS

{p} -- number, probability of an event in a single trial

*DESC 
A random variable has a Bernoulli distribution with probability {p} if
it can be interpreted as an indicator of an event, where {p} is the
probability to observe the event in a single trial.

Numerical value of {p} must satisfy $0<p<1$.

*EXAMPLES
In> NM(PMF(BernoulliDistribution(.4), 1)) 
Result: 0.6

In> NM(CDF(BernoulliDistribution(.4), 1)) 
Result: 0.4

*SEE BinomialDistribution, ChiSquareDistribution, DiscreteUniformDistribution, ExponentialDistribution, GeometricDistribution, NormalDistribution, PoissonDistribution, tDistribution

*SOURCE org/mathpiper/scripts4/statistics/distributions/BernoulliDistribution.mpws
==========
*CMD BinomialDistribution --- binomial distribution
*STD
*CALL
        BinomialDistribution(p,n)

*PARMS
{p} -- number, probability to observe an event in single trial

{n} -- number of trials

*DESC
Suppose we repeat a trial {n} times, the probability to observe an
event in a single trial is {p} and outcomes in all trials are mutually
independent. Then the number of trials when the event occurred
is distributed according to the binomial distribution. The probability
of that is {BinomialDistribution}{(p,n)}.

Describes the number of successes for draws with replacement.

Numerical value of {p} must satisfy $0<p<1$. Numerical value
of {n} must be a positive integer. 


*EXAMPLES
In> NM(PMF(BinomialDistribution(.1,15),0)) 
Result: 0.2058911321

In> NM(CDF(BinomialDistribution(.1,15),2)) 
Result: 0.8159389308

*SEE BernoulliDistribution, ChiSquareDistribution, DiscreteUniformDistribution, ExponentialDistribution, GeometricDistribution, NormalDistribution, PoissonDistribution, tDistribution

*SOURCE org/mathpiper/scripts4/statistics/distributions/BinomialDistribution.mpws
==========
*CMD ChiSquareDistribution --- Chi square distribution
*STD
*CALL
        ChiSquareDistribution(p)

*PARMS

{p} -- number, probability of an event in a single trial

*DESC
A random variable has a ChiSquare distribution with probability {p} if
it can be interpreted as an indicator of an event, where {p} is the
probability to observe the event in a single trial.

Numerical value of {p} must satisfy $0<p<1$.

*EXAMPLES
In> NM(PDF(ChiSquareDistribution(5), 7)) 
Result: 0.07437126808

In> NM(CDF(ChiSquareDistribution(5), 2)) 
Result: 0.08208499862

*SEE BinomialDistribution, BernoulliDistribution, DiscreteUniformDistribution, ContinuousUniformDistribution, ExponentialDistribution, GeometricDistribution, NormalDistribution, PoissonDistribution, tDistribution

*SOURCE org/mathpiper/scripts4/statistics/distributions/ChiSquareDistribution.mpws
==========
*CMD ContinuousUniformDistribution --- Discrete uniform distribution
*STD
Result: PMF(ContinuousUniformDistribution(1,2),1)


*CALL
        ContinuousUniformDistribution(a, b)

*PARMS

{a} -- number, lower range value
{b} -- number, upper range value

*EXAMPLES
In> NM(PDF(ContinuousUniformDistribution(1,5), 1.6)) 
Result: 0.25

*SEE BinomialDistribution, BernoulliDistribution, ChiSquareDistribution, DiscreteUniformDistribution, ExponentialDistribution, GeometricDistribution, NormalDistribution, PoissonDistribution, tDistribution

*SOURCE org/mathpiper/scripts4/statistics/distributions/ContinuousUniformDistribution.mpws
==========
*CMD ContinuousUniformDistribution --- Discrete uniform distribution
*STD
*CALL
        DiscreteDistribution(dom, prob)

*PARMS

{dom} -- list
{prob} -- list

*EXAMPLES
In> DiscreteDistribution(_x, _y) 
Result: DiscreteDistribution(_x, _y)

In> DiscreteDistribution(2,1) 
Result: Undefined

*SEE BinomialDistribution, BernoulliDistribution, ChiSquareDistribution, DiscreteUniformDistribution, ContinuousUniformDistribution, ExponentialDistribution, GeometricDistribution, NormalDistribution, PoissonDistribution, tDistribution

*SOURCE org/mathpiper/scripts4/statistics/distributions/DiscreteDistribution.mpws
==========
*CMD DiscreteUniformDistribution --- Discrete uniform distribution
*STD
*CALL
        DiscreteUniformDistribution(a, b)

*PARMS

{a} -- number, lower range value
{b} -- number, upper range value


*EXAMPLES
In> DiscreteUniformDistribution(1, 2) 
Result: DiscreteUniformDistribution(1, 2)

In> DiscreteUniformDistribution(_x, _y) 
Result: DiscreteUniformDistribution(_x, _y)
*SEE BinomialDistribution, BernoulliDistribution, ChiSquareDistribution, ContinuousUniformDistribution, ExponentialDistribution, GeometricDistribution, NormalDistribution, PoissonDistribution, tDistribution

*SOURCE org/mathpiper/scripts4/statistics/distributions/DiscreteUniformDistribution.mpws
==========
*CMD ExponentialDistribution --- Exponential distribution
*STD
*CALL
        ExponentialDistribution(lambda)

*PARMS

{lambda} -- number, the rate parameter


*EXAMPLES
In> ExponentialDistribution(2) 
Result: ExponentialDistribution(2)

In> ExponentialDistribution(-2) 
Result: Undefined

In> ExponentialDistribution(_x) 
Result: ExponentialDistribution(_x)
*SEE BinomialDistribution, BernoulliDistribution, ChiSquareDistribution, DiscreteUniformDistribution, ContinuousUniformDistribution, GeometricDistribution, NormalDistribution, PoissonDistribution, tDistribution

*SOURCE org/mathpiper/scripts4/statistics/distributions/ExponentialDistribution.mpws
==========
*CMD FDistribution --- the F distribution
*CALL
 Not Implemented Yet


*SOURCE org/mathpiper/scripts4/statistics/distributions/FDistribution.mpws
==========
*CMD GeometricDistribution --- Geometric distribution
*STD
*CALL
        GeometricDistribution(p)

*PARMS

{p} -- number, probability of an event in a single trial


*EXAMPLES
In> GeometricDistribution(1) 
Result: GeometricDistribution(1)

In> GeometricDistribution(2) 
Result: Undefined

In> NM(PMF(GeometricDistribution(.4), 1)) 
Result: 0.24
*SEE BinomialDistribution, BernoulliDistribution, DiscreteUniformDistribution, ChiSquareDistribution, ContinuousUniformDistribution, ExponentialDistribution, NormalDistribution, PoissonDistribution, tDistribution

*SOURCE org/mathpiper/scripts4/statistics/distributions/GeometricDistribution.mpws
==========
*CMD HypergeometricDistribution --- Hypergeometric distribution
*STD
*CALL
        HypergeometricDistribution(N, M, n)

*PARMS

{N} -- number, a finite population
{M} -- number of items from N that fall into a class of interest
{n} -- number of items drawn from N

*DESC

A discrete probability distribution that describes the number of successes in a sequence of
draws from a finite population without replacement.  The hypergeometric distribution is the
probability model which is used for selecting a random sample of n items without replacement 
from a lot of N items, M of which are nonconforming or defective.


*EXAMPLES
In> NM(PMF(HypergeometricDistribution(100,5,10),0)) 
Result: 0.583752367

In> NM(CDF(HypergeometricDistribution(100,5,10),1)) 
Result: 0.9231432779
*SEE BinomialDistribution, BernoulliDistribution, ChiSquareDistribution, DiscreteUniformDistribution, ExponentialDistribution, GeometricDistribution, NormalDistribution, PoissonDistribution, tDistribution

*SOURCE org/mathpiper/scripts4/statistics/distributions/HypergeometricDistribution.mpws
==========
*CMD NormalDistribution --- The normal distribution.
*STD
*CALL
        NormalDistribution(mean, sigma)

*PARMS

{mean} -- Number, the mean of the distribution
{sigma} -- Number, the standard deviation of the distribution

*DESC
The normal distribution.

*EXAMPLES
In> NM(CDF(NormalDistribution(60,5),64.3)) 
Result: 0.8051055222

*SEE BinomialDistribution, BernoulliDistribution, ChiSquareDistribution, DiscreteUniformDistribution, ContinuousUniformDistribution, ExponentialDistribution, GeometricDistribution, NormalDistribution, PoissonDistribution, tDistribution

*SOURCE org/mathpiper/scripts4/statistics/distributions/NormalDistribution.mpws
==========
*CMD PoissonDistribution --- Poisson distribution
*STD
*CALL
        PoissonDistribution(lambda)

*PARMS
{lambda} -- number, the expected number of occurrences that occur during the given interval

*DESC
The poisson distribution.

*EXAMPLES
In> NM(PMF(PoissonDistribution(5), 7)) 
Result: 0.1044448631

In> NM(CDF(PoissonDistribution(5), 2)) 
Result: 0.1246520197

*SEE BinomialDistribution, BernoulliDistribution, DiscreteUniformDistribution, ChiSquareDistribution, ContinuousUniformDistribution, ExponentialDistribution, GeometricDistribution, NormalDistribution, PoissonDistribution, tDistribution

*SOURCE org/mathpiper/scripts4/statistics/distributions/PoissonDistribution.mpws
==========
*CMD tDistribution --- Student's $t$ distribution
*STD
*CALL
        [tDistribution](m)

*PARMS 
{m} -- integer, number of degrees of freedom

*DESC

*REM what does it do???
The procedure {tDistribution} returns the ...

Let $Y$ and $Z$ be independent random variables, $Y$ have the 
NormalDistribution(0,1), {Z} have ChiSquareDistribution(m). Then 
$Y/Sqrt(Z/m)$ has tDistribution(m).

Numerical value of {m} must be positive integer.

*SOURCE org/mathpiper/scripts4/statistics/distributions/tDistribution.mpws
==========
*CMD ChiSquareTest --- Pearson's ChiSquare test
*STD

*CALL
        ChiSquareTest(observed,expected)

*PARMS
{observed} -- list of observed frequencies

{expected} -- list of expected frequencies

*DESC
{ChiSquareTest} is intended to determine if a sample was drawn from a
given distribution or not. To find this out, one has to calculate
observed frequencies into certain intervals and expected ones.


*EXAMPLES
In> x := ChiSquareTest([145,128,73,32,22], [160,120,80,20,20]) 
Result: [["chiSquareScore",9.952083333],["pValue",0.0540319219],["degreesOfFreedom",4]]

In> TableForm(a) 
Result: [["chiSquareScore",9.952083333],["pValue",0.0540319219],["degreesOfFreedom",4]] 
Side Effects: 
["chiSquareScore",9.952083333] 
["pValue",0.0540319219] 
["degreesOfFreedom",4]
*SEE AlphaToChiSquareScore, ChiSquareScoreToAlpha

*SOURCE org/mathpiper/scripts4/statistics/hypothesystest/ChiSquareTest.mpws
==========
*CMD Regress --- find regression

*CALL
        Regress(x, y)

*PARMS
{x, y} -- lists


*DESC
This procedure finds the regression of y onto x, that is y == alpha + beta * x.


*EXAMPLES
In> x := 1 .. 5 
Result: [1,2,3,4,5]

In> y := (2.34*x+2) +(2*2-1) 
Result: [7.34,9.68,12.02,14.36,16.7]

In> Regress(x,y) 
Result: [alpha :: my - xy*mx/x2,beta :: xy/x2]

*SOURCE org/mathpiper/scripts4/statistics/regression/Regress.mpws
==========
*CMD Exp --- exponential function
*STD
*CALL
        Exp(x)

*PARMS

{x} -- argument to the procedure

*DESC

This procedure calculates $e$ raised to the power $x$, where $e$ is the
mathematic constant 2.71828... One can use {Exp(1)}
to represent $e$.

This procedure is threaded, meaning that if the argument {x} is a
list, the procedure is applied to all entries in the list.

*EXAMPLES
In> Exp(0) 
Result: 1

In> Exp(I*Pi) 
Result: Exp(Complex(0, Pi))

In> NM(Exp(1)) 
Result: 2.71828183
*SEE Ln, Sin, Cos, Tan, NM

*SOURCE org/mathpiper/scripts4/stdfuncs/Exp.mpws
==========
*CMD Ln --- natural logarithm
*STD
*CALL
        Ln(x)

*PARMS

{x} -- argument to the procedure

*DESC

This procedure calculates the natural logarithm of "x". This is the
inverse function of the exponential function, {Exp}, i.e. $Ln(x) = y$ implies that $Exp(y) = x$. For complex
arguments, the imaginary part of the logarithm is in the interval
(-$Pi$,$Pi$}. This is compatible with the branch cut of {Arg}.

This procedure is threaded, meaning that if the argument {x} is a
list, the procedure is applied to all entries in the list.

*EXAMPLES
In> Ln(1) 
Result: 0

In> Ln(3) 
Result: Ln(3)

In> NM(Ln(3)) 
Result: 1.098612289

In> Ln(Exp(_x)) 
Result: _x
*SEE Exp, Arg

*SOURCE org/mathpiper/scripts4/stdfuncs/Ln.mpws
==========
*CMD MathSqrtFloat --- square root for floats
*CALL
        MathSqrtFloat(u)

*PARMS

{u} -- float


*DESC

This procedure calculates the square root of a float rounded to one decimal place.


*EXAMPLES
In> SqrtN(3) 
Result: 1.732050808

In> MathSqrtFloat(3) 
Result: 1.7

In> SqrtN(10) 
Result: 3.16227766

In> MathSqrtFloat(10) 
Result: 3.2
*SEE Sqrt, SqrtD, SqrtN

*SOURCE org/mathpiper/scripts4/stdfuncs/elemfuncs/MathSqrtFloat.mpws
==========
*CMD SqrtN --- square root (x must be >= 0) (arbitrary-precision math procedure)
*CALL
        SqrtN(x)

*DESC

This command performs the calculation of an elementary mathematical
function.  The arguments <i>must</i> be numbers.  The reason for the
postfix {N} is that the library needs to define equivalent non-numerical
procedures for symbolic computations, such as {Exp}, {Sin}, etc.

Note that all xxxN procedures accept integers as well as floating-point numbers.
The resulting values may be integers or floats.  If the mathematical result is an
exact integer, then the integer is returned.  For example, {Sqrt(25)} returns
the integer {5}, and {Power(2,3)} returns the integer {8}.  In such cases, the
integer result is returned even if the calculation requires more digits than set by
{BuiltinPrecisionSet}.  However, when the result is mathematically not an integer,
the procedures return a floating-point result which is correct only to the current precision.

*EXAMPLES
In> BuiltinPrecisionSet(10) 
Result: 10

In> Sqrt(10) 
Result: Sqrt(10)

In> SqrtN(10) 
Result: 3.16227766

In> SqrtN(490000*2^150) 
Result: 26445252304070013196697600

In> SqrtN(490000*2^150+1) 
Result: 26445252300000000000000000
*SEE Sqrt, SqrtD, MathSqrtFloat

*SOURCE org/mathpiper/scripts4/stdfuncs/elemfuncs/SqrtN.mpws
==========
*CMD ExpN --- exponential (base 2.718)
*CALL
        ExpNum(x)

    
*PARMS    
{X} -- a real number
    

*DESC

This procedure solves an exponential equation with a base of 2.718.

This is a low-level numerical calculation of an elementary procedure. 
It is only called if NumericMode?() returns True.


*EXAMPLES
In> ExpN(1) 
Result: 2.71828183

In> ExpN(2) 
Result: 7.389056086

In> ExpN(3.7) 
Result: 40.4473044
*SEE ExpN


*SOURCE org/mathpiper/scripts4/stdfuncs/numerical/ExpNum.mpws
==========
*CMD InternalLnNum --- natural logarithm

*CALL
        InternalLnNum(u)

*PARMS

{u} -- number


*DESC

This procedure solves a logarithmic equation using the input number.

This is a low-level numerical calculation of an elementary procedure. 
It is only called if NumericMode?() returns True.


*EXAMPLES
In> InternalLnNum(2) 
Result: 0.6931471807

In> InternalLnNum(4.3) 
Result: 1.458615023
*SEE Ln

*SOURCE org/mathpiper/scripts4/stdfuncs/numerical/InternalLnNum.mpws
==========
*CMD NewtonLn --- natural logarithm

*CALL
        NewtonLn(u)

*PARMS

{u} -- number


*DESC

This procedure solves a logarithmic equation using the input number.

This is a low-level numerical calculation of an elementary procedure. 
It is only called if NumericMode?() returns True.


*EXAMPLES
In> NewtonLn(2) 
Result: 0.6931471807

In> NewtonLn(4.3) 
Result: 1.458615023
*SEE Ln

*SOURCE org/mathpiper/scripts4/stdfuncs/numerical/NewtonLn.mpws
==========
*CMD MathExpThreshold --- display exponential threshold
*CMD SetMathExpThreshold --- change exponential threshold

*CALL
        MathExpThreshold()
        SetMathExpThreshhold(u)

*PARMS

{u} -- number


*DESC

{MathExpThreshold} displays the current exponential threshold and {SetMathExpThreshold}
changes the exponential threshold to the input number.

These are low-level numerical calculations of elementary procedures. 
They are only called if NumericMode?() returns True.


*EXAMPLES
In> MathExpThreshold() 
Result: 500

In> SetMathExpThreshold(10) 
Result: 10

In> MathExpThreshold() 
Result: 10

*SOURCE org/mathpiper/scripts4/stdfuncs/numerical/expthreshold.mpws
==========
*CMD NewtonNum --- low-level optimized Newton's iterations
*STD
*CALL
        NewtonNum(func, x0, prec0, order)
        NewtonNum(func, x0, prec0)
        NewtonNum(func, x0)

*PARMS

{func} -- a procedure specifying the iteration sequence

{x0} -- initial value (must be close enough to the root)

{prec0} -- initial precision (at least 4, default 5)

{order} -- convergence order (typically 2 or 3, default 2)

*DESC

This procedure is an optimized interface for computing Newton's
iteration sequences for numerical solution of equations in arbitrary precision.

{NewtonNum} will iterate the given function starting from the initial
value, until the sequence converges within current precision.
Initially, up to 5 iterations at the initial precision {prec0} is
performed (the low precision is set for speed). The initial value {x0}
must be close enough to the root so that the initial iterations
converge. If the sequence does not produce even a single correct digit
of the root after these initial iterations, an error message is
printed. The default value of the initial precision is 5.

The {order} parameter should give the convergence order of the scheme.
Normally, Newton iteration converges quadratically (so the default
value is {order}=2) but some schemes converge faster and you can speed
up this procedure by specifying the correct order. (Caution: if you give
{order}=3 but the sequence is actually quadratic, the result will be
silently incorrect. It is safe to use {order}=2.)

*REM
The verbose option {V} can be used to monitor the convergence. The
achieved exact digits should roughly form a geometric progression.

*EXAMPLES
In> NewtonNum('[[x], x+Sin(x)], 3, 5, 3) 
Result: 3.141592654

*SOURCE org/mathpiper/scripts4/stdfuncs/nummethods/NewtonNum.mpws
==========

*CMD ArcCos --- inverse trigonometric function arccosine

*CALL
        ArcCos(x)

*PARMS

{x} -- argument to the procedure

*DESC

This procedure represents the inverse trigonometric function arccosine.


*EXAMPLES
In> ArcCos(2) 
Result: ArcCos(2)

In> NM(ArcCos(.5)) 
Result: 1.047197551
*SEE Sin, Cos, Tan, Cot, Sec, Csc, ArcSin, ArcTan, ArcCot, ArcSec, ArcCsc

*SOURCE org/mathpiper/scripts4/stdfuncs/trigsymbolic/ArcCos.mpws
==========

*CMD ArcCot --- inverse trigonometric function arccotangent

*CALL
        ArcCot(x)

*PARMS

{x} -- argument to the procedure

*DESC

This procedure represents the inverse trigonometric function arccotangent.


*EXAMPLES
In> ArcCot(2) 
Result: ArcCot(2)

In> NM(ArcCot(1.5)) 
Result: 0.5880026035
*SEE Sin, Cos, Tan, Cot, Sec, Csc, ArcSin, ArcCos, ArcTan, ArcSec, ArcCsc

*SOURCE org/mathpiper/scripts4/stdfuncs/trigsymbolic/ArcCot.mpws
==========

*CMD ArcCsc --- inverse trigonometric function arccosecant

*CALL
        ArcCsc(x)

*PARMS

{x} -- argument to the procedure

*DESC

This procedure represents the inverse trigonometric function arccosecant.


*EXAMPLES
In> ArcCsc(2) 
Result: ArcCsc(2)

In> NM(ArcCsc(1.5)) 
Result: 0.7297276562
*SEE Sin, Cos, Tan, Cot, Sec, Csc, ArcSin, ArcCos, ArcTan, ArcCot, ArcSec

*SOURCE org/mathpiper/scripts4/stdfuncs/trigsymbolic/ArcCsc.mpws
==========

*CMD ArcSec --- inverse trigonometric function arcsecant

*CALL
        ArcSec(x)

*PARMS

{x} -- argument to the procedure

*DESC

This procedure represents the inverse trigonometric function arcsecant.

*EXAMPLES
In> ArcSec(2) 
Result: ArcSec(2)

In> NM(ArcSec(1.5)) 
Result: 0.8410686706
*SEE Sin, Cos, Tan, Cot, Sec, Csc, ArcSin, ArcCos, ArcTan, ArcCot, ArcCsc

*SOURCE org/mathpiper/scripts4/stdfuncs/trigsymbolic/ArcSec.mpws
==========

*CMD ArcSin --- inverse trigonometric function arcsine

*CALL
        ArcSin(x)

*PARMS

{x} -- argument to the procedure

*DESC

This procedure represents the inverse trigonometric function arcsine.


*EXAMPLES
In> ArcSin(2) 
Result: ArcSin(2)

In> NM(ArcSin(.5)) 
Result: 0.5235987756
*SEE Sin, Cos, Tan, Cot, Sec, Csc, ArcCos, ArcTan, ArcCot, ArcSec, ArcCsc

*SOURCE org/mathpiper/scripts4/stdfuncs/trigsymbolic/ArcSin.mpws
==========

*CMD ArcTan --- inverse trigonometric function arctangent

*CALL
        ArcTan(x)

*PARMS

{x} -- argument to the procedure

*DESC

This procedure represents the inverse trigonometric function arctangent.


*EXAMPLES
In> ArcTan(2) 
Result: ArcTan(2)

In> NM(ArcTan(.5)) 
Result: 0.463647609
*SEE Sin, Cos, Tan, Cot, Sec, Csc, ArcSin, ArcCos, ArcCot, ArcSec, ArcCsc

*SOURCE org/mathpiper/scripts4/stdfuncs/trigsymbolic/ArcTan.mpws
==========

*CMD Cos --- trigonometric function cosine

*CALL
        Cos(x)

*PARMS

{x} -- argument to the procedure

*DESC

This procedure represents the trigonometric function cosine.


*EXAMPLES
In> Cos(2) 
Result: Cos(2)

In> NM(Cos(4`rad)) 
Result: -0.6536436209

In> NM(Cos(7`deg)) 
Result: 0.9925461516
*SEE Sin, Tan, Cot, Sec, Csc, ArcSin, ArcCos, ArcTan, ArcCot, ArcSec, ArcCsc

*SOURCE org/mathpiper/scripts4/stdfuncs/trigsymbolic/Cos.mpws
==========

*CMD Cot --- trigonometric function cotangent

*CALL
        Cot(x)

*PARMS

{x} -- argument to the procedure

*DESC

This procedure represents the trigonometric function cotangent.

*EXAMPLES
In> Cot(2) 
Result: Cot(2)

In> NM(Cot(4`rad)) 
Result: 0.8636911545

In> NM(Cot(7`deg)) 
Result: 8.144346431
*SEE Sin, Cos, Tan, Sec, Csc, ArcSin, ArcCos, ArcTan, ArcCot, ArcSec, ArcCsc

*SOURCE org/mathpiper/scripts4/stdfuncs/trigsymbolic/Cot.mpws
==========

*CMD Csc --- trigonometric function cosecant

*CALL
        Csc(x)

*PARMS

{x} -- argument to the procedure

*DESC

This procedure represents the trigonometric function cosecant.


*EXAMPLES
In> Csc(2) 
Result: Csc(2)

In> NM(Csc(4`rad)) 
Result: -1.321348709

In> NM(Csc(7`deg)) 
Result: 8.205509051
*SEE Sin, Cos, Tan, Sec, Cot, ArcSin, ArcCos, ArcTan, ArcCsc, ArcSec, ArcCot

*SOURCE org/mathpiper/scripts4/stdfuncs/trigsymbolic/Csc.mpws
==========

*CMD Sec --- trigonometric function secant

*CALL
        Sec(x)

*PARMS

{x} -- argument to the procedure

*DESC

This procedure represents the trigonometric function secant.

*EXAMPLES
In> Sec(2) 
Result: Sec(2)

In> NM(Sec(4`rad)) 
Result: -1.529885656

In> NM(Sec(7`deg)) 
Result: 1.007509825
*SEE Sin, Cos, Tan, Cot, Sec, Csc, ArcSin, ArcCos, ArcTan, ArcCot, ArcSec, ArcCsc

*SOURCE org/mathpiper/scripts4/stdfuncs/trigsymbolic/Sec.mpws
==========

*CMD Sin --- trigonometric function sine

*CALL
        Sin(x)

*PARMS

{x} -- argument to the procedure

*DESC

This procedure represents the trigonometric function sine.


*EXAMPLES
In> Sin(2) 
Result: Sin(2)

In> NM(Sin(4`rad)) 
Result: -0.7568024953

In> NM(Sin(7`deg)) 
Result: 0.1218693434
*SEE Cos, Tan, Cot, Sec, Csc, ArcSin, ArcCos, ArcTan, ArcCot, ArcSec, ArcCsc

*SOURCE org/mathpiper/scripts4/stdfuncs/trigsymbolic/Sin.mpws
==========

*CMD Tan --- trigonometric function tangent

*CALL
        Tan(x)

*PARMS

{x} -- argument to the procedure

*DESC

This procedure represents the trigonometric function tangent.


*EXAMPLES
In> Tan(2) 
Result: Tan(2)

In> NM(Tan(4`rad)) 
Result: 1.157821282

In> NM(Tan(7`deg)) 
Result: 0.1227845609
*SEE Sin, Cos, Cot, Sec, Csc, ArcSin, ArcCos, ArcTan, ArcCot, ArcSec, ArcCsc

*SOURCE org/mathpiper/scripts4/stdfuncs/trigsymbolic/Tan.mpws
==========
*CMD Abs --- absolute value or modulus of complex number
*STD
*CALL
        Abs(x)

*PARMS

{x} -- argument to the procedure

*DESC

This procedure returns the absolute value (also called the modulus) of
"x". If "x" is positive, the absolute value is "x" itself; if
"x" is negative, the absolute value is "-x". For complex "x",
the modulus is the "r" in the polar decomposition
$x = r *Exp(I*phi)$.

This procedure is connected to the {Sign} procedure by
the identity "Abs(x) * Sign(x) = x" for real "x".

This procedure is threaded, meaning that if the argument {x} is a
list, the procedure is applied to all entries in the list.

*EXAMPLES
In> Abs(2) 
Result: 2

In> Abs(-1/2) 
Result: 1/2

In> Abs(3+4*I) 
Result: 5
*SEE Sign, Arg

*SOURCE org/mathpiper/scripts4/stubs/Abs.mpws
==========
*CMD CanonicalAdd --- put an expression in canonical form

*CALL
        CanonicalAdd( (u+v)+w )

*PARMS

{u, v, w} -- number or constant

*DESC

This procedure returns an expression in the canonical form with its
terms grouped to the right.

*EXAMPLES
In> CanonicalAdd( (_a + _b) + _c ) 
Result: _a + (_b + _c)

In> CanonicalAdd( (_a - _b) + _c ) 
Result: _a + (_c - _b)

In> CanonicalAdd( (_a + _b) - _c ) 
Result: _a + (_b - _c)

In> CanonicalAdd( (_a - _b) - _c ) 
Result: _a - (_b + _c)

*SOURCE org/mathpiper/scripts4/stubs/CanonicalAdd.mpws
==========
*CMD Ceil --- round a number upwards
*STD
*CALL
        Ceil(x)

*PARMS

{x} -- a number

*DESC

This procedure returns $Ceil(x)$, the smallest integer larger than or equal to $x$.

*EXAMPLES
In> Ceil(1.1) 
Result: 2

In> Ceil(-1.1) 
Result: -1

In> Ceil(4/3) 
Result: 2
*SEE Floor, Round

*SOURCE org/mathpiper/scripts4/stubs/Ceil.mpws
==========
*CMD Floor --- round a number downwards
*STD
*CALL
        Floor(x)

*PARMS

{x} -- a number

*DESC

This procedure returns $Floor(x)$, the largest integer smaller than or equal to $x$.

*EXAMPLES
In> Floor(1.1) 
Result: 1

In> Floor(-1.1) 
Result: -2

In> Floor(4/3) 
Result: 1
*SEE Ceil, Round

*SOURCE org/mathpiper/scripts4/stubs/Floor.mpws
==========
*CMD Gcd --- greatest common divisor
*STD
*CALL
        Gcd(n,m)
        Gcd(list)

*PARMS

{n}, {m} -- integers or Gaussian integers or univariate polynomials

{list} -- a list of all integers or all univariate polynomials

*DESC

This procedure returns the greatest common divisor of "n" and "m".
The gcd is the largest number that divides "n" and "m".  It is
also known as the highest common factor (hcf).  The library code calls
{MathGcd}, which is an internal procedure.  This
procedure implements the "binary Euclidean algorithm" for determining the
greatest common divisor:

*HEAD        Routine for calculating {Gcd(n,m)}
        
*        1. if $n = m$ then return $n$
*        2. if both $n$ and $m$ are even then return $2*Gcd(n/2,m/2)$
*        3. if exactly one of $n$ or $m$ (say $n$) is even then return $Gcd(n/2,m)$
*        4. if both $n$ and $m$ are odd and, say, $n>m$ then return $Gcd((n-m)/2,m)$

This is a rather fast algorithm on computers that can efficiently shift
integers. When factoring Gaussian integers, a slower recursive algorithm is used.

If the second calling form is used, {Gcd} will
return the greatest common divisor of all the integers or polynomials
in "list". It uses the identity
$$Gcd(a,b,c) = Gcd(Gcd(a,b),c)$$.

*EXAMPLES
In> Gcd(55,10) 
Result: 5

In> Gcd([60,24,120]) 
Result: 12

In> Gcd(7300 + 12*I, 2700 + 100*I) 
Result: Complex(-4,4)
*SEE Lcm

*SOURCE org/mathpiper/scripts4/stubs/Gcd.mpws
==========
*CMD Lcm --- least common multiple
*STD
*CALL
        Lcm(n,m)
        Lcm(list)

*PARMS

{n}, {m} -- integers or univariate polynomials
{list}         -- list of integers

*DESC

This command returns the least common multiple of "n" and "m" or all of
the integers in the list {list}.
The least common multiple of two numbers "n" and "m" is the lowest
number which is an integer multiple of both "n" and "m".
It is calculated with the formula
$$Lcm(n,m) = Quotient(n*m,Gcd(n,m))$$.

This means it also works on polynomials, since {Div}, {Gcd} and multiplication are also defined for
them.

*EXAMPLES
In> Lcm(60,24) 
Result: 120

In> Lcm([3,5,7,9]) 
Result: 315
*SEE Gcd


*SOURCE org/mathpiper/scripts4/stubs/Lcm.mpws
==========
*CMD LnCombine --- combine logarithmic expressions using standard logarithm rules
*STD
*CALL
        LnCombine(expr)

*PARMS

{expr} -- an expression possibly containing multiple {Ln} terms to be combined

*DESC

{LnCombine} finds {Ln} terms in the expression it is given, and combines them
using logarithm rules.  It is intended to be the exact converse of {LnExpand}.

*EXAMPLES
In> LnCombine(Ln(_a)+Ln(_b)*_n) 
Result: Ln(_a*_b^_n)

In> LnCombine(2*Ln(2)+Ln(3)-Ln(5)) 
Result: Ln(12/5)
*SEE Ln, LnExpand

*SOURCE org/mathpiper/scripts4/stubs/LnCombine.mpws
==========
*CMD LnExpand --- expand a logarithmic expression using standard logarithm rules
*STD
*CALL
        LnExpand(expr)

*PARMS

{expr} -- the logarithm of an expression

*DESC

{LnExpand} takes an expression of the form $Ln(expr)$, and applies logarithm
rules to expand this into multiple {Ln} expressions where possible.  An
expression like $Ln(a*b^n)$ would be expanded to $Ln(a)+n*Ln(b)$.

If the logarithm of an integer is discovered, it is factorised using {Factors}
and expanded as though {LnExpand} had been given the factorised form.  So 
$Ln(18)$ goes to $Ln(x)+2*Ln(3)$.

*EXAMPLES
In> LnExpand(Ln(_a*_b^_n)) 
Result: Ln(_a) + Ln(_b)*_n

In> LnExpand(Ln(_a^_m/_b^_n)) 
Result: Ln(_a)*_m - Ln(_b)*_n
*SEE Ln, LnCombine

*SOURCE org/mathpiper/scripts4/stubs/LnExpand.mpws
==========
*CMD Modulo --- Determine remainder of two mathematical objects after dividing one by the other

*STD
*CALL
        Modulo(x,y)
        Modulo(x,y,vars)

*PARMS

{x}, {y} -- integers or univariate polynomials
{vars}   -- a list containing the name of the (single) variable appearing in both polynomials

*DESC

{Modulo} returns the remainder after division.  {Modulo} is 
also defined for univariate polynomials.

If {Quotient(x,y)} returns "a" and {Modulo(x,y)} equals "b", 
then these numbers satisfy $x =a*y + b$ and $0 <= b < y$.

The second form of the procedure contains a third parameter, 
and is used in the special case where the  the "divisor" 
polynomial contains an unbound "variable" which is really 
just a parameter.   In that situation, MathPiper cannot 
distinguish the variable from the parameter, until you
specifically name the variable.  See the example below.

*EXAMPLES
In> Quotient(5,3) 
Result: 1

In> Modulo(5,3) 
Result: 2

In> Modulo([2,1],[2,2]) 
Result: [0,1]
*SEE Gcd, Lcm, Quotient

*SOURCE org/mathpiper/scripts4/stubs/Modulo.mpws
==========
*CMD Object --- create an incomplete type
*STD
*CALL
        Object("pred", exp)

*PARMS

{pred} -- name of the predicate to apply

{exp} -- expression on which "pred" should be applied

*DESC

This procedure returns "obj" as soon as "pred" returns {True} 
when applied on "obj". This is used to declare
so-called incomplete types.

*EXAMPLES
In> x := 5 
Result: 5

In> a := Object("Number?", x) 
Result: 5

In> Eval(a) 
Result: 5

When x does not have a number assigned to it:

In> x := _b 
Result: _b

In> a := Object("Number?", x) 
Result: Object("Number?", _b)

In> Eval(a) 
Result: Object("Number?", _b)
*SEE NonObject?

*SOURCE org/mathpiper/scripts4/stubs/Object.mpws
==========
*CMD Quotient --- Determine quotient of two mathematical objects

*STD
*CALL
        Quotient(x,y)

*PARMS

{x}, {y} -- integers or univariate polynomials

*DESC

{Quotient} performs integer division. {Quotient} is also defined for polynomials.

If {Quotient(x,y)} returns "a" and {Modulo(x,y)} equals "b", then these numbers satisfy $x =a*y + b$ and $0 <= b < y$.

*EXAMPLES
Quotient(5,3) -> 1

Modulo(5,3) -> 2

*SEE Gcd, Lcm, Modulo

*SOURCE org/mathpiper/scripts4/stubs/Quotient.mpws
==========
*CMD Rem --- Determine remainder of two mathematical objects after dividing one by the other

*CALL
        Rem(x,y)

*PARMS

{x}, {y} -- numbers

*DESC

This procedure returns the remainder after division.

*EXAMPLES
In> Quotient(5,3) 
Result: 1

In> Rem(5,3) 
Result: 2
*SEE Quotient, Modulo

*SOURCE org/mathpiper/scripts4/stubs/Rem.mpws
==========
*CMD Round --- round a number to the nearest integer
*STD
*CALL
        Round(x)

*PARMS

{x} -- a number

*DESC

This procedure returns the integer closest to $x$. Half-integers
(i.e. numbers of the form $n + 0.5$, with $n$ an integer) are
rounded upwards.

*EXAMPLES
Round(1.49) -> 1

Round(1.51) -> 2

Round(-1.49) -> -1

Round(-1.51) -> -2

*SEE Floor, Ceil

*SOURCE org/mathpiper/scripts4/stubs/Round.mpws
==========
*CMD Sign --- sign of a number
*STD
*CALL
        Sign(x)

*PARMS

{x} -- argument to the procedure

*DESC

This procedure returns the sign of the real number $x$. It is "1"
for positive numbers and "-1" for negative numbers. {Sign(0)} is defined to be 0.

This procedure is connected to the {Abs} procedure by
the identity $Abs(x) * Sign(x) = x$ for real $x$.

This procedure is threaded, meaning that if the argument {x} is a
list, the procedure is applied to all entries in the list.

*EXAMPLES
In> Sign(2) 
Result: 1

In> Sign(-3) 
Result: -1

In> Sign(0) 
Result: 0

In> Sign(-3) * Abs(-3) 
Result: -3
*SEE Arg, Abs

*SOURCE org/mathpiper/scripts4/stubs/Sign.mpws
==========
*CMD Sqrt --- square root
*STD
*CALL
        Sqrt(x)

*PARMS

{x} -- argument to the procedure

*DESC

This procedure calculates the square root of "x". If the result is
not rational, the call is returned unevaluated unless a numerical
approximation is forced with the {NM} procedure. This
procedure can also handle negative and complex arguments.

This procedure is threaded, meaning that if the argument {x} is a
list, the procedure is applied to all entries in the list.

*EXAMPLES
In> Sqrt(16) 
Result: 4

In> Sqrt(15) 
Result: Sqrt(15)

In> NM(Sqrt(15)) 
Result: 3.8729833462

In> Sqrt(4/9) 
Result: 2/3

In> Sqrt(-1) 
Result: Complex(0,1)
*SEE Exp, ^, NM

*SOURCE org/mathpiper/scripts4/stubs/Sqrt.mpws
==========
*CMD <? --- test for "less than"
*STD
*CALL
        e1 <? e2

*PARMS

{e1}, {e2} -- expressions to be compared

*DESC

The two expression are evaluated. If both results are numeric, they
are compared. If the first expression is smaller than the second one,
the result is {True} and it is {False} otherwise. If either of the expression is not numeric, after
evaluation, the expression is returned with evaluated arguments.

The word "numeric" in the previous paragraph has the following
meaning. An expression is numeric if it is either a number (i.e. {Number?} returns {True}), or the
quotient of two numbers, or an infinity (i.e. {Infinity?} returns {True}). MathPiper will try to 
coerce the arguments passed to this comparison operator to a real value before making the comparison.

*EXAMPLES
In> 2 <? 5 
Result: True

In> Cos(1) <? 5 
Result: True
*SEE Number?, Infinity?, NM

*SOURCE org/mathpiper/scripts4/stubs/comparison_operators.mpws
==========
*CMD >? --- test for "greater than"
*STD
*CALL
        e1 >? e2

*PARMS

{e1}, {e2} -- expressions to be compared

*DESC

The two expression are evaluated. If both results are numeric, they
are compared. If the first expression is larger than the second one,
the result is {True} and it is {False} otherwise. If either of the expression is not numeric, after
evaluation, the expression is returned with evaluated arguments.

The word "numeric" in the previous paragraph has the following
meaning. An expression is numeric if it is either a number (i.e. {Number?} returns {True}), or the
quotient of two numbers, or an infinity (i.e. {Infinity?} returns {True}). MathPiper will try to 
coerce the arguments passed to this comparison operator to a real value before making the comparison.

*EXAMPLES
In> 2 >? 5 
Result: False

In> Cos(1) >? 5 
Result: False
*SEE Number?, Infinity?, NM

*SOURCE org/mathpiper/scripts4/stubs/comparison_operators.mpws
==========
*CMD <=? --- test for "less or equal"
*STD
*CALL
        e1 <=? e2

*PARMS

{e1}, {e2} -- expressions to be compared

*DESC

The two expression are evaluated. If both results are numeric, they
are compared. If the first expression is smaller than or equals the
second one, the result is {True} and it is {False} otherwise. If either of the expression is not
numeric, after evaluation, the expression is returned with evaluated
arguments.

The word "numeric" in the previous paragraph has the following
meaning. An expression is numeric if it is either a number (i.e. {Number?} returns {True}), or the
quotient of two numbers, or an infinity (i.e. {Infinity?} returns {True}). MathPiper will try to 
coerce the arguments passed to this comparison operator to a real value before making the comparison.

*EXAMPLES
In> 2 <=? 5 
Result: True

In> Cos(1) <=? 5 
Result: True
*SEE Number?, Infinity?, NM

*SOURCE org/mathpiper/scripts4/stubs/comparison_operators.mpws
==========
*CMD >=? --- test for "greater or equal"
*STD
*CALL
        e1 >=? e2

*PARMS

{e1}, {e2} -- expressions to be compared

*DESC

The two expression are evaluated. If both results are numeric, they
are compared. If the first expression is larger than or equals the
second one, the result is {True} and it is {False} otherwise. If either of the expression is not
numeric, after evaluation, the expression is returned with evaluated
arguments.

The word "numeric" in the previous paragraph has the following
meaning. An expression is numeric if it is either a number (i.e. {Number?} returns {True}), or the
quotient of two numbers, or an infinity (i.e. {Infinity?} returns {True}). MathPiper will try to 
coerce the arguments passed to this comparison operator to a real value before making the comparison.

*EXAMPLES
In> 2 >=? 5 
Result: False

In> Cos(1) >=? 5 
Result: False
*SEE Number?, Infinity?, NM

*SOURCE org/mathpiper/scripts4/stubs/comparison_operators.mpws
==========
*CMD !=? --- test for "not equal"
*STD
*CALL
        e1 !=? e2

*PARMS

{e1}, {e2} -- expressions to be compared

*DESC

Both expressions are evaluated and compared. If they turn out to be
equal, the result is {False}. Otherwise, the result
is {True}.

The expression {e1 !=? e2} is equivalent to {Not?(e1 = e2)}.

*EXAMPLES
In> 1 !=? 2 
Result: True

In> 1 !=? 1 
Result: False
*SEE =?

*SOURCE org/mathpiper/scripts4/stubs/comparison_operators.mpws
==========
*CMD = --- test for equality of expressions
*STD
*CALL
        e1 =? e2

*PARMS

{e1}, {e2} -- expressions to be compared

*DESC

Both expressions are evaluated and compared. If they turn out to be equal, the
result is {True}. Otherwise, the result is {False}. The procedure {Equals?} does
the same.

Note that the test is on syntactic equality, not mathematical equality. Hence
even if the result is {False}, the expressions can still be
<i>mathematically</i> equal; see the examples below. Put otherwise, this
procedure tests whether the two expressions would be displayed in the same way
if they were printed.

*EXAMPLES
In> e1 := (_x + 1) * (_x - 1) 
Result: (_x + 1)*(_x - 1)

In> e2 := _x^2 - 1 
Result: _x^2 - 1

In> e1 =? e2 
Result: False
*SEE !=?, Equals?

*SOURCE org/mathpiper/scripts4/stubs/comparison_operators.mpws
==========
*CMD << --- binary shift left operator
*CMD >> --- binary shift right operator
*STD
*CALL
        n<<m
        n>>m

*PARMS

{n}, {m} -- integers

*DESC

These operators shift integers to the left or to the right.
They are similar to the C shift operators. These are sign-extended
shifts, so they act as multiplication or division by powers of 2.

*EXAMPLES
1 << 10 -> 1024

-1024 >> 10 -> -1

*SEE +, -, *, ^

*SOURCE org/mathpiper/scripts4/stubs/shifting_operators.mpws
==========
*CMD Add --- find sum of a list of values
*STD
*CALL
        Add(val1, val2, ...)
        Add([list])

*PARMS

{val1}, {val2} -- expressions

{[list]} -- list of expressions to add

*DESC

This procedure adds all its arguments and returns their sum. It accepts any
number of arguments. The arguments can be also passed as a list.

*EXAMPLES
In> Add(1,4,9) 
Result: 14

In> Add(1 .. 10) 
Result: 55

*SOURCE org/mathpiper/scripts4/sums/Add.mpws
==========
*CMD Average --- find the average of a list of numbers

*CALL
        Average(val1, val2, ...)
        Average(list)

*PARMS

{val1}, {val2} -- numbers

{list} -- list of numbers to add

*DESC

This procedure returns the average of all its arguments. It accepts any
number of arguments. The arguments can be also passed as a list.

*EXAMPLES
In> Average(2,3,4) 
Result: 3

In> Average([5,9,7]) 
Result: 7

In> NM(Average(4,5,9,11)) 
Result: 7.25

*SOURCE org/mathpiper/scripts4/sums/Average.mpws
==========
*CMD Factorial  --- factorial

*CALL
        Factorial(n)
        
*PARMS
{n} -- integer or half-integer

*DESC
The factorial procedure calculates the factorial of integer or half-integer numbers. For
nonnegative integers, $n! := n*(n-1)*(n-2)*...*1$. The factorial of
half-integers is defined via Euler's Gamma procedure, $z! := Gamma(z+1)$. If $n=0$ the procedure returns $1$.

The factorial procedure throws an exception if the argument is too large (currently the limit 
is $n < 65535$) because exact factorials of such large numbers are computationally expensive and most probably 
not useful. One can call {InternalLnGammaNum()} to evaluate logarithms of such factorials to desired precision.

*EXAMPLES
In> Factorial(5) 
Result: 120

In> 1 * 2 * 3 * 4 * 5 
Result: 120

In> Factorial(1/2) 
Result: Sqrt(Pi)/2
*SEE BinomialCoefficient, Product, Gamma, ***, Subfactorial

*SOURCE org/mathpiper/scripts4/sums/Factorial.mpws
==========
*CMD Maximum --- maximum of a number of values
*STD
*CALL
        Maximum(x,y)
        Maximum(list)

*PARMS

{x}, {y} -- pair of values to determine the maximum of

{list} -- list of values from which the maximum is sought

*DESC

This procedure returns the maximum value of its argument(s). If the
first calling sequence is used, the larger of "x" and "y" is
returned. If one uses the second form, the largest of the entries in
"list" is returned. In both cases, this procedure can only be used
with numerical values and not with symbolic arguments.

*EXAMPLES
In> Maximum(2,3) 
Result: 3

In> Maximum([5,8,4]) 
Result: 8
*SEE Minimum, Sum

*SOURCE org/mathpiper/scripts4/sums/Maximum.mpws
==========
*CMD Minimum --- minimum of a number of values
*STD
*CALL
        Minimum(x,y)
        Minimum(list)

*PARMS

{x}, {y} -- pair of values to determine the minimum of

{list} -- list of values from which the minimum is sought

*DESC

This procedure returns the minimum value of its argument(s). If the
first calling sequence is used, the smaller of "x" and "y" is
returned. If one uses the second form, the smallest of the entries in
"list" is returned. In both cases, this procedure can only be used
with numerical values and not with symbolic arguments.

*EXAMPLES
In> Minimum(2,3) 
Result: 2

In> Minimum([5,8,4]) 
Result: 4
*SEE Maximum, Sum

*SOURCE org/mathpiper/scripts4/sums/Minimum.mpws
==========
*CMD Product --- product of a list of values
*STD
*CALL
        Product(list)
        Product(var, from, to, body)

*PARMS

{list} -- list of values to multiply

{var} -- variable to iterate over

{from} -- integer value to iterate from

{to} -- integer value to iterate up to

{body} -- expression to evaluate for each iteration

*DESC

The first form of the {Product} command simply
multiplies all the entries in "list" and returns their product.

If the second calling sequence is used, the expression "body" is
evaluated while the variable "var" ranges over all integers from
"from" up to "to", and the product of all the results is
returned. Obviously, "to" should be greater than or equal to
"from".

*EXAMPLES
In> Product([1,2,3,4]) 
Result: 24

In> Product(i, 1, 4, i) 
Result: 24

*SEE Sum, Apply

*SOURCE org/mathpiper/scripts4/sums/Product.mpws
==========
*CMD Subfactorial  --- factorial and related procedures
*CALL
        Subfactorial(m)

*PARMS
{m} -- integer

*DESC
The {Subfactorial} procedure can be interpreted as the  number of permutations of {m} objects in which no object 
appears in its natural place, also called "derangements." 

The factorial procedures terminate and print an error message if the arguments are too large (currently the limit 
is $n < 65535$) because exact factorials of such large numbers are computationally expensive and most probably 
not useful. One can call {InternalLnGammaNum()} to evaluate logarithms of such factorials to desired precision.

*EXAMPLES
In> Subfactorial(10) 
Result: 1334961

*SEE BinomialCoefficient, Product, Gamma, ***,

*SOURCE org/mathpiper/scripts4/sums/Subfactorial.mpws
==========
*CMD Sum --- find the sum of the elements in a list
*STD
*CALL
        Sum(list)

*PARMS

{list} -- list of values to sum


*DESC

Adds all the entries in "list" and returns their sum.


*EXAMPLES
In> Sum([1,2,3]) 
Result: 6

In> Sum(1 .. 10) 
Result: 55
*SEE Product

*SOURCE org/mathpiper/scripts4/sums/Sum.mpws
==========
*CMD ***  --- partial factorial operator

*CALL
        a *** b

*PARMS
{a}, {b} -- numbers

*DESC
The "partial factorial" procedure {a *** b} calculates the product $a*(a+1)*...$ 
which is terminated at the least integer not greater than $b$. The arguments $a$ 
and $b$ do not have to be integers; for integer arguments, {a *** b} = $b! / (a-1)!$. 
This procedure is sometimes a lot faster than evaluating the two factorials, 
especially if $a$ and $b$ are close together. If $a>b$ the procedure returns $1$.

The factorial procedures terminate and print an error message if the arguments are too large (currently the limit 
is $n < 65535$) because exact factorials of such large numbers are computationally expensive and most probably 
not useful. One can call {InternalLnGammaNum()} to evaluate logarithms of such factorials to desired precision.

*EXAMPLES
In> 1/3 *** 10 
Result: 17041024000/59049

In> 1 *** 10 
Result: 3628800

In> 2 *** 8 
Result: 40320
*SEE BinomialCoefficient, Product, Gamma, Subfactorial

*SOURCE org/mathpiper/scripts4/sums/asterisk_asterisk_asterisk_operator.mpws
==========
*CMD Check --- throw an exception if a value is not of the specified type or types

*CALL
	CheckType(value, predicatesString)

*PARMS

{value} -- a value to check

{predicatesString} -- string which holds the names of one or more single argument predicate procedures

*DESC
Applies all of the single argument predicate
procedures that are listed in {predicatesString}
to the {value}. If the predicates are separated by
a comma, then all of the predicates need to
return "True" in order for the check to pass. If the
predicates are separated by a semicolon, then
at least one of the predicates need to return "True"
in order order for the check to pass.

If a check fails, an exception is thrown. If it
passes, it returns the value as a result. 

*EXAMPLES
In> CheckType(3, "PositiveNumber?") 
Result: 3

In> CheckType(3, "NegativeNumber?") 
Result: Exception
Exception:  Error: The value "3" is not of type "NegativeNumber". Starting at index 20.

In> CheckType(3, "PositiveNumber?,Integer?") 
Result: 3

In> CheckType(3, "PositiveNumber?,String?") 
Result: Exception
Exception:  Error: The value "3" is not of type "String". Starting at index 20.

In> CheckType(3, "PositiveNumber?;String?") 
Result: 3

In> CheckType(3, "NegativeNumber?;String?") 
Result: Exception
Exception:  Error: The value "3" is not of any of the specified types. Starting at index 16.

*SEE Check


*SOURCE org/mathpiper/scripts4/testers/CheckType.mpws
==========
*CMD KnownFailure --- Mark a test as a known failure
*STD
*CALL
        KnownFailure(test)

*PARMS

{test} -- expression that should return {False} on failure

*DESC

The command {KnownFailure} marks a test as known to fail
by displaying a message to that effect on screen.

This might be used by developers when they have no time
to fix the defect, but do not wish to alarm users who download
MathPiper and type {make test}.

*E.G.

In> KnownFailure(Verify(1,2))
        Known failure:
        ******************
         1 evaluates to  1 which differs from  2
        ******************
Result: False;

In> KnownFailure(Verify(1,1))
        Known failure:
        Failure resolved!
Result: True;

*SEE Verify, TestMathPiper, LogicVerify, LogicTest


*SOURCE org/mathpiper/scripts4/testers/KnownFailure.mpws
==========
*CMD LogicTest --- verifying equivalence of two expressions
*STD
*CALL
        LogicTest(variables,expr1,expr2)

*PARMS

{variables} -- list of variables

{exprN} -- Some boolean expression

*DESC

The command {LogicTest} can be used to verify that an
expression is <I>equivalent</I> to  a correct answer after evaluation.
It returns {True} or {False}.


*E.G.

In> LogicTest([A,B,C],Not?((!? A) &? (!? B)),A |? B)
Result: True

In> LogicTest([A,B,C],Not?((!? A) &? (!? B)),A |? C)
        ******************
        CommandLine: 1

        $TrueFalse4([A,B,C],Not?(!? A &? !? B))
         evaluates to
        [[[False,False],[True,True]],[[True,True],[True,True]]]
         which differs from
        [[[False,True],[False,True]],[[True,True],[True,True]]]
        ******************
Result: False

*SEE KnownFailure, Verify, TestMathPiper, LogicVerify


*SOURCE org/mathpiper/scripts4/testers/LogicTest.mpws
==========
*CMD LogicVerify --- verifying equivalence of two expressions
*STD
*CALL
        LogicVerify(question,answer)

*PARMS

{question} -- expression to check for

{answer} -- expected result after evaluation


*DESC

The command {LogicVerify} can be used to verify that an
expression is <I>equivalent</I> to  a correct answer after evaluation.
It returns {True} or {False}

*E.G.
In> LogicVerify(a &? c |? b &? !? c,a |? b)
Result: True;

In> LogicVerify(a &? c |? b &? !? c,b |? a)
Result: True;

*SEE KnownFailure, Verify, TestMathPiper, LogicTest


*SOURCE org/mathpiper/scripts4/testers/LogicVerify.mpws
==========
*CMD NumericEqual --- check for equivalence of two numbers

*CALL
        NumericEqual(num1, num2, prec)

*PARMS

{num1, num2} -- numbers

{prec} -- integer, precision to use


*DESC

This procedure is used to determine if two numbers are equal. {num1} is compared to {num2}, to {prec} digits of precision.
The procedure returns {True} if the numbers are equal and returns {False} if they are not equal.


*EXAMPLES
In> NumericEqual(3, 3, 1) 
Result: True

In> NumericEqual(2, 3, 1) 
Result: False

In> NumericEqual(1.2345, 1.2340, 3) 
Result: True

In> NumericEqual(1.2345, 1.2340, 4) 
Result: False

*SEE Verify

*SOURCE org/mathpiper/scripts4/testers/NumericEqual.mpws
==========
*CMD RandVerifyArithmetic --- Special purpose arithmetic verifiers
*STD
*CALL
        RandVerifyArithmetic(n)

*PARMS

{n} -- integer arguments

*DESC

{RandVerifyArithmetic(n)} calls {VerifyArithmetic} with
random values, {n} times.

*E.G.

In> RandVerifyArithmetic(4)
Result: True;

*SEE Verify, VerifyArithmetic, RandVerifyArithmetic, VerifyDiv, KnownFailure, TestMathPiper, LogicVerify, LogicTest


*SOURCE org/mathpiper/scripts4/testers/RandVerifyArithmetic.mpws
==========
*CMD RoundTo --- Round a real-valued result to a set number of digits
*STD
*CALL
        RoundTo(number,precision)

*PARMS

{number} -- number to round off

{precision} -- precision to use for round-off

*DESC

The procedure {RoundTo} rounds a floating point number to a
specified precision, allowing for testing for correctness
using the {Verify} command.

*E.G.

In> NM(RoundTo(Exp(1),30),30)
Result: 2.71828182110230114951959786552;

In> NM(RoundTo(Exp(1),20),20)
Result: 2.71828182796964237096;

*SEE Verify, VerifyArithmetic, VerifyDiv


*SOURCE org/mathpiper/scripts4/testers/RoundTo.mpws
==========
*CMD TestMathPiper --- verifying equivalence of two expressions
*STD
*CALL
        TestMathPiper(question,answer)

*PARMS

{question} -- expression to check for

{answer} -- expected result after evaluation

*DESC

The command {TestMathPiper} can be used to verify that an
expression is <I>equivalent</I> to  a correct answer after evaluation.
It returns {True} or {False}.

*E.G.
In> TestMathPiper(x*(1+x),x^2+x)
Result: True;


*SEE KnownFailure, Verify, LogicVerify, LogicTest


*SOURCE org/mathpiper/scripts4/testers/TestMathPiper.mpws
==========
*CMD Verify --- verifying equivalence of two expressions
*STD
*CALL
        Verify(question, answer)

*PARMS

{question} -- expression to check for

{answer} -- expected result after evaluation


*DESC

The command {Verify} can be used to verify that an
expression is <I>equivalent</I> to  a correct answer after evaluation.
It returns {True} or {False}.

For some calculations, the demand that two expressions
are <I>identical</I> syntactically is too stringent. The
MathPiper system might change at various places in the future,
but $ 1+x $ would still be equivalent, from a mathematical
point of view, to $ x+1 $.

The general problem of deciding that two expressions $ a $ and $ b $
are equivalent, which is the same as saying that $ a-b=0 $ ,
is generally hard to decide on. The following commands solve
this problem by having domain-specific comparisons.

The comparison commands do the following comparison types:

*        {Verify} -- verify for literal equality.
This is the fastest and simplest comparison, and can be
used, for example, to test that an expression evaluates to $ 2 $.
*        {TestMathPiper} -- compare two expressions after simplification as
multivariate polynomials. If the two arguments are equivalent
multivariate polynomials, this test succeeds. {TestMathPiper} uses {Simplify}. Note: {TestMathPiper} currently should not be used to test equality of lists.
*        {LogicVerify} -- Perform a test by using {CanProve} to verify that from
{question} the expression {answer} follows. This test command is
used for testing the logic theorem prover in MathPiper.
*        {LogicTest} -- Generate a truth table for the two expressions and compare these two tables. They should be the same if the two expressions are logically the same.

*E.G.
In> Verify(1+2,3)
Result: True;

In> Verify(x*(1+x),x^2+x)
        ******************
        x*(x+1) evaluates to x*(x+1) which differs
          from x^2+x
        ******************
Result: False;

In> TestMathPiper(x*(1+x),x^2+x)
Result: True;

In> Verify(a &? c |? b &? !? c,a |? b)
        ******************
         a &? c |? b &? !? c evaluates to  a &? c
          |? b &? !? c which differs from  a |? b
        ******************
Result: False;

In> LogicVerify(a &? c |? b &? !? c,a |? b)
Result: True;

In> LogicVerify(a &? c |? b &? !? c,b |? a)
Result: True;

In> LogicTest([A,B,C],Not?((!? A) &? (!? B)),A |? B)
Result: True

In> LogicTest([A,B,C],Not?((!? A) &? (!? B)),A |? C)
        ******************
        CommandLine: 1

        TrueFalse4([A,B,C],Not?(!? A &? !? B))
         evaluates to
        [[[False,False],[True,True]],[[True,True],[True,True]]]
         which differs from
        [[[False,True],[False,True]],[[True,True],[True,True]]]
        ******************
Result: False

*SEE KnownFailure, TestMathPiper, LogicVerify, LogicTest


*SOURCE org/mathpiper/scripts4/testers/Verify.mpws
==========
*CMD VerifyArithmetic --- Special purpose arithmetic verifiers
*STD
*CALL
        VerifyArithmetic(x,n,m)

*PARMS

{x}, {n}, {m} -- integer arguments

*DESC

The command {VerifyArithmetic} tests a
mathematic equality which should hold, testing that the
result returned by the system is mathematically correct
according to a mathematically provable theorem.

{VerifyArithmetic} verifies for an arbitrary set of numbers
$ x $, $ n $ and $ m $ that
$$ (x^n-1)*(x^m-1) = x^(n+m)-(x^n)-(x^m)+1 $$.

The left and right side represent two ways to arrive at the
same result, and so an arithmetic module actually doing the
calculation does the calculation in two different ways.
The results should be exactly equal.

*EXAMPLES
VerifyArithmetic(100,50,60) -> True

*SEE Verify,RandVerifyArithmetic, VerifyDiv, KnownFailure, TestMathPiper, LogicVerify, LogicTest


*SOURCE org/mathpiper/scripts4/testers/VerifyArithmetic.mpws
==========
*CMD VerifyDiv --- Special purpose arithmetic verifiers
*STD
*CALL
        VerifyDiv(u,v)

*PARMS

{u}, {v} -- integer arguments

*DESC

{VerifyDiv(u,v)} checks that
$$ u = v*Quotient(u,v) + Modulo(u,v) $$.


*E.G.

In> VerifyDiv(x^2+2*x+3,x+1)
Result: True;

In> VerifyDiv(3,2)
Result: True;

*SEE Verify, VerifyArithmetic, RandVerifyArithmetic, VerifyDiv, KnownFailure, TestMathPiper, LogicVerify, LogicTest


*SOURCE org/mathpiper/scripts4/testers/VerifyDiv.mpws
==========
*CMD VerifySolve --- verifies that one expression is mathematically equivalent to another
*STD
*CALL
        VerifySolve(expression,answer)

*PARMS

{expression} -- expression to be checked

{answer} -- expected result


*DESC

VerifySolve(expression, answer) tests whether 'expression' evaluates to 
something "equal" to 'answer', and complains explicitly if it doesn't. 

  Here, "equal" means:
   o  for lists: having the same entries, possibly in a different order;
   o  for equations: having the same right-hand sides, possibly after 'Simplify';
   o  in all other cases: equality, possible after 'Simplify'.
  Hence, { a == 1, a == x+1 } is "equal" to { a == 1+x, a == 1 }.

The command {VerifySolve} is usually employed to verify that an equation or
set of equations has been solved correctly.   

But it also has a wider applicability.

NOTE:
    This procedure used to be defined in the test file solve.mpt, where it was
used extensively.  However, by defining it in that file, it was unavailable for
use as a general tool.  Now it has been made available.

*E.G.


In> VerifySolve(Solve(a+x*y==z,x),[x==(z-a)/y]);
Result: True


In> VerifySolve(Solve(a+x*y==z,x),[x==(a-z)/y]);
Result: False
Side Effects:
******************
none: -1 
Solve(a+x*y==z,x)
 evaluates to
[x==-(a-z)/y]
 which differs from
[x==(a-z)/y]
******************


In> Verify(x*(1+x),x+x^2)
Result: False
Side Effects:
******************
none: -1 
x*(1+x)
 evaluates to
x*(x+1)
 which differs from
x+x^2
******************


In> VerifySolve(x*(1+x),x+x^2)
Result: True

NOTE: Verify cannot see past the syntactical dissimilarity;  
      VerifySolve can see the mathematical identity.

*SEE Verify, KnownFailure, TestMathPiper, LogicVerify, LogicTest


*SOURCE org/mathpiper/scripts4/testers/VerifySolve.mpws
==========
*CMD RecognizedUnitsAll --- list of recognized units appearing in an expression (with duplicates)

*CALL
        RecognizedUnitsAll(expression)

*PARMS

{expression} -- an expression


*DESC

The command {RecognizedUnitsAll(expression)} returns a list of all recognized
units (including duplicates) that appear in the expression {expression}.


*EXAMPLES
In> RecognizedUnitsAll(m*A) 
Result: [m,A]

In> RecognizedUnitsAll(10`mA * 5`Ω == 50`mV) 
Result: [mA,Ω,mV]

In> RecognizedUnitsAll(20`mA * 10 == 200`mA) 
Result: [mA,mA]

*SEE RecognizedUnit?

*SOURCE org/mathpiper/scripts4/units/RecognizedUnitsAll.mpws
==========
*CMD UnitsEqual? --- test if two units are equal

*CALL
        UnitsEqual?(x,y)

*PARMS

{x,y} -- units to compare


*DESC

This command tests whether two units are equal. It returns {True} if the units
are equal and {False} if they are not equal.


*EXAMPLES
In> UnitsEqual?(2`mA, 2`mA) 
Result: True

In> UnitsEqual?(5`mA, 3`mA) 
Result: False

In> UnitsEqual?(3`mA, 1`mA + 2`mA) 
Result: True

In> UnitsEqual?(4`A, 4000`mA) 
Result: True

In> UnitsEqual?(20`V ∠ 40`deg, 20`V ∠ 40`deg) 
Result: True

In> UnitsEqual?(25`V ∠ 40`deg, 20`V ∠ 40`deg) 
Result: False

In> UnitsEqual?(20`V ∠ 45`deg, 20`V ∠ 40`deg) 
Result: False

*SEE UnitsGreaterThan?, UnitsLessThan?

*SOURCE org/mathpiper/scripts4/units/UnitsEqual_.mpws
==========
*CMD UnitsGreaterThan? --- test if one unit is greater than another unit

*CALL
        UnitsGreaterThan?(x,y)

*PARMS

{x,y} -- units to compare


*DESC

This command compares two units. It returns {True} if {x} is greater than
{y}. Otherwise, it returns {False}.


*EXAMPLES
In> UnitsGreaterThan?(5`mA, 3`mA) 
Result: True

In> UnitsGreaterThan?(2`mA, 5`mA) 
Result: False

In> UnitsGreaterThan?(10`V ∠ 30`deg, 5`V ∠ 20`deg) 
Result: True

In> UnitsGreaterThan?(3`V  ∠ 20`deg, 4`V ∠ 80`deg) 
Result: False

*SEE UnitsLessThan?, UnitsEqual?

*SOURCE org/mathpiper/scripts4/units/UnitsGreaterThan_.mpws
==========
*CMD UnitsLessThan? --- test if one unit is less than another unit

*CALL
        UnitsLessThan?(x,y)

*PARMS

{x,y} -- units to compare


*DESC

This command compares two units. It returns {True} if {x} is less than
{y}. Otherwise, it returns {False}.


*EXAMPLES
In> UnitsLessThan?(2`mA, 5`mA) 
Result: True

In> UnitsLessThan?(5`mA, 3`mA) 
Result: False

In> UnitsLessThan?(3`V  ∠ 20`deg, 4`V ∠ 80`deg) 
Result: True

In> UnitsLessThan?(10`V ∠ 30`deg, 5`V ∠ 20`deg) 
Result: False

*SEE UnitsGreaterThan?, UnitsEqual?

*SOURCE org/mathpiper/scripts4/units/UnitsLessThan_.mpws
==========
*CMD UnitsStrip --- remove the units from an expression

*CALL
        UnitsStrip(x ` y)

*PARMS

{x} -- constant
{y} -- units


*DESC

This command strips the units from an expression and returns the constant alone.


*EXAMPLES
In> UnitsStrip(x_ ` y_) 
Result: x_

*SOURCE org/mathpiper/scripts4/units/UnitsStrip.mpws
==========
*CMD UnitsStripAll --- remove the units from an expression

*CALL
        UnitsStripAll(expression)

*PARMS

{x} -- expression
{y} -- unit


*DESC

This command strips all of the the units from an expression.


*EXAMPLES
In> UnitsStripAll(x_ ` y_) 
Result: x_

*SOURCE org/mathpiper/scripts4/units/UnitsStripAll.mpws
==========
*CMD ` --- unit operator

*CALL
a ` u

*PARMS
{a} -- an expression
{u} -- a symbolic expression

*DESC
Creates a unit expression, which can be used with familar arithmetic operations to perform physical calculations.
There are several units builtin to mathpiper, including SI units and common imperial units, additionally there are methods to create your own.
MathPiper provides the unit conversion operator, {#}, to easily convert between units.

More formally, units follow the following arithmetic rules:

(a ` u) + (b ` u) =? (a + b) ` u

(a ` u) * (b ` v) =? (a * b) ` (u * v)

(a ` u) ^ 2 =? (a^2) ` (u^2)

*EXAMPLES
In> 1 ` m 
Result: 1 ` m

In> 1 ` m + 1 ` m 
Result: 2 ` m

In> 1 ` m * 1 ` N 
Result: 1 ` (m*N)

In> (2 ` m) ^ 2 
Result: 4 ` (m^2)

If a mix of SI and imperial are used with multiplication or division, the units are automatically converted to SI

In> 2 ` m * 3 ` ft 
Result: (1143/625)`(m^2)

Similarly if a mix of different imperial units are used, the units are automatically simplified

In> 2`inch * 3`ft 
Result: 72`(inch^2)

Finally, Ad-Hoc units can be used

In> 1 ` cat_ + 2 ` cat_ 
Result: 3 ` cat_

*SEE #

*SOURCE org/mathpiper/scripts4/units/mpunits.mpws
==========
*CMD # --- unit conversion operator

*CALL
a # v

*PARMS
{a} -- an expression with units
{v} -- a symbolic expression

*DESC
Converts the expression {a} to use the units {v}. There are many built in unit conversions in MathPiper,
as well as a means to create user conversions with {DeclareUnitConversion}. 
There is automatic detection if a given conversion is impossible, based on the dimensions of the input units. 

Unit conversion distributes across addition and subtraction. 

*EXAMPLES
In> 1 ` ft # yard 
Result: (1/3) ` yard

In> 1 ` ft # m 
Result: (381/1250) ` m

In> NM(1 ` ft # m) 
Result: 0.3048 ` m

In> 1 ` ft + 1 ` m 
Result: 1 ` ft + 1 ` m

In> 1 ` ft + 1 ` m # ft 
Result: (1631/381) ` ft

In> 1 ` ft # second 
Result: Exception 
Exception:  Error: Invalid Conversion: the left side has dimensions: <Length> 
While the right side has different dimensions: <Time> Starting at index 7.

In> DeclareUnitConversion(_cat -> 3 * _dog) 
Result: True

In> 1`_cat # _dog 
Result: 3`_dog

In> RemoveUnitConversion(_cat) 
Result: 3`_dog

Without the unit conversion, you get nonsense

In> 1 `_cat # _dog 
Result: (_cat/_dog)`_dog

*SEE `, DeclareUnitConversion, RemoveUnitConversion

*SOURCE org/mathpiper/scripts4/units/mpunits.mpws
==========
*CMD UnitOf --- unit separation procedure
*CMD ValueOf --- value separation procedure

*CALL
UnitOf(a)
ValueOf(a)

*PARMS
{a} -- an expression with units

*DESC
Retrieves the unit or value of an expression with units.

*EXAMPLES
In> UnitOf(2 ` m) 
Result: m

In> ValueOf(2 ` m) 
Result: 2

*SEE `

*SOURCE org/mathpiper/scripts4/units/mpunits.mpws
==========
*CMD RecognizedUnit? --- unit recognition predicate

*CALL
RecognizedUnit?(u)

*PARMS
{u} -- a symbol

*DESC
Returns {True} if MathPiper recognizes the symbol as a unit, {False} otherwise.

*EXAMPLES
In> RecognizedUnit?(meter) 
Result: True

In> RecognizedUnit?(True) 
Result: False


*SOURCE org/mathpiper/scripts4/units/mpunits.mpws
==========
*CMD SIUnit? --- SI unit recognition predicate

*CALL
SIUnit?(u)

*PARMS
{u} -- a symbol

*DESC
Returns {True} if MathPiper recognizes the symbol as an SI unit, {False} otherwise.

*EXAMPLES
In> SIUnit?(meter) 
Result: True

In> SIUnit?(yard) 
Result: False
*SEE NonSIUnit?, BaseOrDerivedUnit?

*SOURCE org/mathpiper/scripts4/units/mpunits.mpws
==========
*CMD NonSIUnit? --- non-SI unit recognition predicate

*CALL
NonSIUnit?(u)

*PARMS
{u} -- a symbol

*DESC
Returns {True} if MathPiper recognizes the symbol as a non-SI unit, {False} otherwise.

*EXAMPLES
In> NonSIUnit?(meter) 
Result: False

In> NonSIUnit?(yard) 
Result: True
*SEE SIUnit?, BaseOrDerivedUnit?

*SOURCE org/mathpiper/scripts4/units/mpunits.mpws
==========
*CMD DeclareUnitConversion -- declare a unit conversion
*CMD RemoveUnitConversion  -- remove a unit conversion

*CALL
DeclareUnitConversion(u -> expression);
RemoveUnitConversion(u -> expression);

*PARMS
{u} -- a symbol
{expression} -- an expression

*DESC
Declares (or removes) a MathPiper conversion. {u} must be a user created symbol, and expression must only involve multiplication and division.
A list of currently known conversions is returned.

*EXAMPLES
In> DeclareUnitConversion(_left -> 3 * _right) 
Result: True

In> 3`_right # _left 
Result: 1`_left

In> RemoveUnitConversion(_left) 
Result: 3 * _right

MathPiper no longer understands _left and _right

In> 3`_right # _left 
Result: ((3*_right)/_left)`_left

*SEE #

*SOURCE org/mathpiper/scripts4/units/mpunits.mpws
==========
*CMD DeclareFundamentalDimension --- declare a fundamental dimension
*CMD DeclareDimensionConversion --- declare a dimension conversion
*CMD RemoveFundamentalDimension --- remove a fundamental dimension
*CMD RemoveDimensionConversion  --- remove a dimension conversion

*CALL
DeclareFundamentalDimension(dimension)
DeclareDimensionConversion(u -> dimension)
RemoveFundamentalDimension(dimension)
RemoveDimensionConversion(u -> dimension)

*PARMS
{dimension} -- a symbol, conventionally this is Capitalized
{u} -- a symbol

*DESC
These four procedures are closely related, often used together, and all return a list of the current known dimensions/conversions respectively. 
The difference is dimension conversions are used in {DimensionsOf} to calculate the dimension of a given unit.
Whereas fundamental units are only used in {DimensionsAsListOf} to create a list based on the result of a call to {DimensionsOf}. 
The conversion type checking works based on {DimensionsAsListOf}, so if this behavior is not desired, one can forgo the call to DeclareFundamentalDimension.

A note of caution is that it is possible to remove the standard dimensions of MathPiper, which would break the automatic conversion type checking.

*EXAMPLES
In> DeclareFundamentalDimension(_Livestock) 
Result: [...,_Livestock]

In> DeclareDimensionConversion(_sheep -> _Livestock) 
Result: [...,_sheep -> _Livestock]

In> DimensionsOf(_sheep) 
Result: _Livestock

In> DimensionsAsListOf(_sheep) 
Result: [0,0,0,0,0,0,0,1]

In> 1 ` m # _sheep 
Result: Exception 
Exception:  Error: Invalid Conversion: the left side has dimensions: <Length> 
While the right side has different dimensions: <_Livestock> Starting at index 6.

In> RemoveDimensionConversion(_sheep -> _Livestock) 
Result: [...]

In> RemoveFundamentalDimension(_Livestock) 
Result: [...]


*SEE DimensionsOf,DimensionsAsListOf

*SOURCE org/mathpiper/scripts4/units/mpunits.mpws
==========
*CMD FundamentalUnitsOf --- calculate the fundamental units of an expression

*CALL
FundamentalUnitsOf(a ` u)
FundamentalUnitsOf(u)

*PARMS
{a} -- an expression
{u} -- a symbolic expression

*DESC
Returns the fundamental units of an expression. Note that these units are implied via conversion rules built into MathPiper, or declared with {DeclareUnitConversion},
not based on an explicit list. Therefore if an ad-hoc unit is passed in for {u}, then the return value will be {u}.

*EXAMPLES
In> FundamentalUnitsOf(3 ` N) 
Result: (kg*m)/s^2

In> FundamentalUnitsOf(N * _sheep / ohm) 
Result: (s * A^2 * _sheep) / m

*SEE DeclareUnitConversion


*SOURCE org/mathpiper/scripts4/units/mpunits.mpws
==========
*CMD DimensionsOf --- calculate the dimensions of an expression
*CMD DimensionsAsListOf -- calculate the dimensions of an expression, and display it as a list

*CALL
DimensionsOf(a ` u)
DimensionsOf(u)
DimensionsAsListOf(a ` u)
DimensionsAsListOf(u)

*PARMS
{a} -- an expression
{u} -- a symbolic expression

*DESC
Similar to {FundamentalUnitsOf}, however an additional substitution is performed to convert the fundamental units into their respective dimension.
The procedures differ in their output format, {DimensionsOf} outputs in a human readable format 
whereas {DimensionsAsListOf} outputs the degree of each dimension in a list with the following order:

[Length, Mass, Time, Current, Temperature, Quantity, LuminousIntensity]. 

These interact well with {DeclareFundamentalDimension} and {DeclareDimensionConversion}.


*EXAMPLES
In> DimensionsAsListOf(N) 
Result: [1,1,-2,0,0,0,0]

In> DeclareFundamentalDimension(_Livestock) 
Result: [...,_Livestock]

In> DeclareDimensionConversion(_sheep -> _Livestock) 
Result: [...,_sheep -> _Livestock]

In> DimensionsAsListOf(_sheep * N) 
Result: [1,1,-2,0,0,0,0,1]

*SEE FundamentalUnitsOf,DeclareFundamentalDimension,DeclareDimensionConversion


*SOURCE org/mathpiper/scripts4/units/mpunits.mpws
==========
*CMD BaseOrDerivedUnit? --- Base Unit or Derived Unit recognition predicate

*Call
        BaseOrDerivedUnit?(x)

*PARMS
{x} -- a unit


*DESC
Returns {True} if MathPiper recognizes the symbol as either an SI base unit or an SI derived unit. Otherwise, it returns {Exception}.


*EXAMPLES
In> BaseOrDerivedUnit?(meter) 
Result: True

In> BaseOrDerivedUnit?(second) 
Result: True

In> BaseOrDerivedUnit?(minute) 
Result: True

In> BaseOrDerivedUnit?(ohm) 
Result: True

In> BaseOrDerivedUnit?(1`V) 
Result: True

In> BaseOrDerivedUnit?(rock) 
Result: Exception 
Exception: Error: The variable <rock> does not have a value assigned to it. Starting at index 19.
*SEE SIUnit?, NonSIUnit?

*SOURCE org/mathpiper/scripts4/units/mpunits.mpws
==========
*CMD LogP10 --- Logarithm for calculating decibel power gain

*CALL
        LogP10(u)

*PARMS
{u} -- a number

*DESC
This procedure is used to calculate the decibel power gain of a circuit.
It uses the formula {10log(A?p)} where A?p is the power gain of the circuit.

*EXAMPLES
In> LogP10(.5) 
Result: (-3.010299957)`dB

In> LogP10(2) 
Result: 3.010299957`dB
*SEE LogV20, AntilogP10, AntilogV20

*SOURCE org/mathpiper/scripts4/units/mpunits.mpws
==========
*CMD LogV20 --- Logarithm for calculating decibel voltage or current gain

*CALL
        LogV20(u)

*PARMS
{u} -- a number

*DESC
This procedure is used to calculate the decibel voltage or current gain of a circuit.
It uses the formula {20log(A?v)} where A?v is the voltage gain of the circuit, 
or {20log(A?i)} where A?i is the current gain of the circuit.

*EXAMPLES
In> LogV20(0.707) 
Result: (-3.011611724)`dB

In> LogV20(0.5) 
Result: (-6.020599914)`dB
*SEE LogP10, AntilogP10, AntilogV20

*SOURCE org/mathpiper/scripts4/units/mpunits.mpws
==========
*CMD AntilogP10 --- Inverse logarithm for converting decibel power gain to standard numeric form

*CALL
        AntilogP10(u)

*PARMS
{u} -- decibel

*DESC
This procedure is used to convert the decibel power gain of a circuit to standard numeric form.
It uses the formula {Antilog( A?p(dB) / 10 )} where A?p is the power gain of the circuit in decibels.

The argument passed to the procedure should be A?p(dB) alone. Division by 10 is completed by the procedure.

*EXAMPLES
In> NM( AntilogP10(-1.8`dB) ) 
Result: 0.6606934478`1

In> NM( AntilogP10(-5`dB) ) 
Result: 0.316227766`1
*SEE LogP10, LogV20, AntilogV20

*SOURCE org/mathpiper/scripts4/units/mpunits.mpws
==========
*CMD AntilogV20 --- Inverse logarithm for converting decibel voltage or current gain to standard numeric form

*CALL
        AntilogV20(u)

*PARMS
{u} -- decibel

*DESC
This procedure is used to convert the decibel voltage or current gain of a circuit to standard numeric form.
It uses the formula {Antilog( A?v(dB) / 20 )} where A?v is the voltage gain of the circuit in decibels,
or {Antilog( A?i(dB) / 20 )} where A?i is the current gain of the circuit in decibels.

The argument passed to the procedure should be A?v(dB) or A?i(dB) alone.
Division by 20 is completed by the procedure.

*EXAMPLES
In> NM( AntilogV20(-2.8`dB) ) 
Result: 0.7244359599`1

In> NM( AntilogV20(2.8`dB) ) 
Result: 1.380384265`1
*SEE LogP10, LogV20, AntilogP10

*SOURCE org/mathpiper/scripts4/units/mpunits.mpws
==========
*CMD CUnparsable? --- check possibility to export expression to C++ code
*STD
*CALL
        CUnparsable?(expr)
        CUnparsable?(expr, funclist)
        
*PARMS

{expr} -- expression to be exported (this argument is not evaluated)

{funclist} -- list of "allowed" procedure names

*DESC

{CUnparsable?} returns {True} if the MathPiper expression {expr} can be exported
into C++ code. This is a check whether the C++ exporter {UnparseC} can be safely
used on the expression.

A MathPiper expression is considered exportable if it contains only procedures that can be translated into C++ (e.g. {ListToProcedure} cannot be exported). All variables and constants are considered exportable.

The verbose option prints names of procedures that are not exportable.

The second calling format of {CUnparsable?} can be used to "allow" certain procedure names that will be available in the C++ code.

*EXAMPLES
In> CUnparsable?(Sin(a1)+2*Cos(b1)) 
Result: True

In> Verbose(CUnparsable?(1+func123(b1))) 
Result: False 
Side Effects: 
CUnparsable?: Info: unexportable procedure(s): func123

This returned {False} because the procedure {func123} is not available in C++. We can 
explicitly allow this procedure and then the expression will be considered exportable:

In> CUnparsable?(1+func123(b1), ["func123"]) 
Result: True

*SEE UnparseC, Verbose                                                   

*SOURCE org/mathpiper/scripts4/unparsers/CUnparsable_.mpws
==========
*CMD Unparse6502 --- convert held mathpiper code to 6502 Assembly 
*STD
*CALL
        Unparse6502(expr)

*PARMS

{code} -- MathPiper code in tree form

*DESC
Unparse6502 returns a string containing an 6502 assembly language
translation of a MathPiper program

The following table lists the parts of MathPiper that are
currently supported:

|table|
|Integers between -128 and 127|
|{} (sequences)|
|[] (treated as arrays)|
|Echo|
|:= (for variable assignment and procedure definition)| 
|If|
|While|
|<?, >?, =?, >=?, <=?, !=?|
|++, --, +, -|
|Length|
|Nl()|
|calling procedures|
|miscellaneous syntax|
|/table

*E.G.
In> code := '{If(1 <? 3){echoVar := "Hello World!";Echo(echoVar);}}
Result: {
    If(1 <? 3)
    {
        echoVar := "Hello World!";
        Echo(echoVar);
    }
}

In> Unparse6502(code)
Result: "
\%uasm65
OutChar: equ E003h ;Output byte in A register to serial port.
GetChar: equ E006h ;Get a byte from the serial port.
GetCharW: equ E009h ;Wait and get a byte from the serial port.
PrntMess: equ E00Ch ;Print a message to the serial port.
OutSpace: equ E00Fh ;Output spaces to the serial port.
OutHex: equ E012h ;Output a HEX number to the serial port.
DgtToBin: equ E015h ;Convert an ASCII digit into binary.
GetLine: equ E018h ;Input a line from the serial port.
     org 0200h



   lda 1d
   cmp 3d
   bcc Over
LessThan:


   ldx ##echoVar<
   ldy ##echoVar>
   jsr PrntMess

   lda ##0Ah
   jsr OutChar
   lda ##13d
   jsr OutChar

Over:



echoVar:
   dbt "Hello World!"
     dbt 0d

    end


*SEE UnparseC, UnparseLatex

*SOURCE org/mathpiper/scripts4/unparsers/Unparse6502.mpws
==========
*CMD UnparseActivityDiagram --- print a flowchart as an expression

*CALL
        UnparseActivityDiagram(code)

*PARMS
{code} -- the flowchart's code

*DESC
This procedure takes the code from a flowchart and prints it as a MathPiper expression.

*EXAMPLES
MATHPIPER_FOLD: 
lst := []; 
For(index := 1, index <=? 5, index++) { Append!(lst,index); } 
lst; 
END_MATHPIPER_FOLD

If a mathpiper fold's flowchart value is set to "true" when <Shift><Enter> is pressed, 
the written code is turned into a flowchart. The flowchart is then used as an argument 
in the UnparseActivityDiagram procedure.

UnparseActivityDiagram(flowchartCode) is used in the output fold to generate the following:

OUTPUT FOLD 
Result: 
lst := []; 
For(index := 1, index <=? 5, index++) { Append!(lst,index); } 
lst; 
END_OUTPUT_FOLD

*SEE UnparseMath2D, UnparseLatex, UnparseC

*SOURCE org/mathpiper/scripts4/unparsers/UnparseActivityDiagram.mpws
==========
*CMD UnparseC --- export expression to C++ code

*CALL
        UnparseC(expr)
        
*PARMS

{expr} -- expression to be exported

*DESC

{UnparseC} returns a string containing C++ code that attempts to implement the MathPiper expression {expr}. Currently the exporter handles most expression types but not all.

*EXAMPLES
In> UnparseC(Sin('a1) + 2*Cos('b1)) 
Result: "sin(a1) + 2 * cos(b1)"

*SEE UnparseMath2D, UnparseLatex, CUnparsable?

*SOURCE org/mathpiper/scripts4/unparsers/UnparseC.mpws
==========
*CMD UnparseLatex --- export expressions to $LaTeX$
*STD
*CALL
        UnparseLatex(expr)

*PARMS

{expr} -- an expression to be exported

*DESC

{UnparseLatex} returns a string containing a $LaTeX$ representation 
of the MathPiper expression {expr}. Currently the exporter handles 
most expression types but not all.

*EXAMPLES
UnparseLatex(('a1)+2*('b1)) -> "$a1 + 2 \\cdot b1$"

*SEE UnparseMath2D, UnparseC

*SOURCE org/mathpiper/scripts4/unparsers/UnparseLatex.mpws
==========
*CMD UnparseMath2D --- print an expression nicely with ASCII art
*STD
*CALL
        UnparseMath2D(expr)

*PARMS

{expr} -- an expression

*DESC

{UnparseMath2D} renders an expression in a nicer way, using ascii art.
This is generally useful when the result of a calculation is more
complex than a simple number.

*EXAMPLES
In> UnparseMath2D('( 2/x^2 + 3/x^1*y^1 + 4/y^2 )) 
Result: True 
Side Effects: 
2    3     1   4 
-- + -- * y  + -- 
2    1         2 
x    x         y

*SEE UnparserSet

*SOURCE org/mathpiper/scripts4/unparsers/UnparseMath2D.mpws
==========
