# Yacas users function reference

- Startup configuration
- Arithmetic
- Other operations on numbers
- Calculus
- Linear Algebra
- Polynomials
- List operations
- Functional operators
- Control flow functions
- Predicates
- Propositional logic theorem prover
- Constants
- Variables
- Input/Output
- String manipulation
- Programming
- Built-in functions
- The Yacas plugin structure
- Generic objects

DefaultDirectory , PrettyPrinter , Help , HistorySize .

# Startup configuration

Yacas allows you to configure a few things at startup. The file ~/.yacasrc will be executed when Yacas is run. The followinf functions can be useful when used in the ~/.yacasrc file.

###

DefaultDirectory

Internal function

##### Calling Sequence:

DefaultDirectory(path)

##### Parameters:

path - a string containing a full path where yacas script files reside

##### Description:

When loading files, yacas 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).
Yacas first 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 Yacas searches for the initialization scripts and standard scripts.

##### Examples:

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

##### See Also:

Load , Use , DefLoad , FindFile .

###

PrettyPrinter

Standard math library

##### Calling Sequence:

PrettyPrinter(printer)

##### Parameters:

printer - a string containing the name of a function that can pretty-print an expression

##### Description:

PrettyPrinter(printer) sets up the function printer to print out the results on the command line.
This function can be reset to the internal printer with `PrettyPrinter()`

##### Examples:

    In> Taylor(x,0,5)Sin(x)
    Out> x-x^3/6+x^5/120;
    In> PrettyPrinter("PrettyForm");

    True

    Out>
    In> Taylor(x,0,5)Sin(x)

         3    5
        x    x
    x - -- + ---
        6    120

    Out>
    In> PrettyPrinter();
    Out> True;
    In> Taylor(x,0,5)Sin(x)
    Out> x-x^3/6+x^5/120;

##### See Also:

PrettyForm , Write .

###

Help

Standard math library

##### Calling Sequence:

Help()
Help(function)

##### Parameters:

function - a string containing the name of a function to show help for

##### Description:

When help is requested by the user, by typing ?function or ??, the functions Help() (for ??) and Help(function) (for ?function) are called. By default, lynx is used as a browser. The help resides in the subdirectory documentation/ under the directory the math scripts were installed in. So the help files can be found using FindFile.

##### Examples:

To use netscape for browsing help, enter the following commands:

    Help(_f) <-- SystemCall("netscape ":FindFile("documentation/ref.html"):"#":f);
    Help() := SystemCall("netscape ":FindFile("documentation/books.html"));

##### See Also:

SystemCall , FindFile .

###

HistorySize

Internal function

##### Calling Sequence:

HistorySize(n)

##### Parameters:

n - number of lines to store in history file

##### Description:

When exiting, yacas saves the command line history to a file ~/.yacas_history . By default it will only save the last 50 lines, to save space on the harddisk. This can be overridden with this function. Passing -1 tells the system to save all the lines.

##### Examples:

    In> HistorySize(200)
    Out> True;
    In> quit

##### See Also:

+ , - , * , / , ^ .

# Arithmetic

###

Arithmetic operations

Standard math library

##### Calling Sequence:

x+y (precedence 6)
+x
x-y (precedence 5)
-x
x*y (precedence 3)
x/y (precedence 3)
x^y (precedence 2)

##### Parameters:

x and y - some objects for which arithmetic operations are defined.

##### Description:

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
    Out> 5;
    In> 2*3
    Out> 6;

##### See Also:

Div , Mod , Gcd , Lcm , << , >> , FromBase , ToBase , Precision , GetPrecision , N , Rationalize , IsPrime , IsPrimePower , Factors , Factor , PAdicExpand , ContFrac , Decimal , TruncRadian , Floor , Ceil , Round , Pslq .

# Other operations on numbers

###

Div and Mod

Standard math library

##### Calling Sequence:

Div(x,y)
Mod(x,y)

##### Parameters:

x and y - integers

##### Description:

Div performs integer division and Mod returns the remainder after division. Div and Mod are also defined for polynomials.

##### Examples:

    In> Div(5,3)
    Out> 1;
    In> Mod(5,3)
    Out> 2;

##### See Also:

###

Gcd

Standard math library

##### Calling Sequence:

Gcd(n,m)
Gcd(list)

##### Parameters:

n,m - integers or univariate polynomials
list - a list of all integers or all univariate polynomials

##### Description:

Gcd(n,m) returns the greatest common divisor of n and m. The gcd is the largest number that divides n and m. The library code calls MathGcd, which is an internal function. This function implements the binary Euclidean algorithm for determining the greatest common divisor:

    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.
Gcd(list), with list a list of arbitrary length of integers, will return the greatest common divisor of all the integers listed. For lists Gcd uses the identity

    Gcd({a,b,c}) = Gcd(Gcd(a,b),c)

##### Examples:

    In> Gcd(55,10)
    Out> 5;
    In> Gcd({60,24,120})
    Out> 12;

##### See Also:

Lcm .

###

Lcm

Standard math library

##### Calling Sequence:

Lcm(n,m)

##### Parameters:

n,m - integers

##### Description:

Lcm(n,m) : returns the least common multiple of a and b. The least common multiple L of two numbers n,m is the number L=Lcm(n,m) for which there are two integers p,q so such that p*n=q*m=L. This is calculated with the formula:

    Lcm(n,m) = Div(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)
    Out> 120;

##### See Also:

Gcd .

###

<< and >>

Standard math library

##### Calling Sequence:

n<<m and n>>m

##### Parameters:

n,m - integers

##### Description:

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 like multiplication or division by powers of 2.

##### Examples:

    Examples:
    1<<10; should evaluate to 1024
    -1024>>10; should evaluate to -1

###

FromBase and ToBase

Internal function

##### Calling Sequence:

FromBase(base,number)
ToBase(base,number)

##### Parameters:

base - a base to write the numbers in
number - a number to write out in the base representation

##### Description:

Conversion of numbers to and from base 10 numbers.

These functions use the p-adic expansion capabilities of the built-in arbitrary precision math libraries.

##### Examples:

    In> FromBase(2,111111)
    Out> 63;
    In> ToBase(16,255)
    Out> ff;

##### See Also:

###

Precision and GetPrecision

Internal function

##### Calling Sequence:

Precision(n)
GetPrecision()

##### Parameters:

n - required number of digits precision required for following calculations, in base 10.

##### Description:

Precision and GetPrecision can be used to get and set the required number of digits of precision in base 10 in the environment. All subsequent floating point operations will allow for at least n digits after the decimal point.

##### Examples:

    In> Precision(10)
    Out> True;
    In> N(Sin(1))
    Out> 0.8414709848;
    In> Precision(20)
    Out> True;
    In> N(Sin(1))
    Out> 0.84147098480789650665;
    In> GetPrecision()
    Out> 20;

##### See Also:

N .

###

N

Standard math library

##### Calling Sequence:

N(expression)
N(expression,precision)

##### Parameters:

expression - expression to evaluate
precision - precision to use

##### Description:

Normally numeric values are left as-is as long as possible in calculations using division, or trigonometric functions like Sin, Cos, etcetera. N forces Yacas to calculate floating point representations of functions whenever possible, using the current precision or the specified precision.

In addition, the variable Pi is bound to the value of pi up to the required precision.

##### Examples:

    In> 1/2
    Out> 1/2;
    In> N(1/2)
    Out> 0.5;
    In> Sin(1)
    Out> Sin(1);
    In> N(Sin(1),10)
    Out> 0.8414709848;
    In> Pi
    Out> Pi;
    In> N(Pi,20)
    Out> 3.14159265358979323846;

##### See Also:

Precision , GetPrecision .

###

Rationalize

Standard math library

##### Calling Sequence:

Rationalize(expression)

##### Parameters:

expression - expression to rationalize

##### Description:

Rationalize scans the entire expression replacing all floating point values into rational representations p/q for some integers p and q, such that the division of p by q gives the original floating point value up to the number of digits of the original floating point value.

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.

##### Examples:

    In> Sin(1.234)
    Out> Sin(1.234);
    In> Rationalize(%)
    Out> Sin(617/500);

##### See Also:

N , Precision , GetPrecision .

###

IsPrime(n)

IsPrime(n) : returns True if n is prime, False otherwise.

###

IsPrimePower(n)

IsPrimePower(n) : returns True if there is a prime p such that p^m = n.

###

Factor and Factors

Standard math library

##### Calling Sequence:

Factor(x)
Factors(x)

##### Parameters:

x - an integer number or univariate polynomial to factor

##### Description:

Factors decomposes integer numbers or univariate polynomials into a product of primes or irreducible polynomials.

The result of Factors is a list of lists of the form {p,n}, where each p^n divides the original x.

Factor shows the result of Factors in a nicer human readable format.

##### Examples:

    In> Factors(12)
    Out> {{2,2},{3,1}};
    In> PrettyForm(Factor(12))

     2
    2  * 3

##### See Also:

###

PAdicExpand(n,p)

PAdicExpand returns the p-adic expansion of n:

n = a0 +a1*p +a2*p^2+...

So for instance

    In> PrettyForm(PAdicExpand(1234,10))

                       2     3
    4 + 3 * 10 + 2 * 10  + 10

    Out> True;

This function should also work on polynomials.

###

ContFrac

Standard math library

##### Calling Sequence:

ContFrac(x) or ContFrac(x,maxdepth)

##### Parameters:

x - expression to break down
maxdepth - maximum required depth of result

##### Description:

Return the continued fraction expansion of a floating point number, or of a polynomial. 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.

##### Examples:

    In> PrettyForm(ContFrac(N(Pi)))

                     1
    3 + ---------------------------
                       1
        7 + -----------------------
                         1
            15 + ------------------
                           1
                 1 + --------------
                              1
                     292 + --------
                           1 + rest

##### See Also:

###

Decimal

Standard math library

##### Calling Sequence:

Decimal(frac)

##### Parameters:

frac - a rational number

##### Description:

Decimal returns the infinite decimal representation of a number. This function 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.

##### Examples:

    In> Decimal(1/22)
    Out> {0,0,{4,5}};
    In> N(1/22,30)
    Out> 0.045454545454545454545454545454;

###

TruncRadian

Standard math library

##### Calling Sequence:

TruncRadian(r)

##### Parameters:

r - a radian

##### Description:

TruncRadian calculates r mod 2*Pi, returning a value between 0 and 2*Pi. This function is used in the trigonometry functions, just before doing the numerical calculation. It greatly speeds up the calculation if the value passed is a big number.

The library uses the formula

                 /   r    \
    r - MathFloor| ------ | * 2 * Pi
                 \ 2 * Pi /

where r and 2*Pi are calculated with twice the precision used in the environment to make sure there is no rounding error in the significant digits.

##### Examples:

    In> 2*Pi()
    Out> 6.283185307;
    In> TruncRadian(6.28)
    Out> 6.28;
    In> TruncRadian(6.29)
    Out> 0.0068146929;

##### See Also:

Sin , Cos , Tan .

###

Floor

Standard math library

##### Calling Sequence:

Floor(x)

##### Parameters:

x - a number

##### Description:

Floor returns the largest integer smaller than x.

##### Examples:

    In> Floor(1.1)
    Out> 1;
    In> Floor(-1.1)
    Out> -2;

##### See Also:

Ceil , Round .

###

Ceil

Standard math library

##### Calling Sequence:

Ceil(x)

##### Parameters:

x - a number

##### Description:

Ceil returns the smallest integer larger than x.

##### Examples:

    In> Ceil(1.1)
    Out> 2;
    In> Ceil(-1.1)
    Out> -1;

##### See Also:

Floor , Round .

###

Round

Standard math library

##### Calling Sequence:

Round(x)

##### Parameters:

x - a number

##### Description:

Round returns the integer closest to x. 0.5 is rounded down.

##### Examples:

    In> Round(1.49)
    Out> 1;
    In> Round(1.51)
    Out> 2;
    In> Round(-1.49)
    Out> -1;
    In> Round(-1.51)
    Out> -2;

##### See Also:

Floor , Ceil .

###

Pslq

Standard math library

##### Calling Sequence:

Pslq(xlist,precision)

##### Parameters:

xlist - list of floating point numbers
precision - required number of digits precision of calculation

##### Description:

The Pslq is an integer relation detection algorithm. Given a list of constants x find coefficients sol[i] such that `sum(sol[i]*x[i], i=1..n) = 0` (where n=Length(x)). x is the list of real expressions. N(x[i]) must evaluate to floating point numbers.

##### Examples:

    In> Pslq({ 2*Pi+3*Exp(1) , Pi , Exp(1) },20)
    Out> {1,-2,-3};

Note: in this example the system detects correctly that `1* (2*Pi+3*E) -2*(Pi) - 3*(E) = 0`

##### See Also:

Sin , Cos , Tan , ArcSin , ArcCos , ArcTan , Exp , Ln , Sqrt , Abs , Sign , Complex , Re , Im , I , Conjugate , Arg , ! , Bin , Sum , Average , Factorize , Min , Max , IsZero , IsRational , Numer , Denom , Commutator , Taylor , InverseTaylor , ReversePoly , BigOh , Newton , D , Diverge , Curl , Integrate , Simplify , RadSimp , Rationalize , Solve , SuchThat , Eliminate , PSolve , Random , VarList , Limit , TrigSimpCombine , LagrangeInterpolant , Fibonacci .

# Calculus

###

Trigonometric functions

Standard math library

##### Calling Sequence:

Sin(x)
Cos(x)
Tan(x)
ArcSin(x)
ArcCos(x)
ArcTan(x)

##### Parameters:

x - some number

##### Description:

These functions represent the trigonometric functions and their inverses. Yacas leaves them alone even if x is a number, trying to keep the result as exact as possible. The floating point approximations of these functions can be forced by using the N(...) functions.

Yacas knows some trigonometric identities, so it can simplify to exact results even if N is not used. This is the case when the arguments are of the form Pi, Pi/2 etcetera.

##### Examples:

    In> Sin(1)
    Out> Sin(1);
    In> N(Sin(1),20)
    Out> 0.84147098480789650665;
    In> Sin(Pi/4)
    Out> Sqrt(2)/2;

##### See Also:

N , Pi .

###

Exp(x), Ln(x)

Standard math library

##### Calling Sequence:

Exp(x)
Ln(x)

##### Parameters:

x - a number

##### Description:

Calculate e^x, or its inverse, ln(x), respectively.

##### Examples:

    In> Exp(2)
    Out> Exp(2);
    In> Ln(%)
    Out> 2;

###

Sqrt

Standard math library

##### Calling Sequence:

Sqrt(x)

##### Parameters:

x - anumber

##### Description:

Calculate the square root of x.

##### Examples:

    In> Sqrt(16)
    Out> 4;
    In> Sqrt(15)
    Out> Sqrt(15);
    In> N(Sqrt(15))
    Out> 3.8729833462;

###

Abs, Sign

Standard math library

##### Calling Sequence:

Abs(x)
Sign(x)

##### Parameters:

x - a number

##### Description:

Abs(x) returns the absolute value of a number. Abs(x)*Sign(x) should always be equal to x. Sign(x) returns 1 if the number is positive or zero, -1 otherwise.

##### Examples:

    In> Abs(-2)
    Out> 2;
    In> Sign(-2)
    Out> -1;

###

Complex numbers

Standard math library

##### Calling Sequence:

Complex(x,y)
Re(z)
Im(z)
I
Conjugate(expression)
Arg(z)

##### Parameters:

x - a real number
y - a real number
z - a real or complex number
expression - an expression containing complex numbers

##### Description:

Complex(x,y) represents a complex number x+I*y, where I is a pure imaginary number, I = Sqrt(-1). Re(z) returns the real part of a complex number, and Im(z) returns the imaginary part. Conjugate returns the complex conjugate of an expression. It does this by replacing all occurrences of Complex(a,b) in the expression with Complex(a,-b). This operation assumes all unbound variables are real-valued.

Complex(x,y) is the internal representation of a complex number in Yacas.

Arg returns the angle a for which the complex number is amp*(Cos(angle) + I*Sin(angle)). As such it returns an angle from -Pi to +Pi.

##### Examples:

    In> z := 2+3*I
    Out> Complex(2,3);
    In> Re(z)
    Out> 2;
    In> Im(z)
    Out> 3;
    In> Arg(Exp(I*Pi/3))
    Out> Pi/3;

###

Factorial and binomial numbers

Standard math library

##### Calling Sequence:

n!, Bin(n,m)

##### Parameters:

n - a positive integer
m - a positive integer

##### Description:

n! evaluates to n*(n-1)*(n-2)*....*1. Bin(n,m) evaluates to n!/(n!*(n-m)!).

##### Examples:

    In> 10!
    Out> 3628800;
    In> Bin(10,4)
    Out> 210;
    In> (10!)/((6!)*(4!))
    Out> 210;
    In> (3/2)!
    Out> (3*Sqrt(Pi))/4;

###

Sums and products.

Standard math library

##### Calling Sequence:

Sum(var,from,to,body)
Sum(list)
Average(list)
Factorize(var,from,to,body)
Factorize(list)

##### Parameters:

var - a variable to iterate over
from - integer value to iterate from
to - integer value to iterate upto
body - expression to evaluate for each iteration
list - list of values to iterate over

##### Description:

Sum returns the sum of a list of values. Factorize returns the product of a list of values. Average returns the average of a list of values.

Iteration can either proceed over the elements of a list passed in, or by evaluating 'body' by iterating variable 'var' from value 'from' upto 'to'. 'to' should be greater than or equal to from.

##### Examples:

    In> Sum(i,1,3,i)
    Out> 6;
    In> Sum({1,2,3})
    Out> 6;
    In> Sum(1 .. 3)
    Out> 6;
    In> Average(1 .. 3)
    Out> 2;
    In> Factorize(i,1,3,i)
    Out> 6;
    In> Factorize({1,2,3})
    Out> 6;
    In> Factorize(1 .. 3)
    Out> 6;

##### See Also:

Max , Min .

###

Minimum and maximum values

Standard math library

##### Calling Sequence:

Min(x,y)
Min(list)
Max(x,y)
Max(list)

##### Parameters:

x - a number
y - a number
list - a list of numbers

##### Description:

Min and Max return the minimum and maximum value of their arguments respectively. Min and max can either be called with two numbers as arguments, or with a list of numbers.

##### Examples:

    In> Min(2,3)
    Out> 2;
    In> Max(2,3)
    Out> 3;
    In> Min(5 .. 15)
    Out> 5;
    In> Max(5 .. 15)
    Out> 15;

##### See Also:

Sum , Average .

###

IsZero(x)

IsZero(x) : Returns wether x is zero or not.

###

Rational numbers

Standard math library

##### Calling Sequence:

IsRational(r)
Numer(r)
Denom(r)

##### Parameters:

r - a rational number or expression

##### Description:

Rational numbers are anything like a/b, or 2/5. IsRational returns True if the argument is a rational expression, and False otherwise. Numer and Denom return the numerator and denominator of a rational expression, respectively.

##### Examples:

    In> IsRational(a)
    Out> False;
    In> IsRational(a/b)
    Out> True;
    In> Numer(a/b)
    Out> a;
    In> Denom(a/b)
    Out> b;

###

Commutator

Internal function
Standard math library

##### Calling Sequence:

Commutator(a,b)

##### Parameters:

a - a mathematical object
b - a mathematical object

##### Description:

Return "a b - b a". For numbers and such this is zero, for matrices in general it isn't.

##### Examples:

    In> Commutator(2,3)
    Out> 0;
    In> m1:=Identity(3)
    Out> {{1,0,0},{0,1,0},{0,0,1}};
    In> m1[1][2] := a
    Out> True;
    In> m2:=Identity(3)
    Out> {{1,0,0},{0,1,0},{0,0,1}};
    In> m2[2][2] := a
    Out> True;
    In> Commutator(m1,m2)
    Out> {{0,a^2-a,0},{0,0,0},{0,0,0}};

###

Taylor

Standard math library

##### Calling Sequence:

Taylor(var,at,order)expression

##### Parameters:

var - variable
at - point to get taylor series around
order - order of approximation
expression - expression to get taylor series for

##### Description:

Return the Taylor series expansion of function "expression", with respect to variable "var", around "var=at", upto order "order".

##### Examples:

    In> Taylor(x,0,9)Sin(x)

         3    5      7       9
        x    x      x       x
    x - -- + --- - ---- + ------
        6    120   5040   362880

    Out>

##### See Also:

InverseTaylor , ReversePoly , BigOh .

###

InverseTaylor

Standard math library

##### Calling Sequence:

InverseTaylor(var,at,degree) expression

##### Parameters:

var - variable
at - point to get inverse taylor series around
order - order of approximation
expression - expression to get inverse taylor series for

##### Description:

InverseTaylor builds a taylor series expansion of the inverse of function func, with respect to variable var around value, upto degree. InverseTaylor uses the function ReversePoly to perform the task.

##### Examples:

    In> exp1 := Taylor(x,0,7)Sin(x)

         3    5      7
        x    x      x
    x - -- + --- - ----
        6    120   5040

    Out>
    In> exp2 := InverseTaylor(x,0,8)ArcSin(x)

     5      7     3
    x      x     x
    --- - ---- - -- + x
    120   5040   6

    Out>
    In> Simplify(exp1-exp2)

    0

    Out>

##### See Also:

ReversePoly , Taylor , BigOh .

###

ReversePoly

Standard math library

##### Calling Sequence:

ReversePoly(f,g,var,newvar,degree)

##### Parameters:

f - a function of one free variable 'var'
g - a function of one free variable 'var'
var - a variable
newvar - a new variable to express the result in
degree - The degree of the required solution

##### Description:

Given polynomials f(var) and g(var), determine a polynomial h(newvar) for which h(f(var)) = g(var). The resulting polynomial will be of degree degree. The only requirement is that the first derivative of f should not be zero.

This function is used to determine the taylor series expansion of a function: if g(var)=var, then h(f(var))=var, so h will be the inverse of f.

##### Examples:

    In> f(x):=Eval(Expand((1+x)^4))
    Out> True;
    In> g(x) := x^2
    Out> True;
    In> h(y):=Eval(ReversePoly(f(x),g(x),x,y,8))
    Out> True;
    In> BigOh(h(f(x)),x,8)
    Out> x^2;
    In> h(x)
    Out> (-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 Also:

InverseTaylor , Taylor , BigOh .

###

BigOh

Standard math library

##### Calling Sequence:

BigOh(poly,var,degree)

##### Parameters:

poly - a univariate polynomial
var - a free variable
degree - positive integer

##### Description:

BigOh drops all terms of order degree or higher in a given polynomial poly in variable var. .

##### Examples:

    In> BigOh(1+x+x^2+x^3,x,2)
    Out> x+1;

##### See Also:

Taylor , InverseTaylor .

###

Newton

Standard math library

##### Calling Sequence:

Newton(expression,variable,initial,accuracy)

##### Parameters:

expression - an expression to find a zero for
variable - free variable to adjust to find a zero
initial - initial value to use in the search
accuracy - minimum required accuracy of the result

##### Description:

Find a zero of "expression", as a function of "variable", starting around value "initial", and continuing until the value for "variable" is maximally "accuracy" away from the correct value.

##### Examples:

    In> Newton(Sin(x),x,3,0.0001)
    Out> 3.1415926535;

###

Derivatives

Standard math library

##### Calling Sequence:

D(var)expression
D(list)expression
D(var,n)expression

##### Parameters:

var - variable
list - a list of variables
expression - expression to take derivative of
n - order of derivative

##### Description:

Calculate analytic derivative of an expression. The D operator is threaded. Alternatively, D can be invoked with "D(variable,n)expression". In that case the n-th derivative will be taken.

##### Examples:

    In> D(x)Sin(x*y)
    Out> y*Cos(x*y);
    In> D({x,y,z})Sin(x*y)
    Out> {y*Cos(x*y),x*Cos(x*y),0};
    In> D(x,2)Sin(x*y)
    Out> -Sin(x*y)*y^2;
    In> D(x){Sin(x),Cos(x)}
    Out> {Cos(x),-Sin(x)};

##### See Also:

Integrate , Taylor .

###

Diverge and Curl

Standard math library

##### Calling Sequence:

Diverge(vector, basis)
Curl(vector, basis)

##### Parameters:

vector - a vector
basis - a list of variables

##### Description:

Diverge(vector, basis) will calculate the divergence of a vector. Curl(vector, basis) calculate the curl of a vector.

##### Examples:

    In> Diverge({x*y,x*y,x*y},{x,y,z})
    Out> {y,x,0};
    In> Curl({x*y,x*y,x*y},{x,y,z})
    Out> {x,-y,y-x};

##### See Also:

D .

###

Integrate

Standard math library

##### Calling Sequence:

Integrate(var,from,to) expression
Integrate(var) expression

##### Parameters:

var - variable to integrate over
from - value to integrate from
to - value to integrate upto
expression - expression to integrate over

##### Description:

Integrate an expression over variable var=from to var=to. Some simple integration rules have currently been implemented. Transcendental functions, polynomials, products of transcendental functions and polynomials, and rational functions.

##### Examples:

    In> Integrate(x,a,b)Cos(x)
    Out> Sin(b)-Sin(a);
    In> Integrate(x)Cos(x)
    Out> Sin(x)+C9;

##### See Also:

D .

###

Simplify

Internal function
Standard math library

##### Calling Sequence:

Simplify(expression)

##### Parameters:

expression - an expression

##### Description:

Simplify tries to simplify an expression as much as possible. It does this by grouping powers within terms, and then grouping like terms.

##### Examples:

    In> a*b*a^2/b-a^3
    Out> (b*a^3)/b-a^3;
    In> Simplify(a*b*a^2/b-a^3)
    Out> 0;

##### See Also:

TrigSimpCombine , RadSimp .

###

RadSimp

Standard math library

##### Calling Sequence:

RadSimp(expression)

##### Parameters:

expression - an expression containing nested radicals

##### Description:

RadSimp tries to unnest nested radicals. It does this using a simple brute force method, and tries to write it out as an expression of the form Sqrt(e1) + Sqrt(e2) + ... .

##### Examples:

    In> RadSimp(Sqrt(9+4*Sqrt(2)))
    Out> 1+Sqrt(8);
    In> RadSimp(Sqrt(5+2*Sqrt(6))+Sqrt(5-2*Sqrt(6)))
    Out> Sqrt(12);
    In> RadSimp(Sqrt(14+3*Sqrt(3+2*Sqrt(5-12*Sqrt(3-2*Sqrt(2))))))
    Out> 3+Sqrt(2);

##### See Also:

Simplify .

###

Rationalize

Standard math library

##### Calling Sequence:

Rationalize(expression)

##### Parameters:

expression - an expression containing real numbers

##### Description:

Convert every real number in 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).

##### Examples:

    In> {1.2,3.123,4.5}
    Out> {1.2,3.123,4.5};
    In> Rationalize(%)
    Out> {6/5,3123/1000,9/2};

###

Solve

Internal function
Standard math library

##### Calling Sequence:

Solve(eq,var)
Solve(eqlist,varlist)

##### Parameters:

eq - single identity equation
var - single variable
eqlist - list of identity equations
varlist - list of variables

##### Description:

Solve tries to solve (a set of) equations for (a set of) variables. Pass the equations in a list, as well as the variables to be solved for. The solver will then use SuchThat, in combination with Eliminate, to simplify the equations. This suffices for all linear equations and a large group of simple non-linear equations. When the variable argument receives a list of variables to solve for, Solve returns a list of results, with each result being a solution to the set of equations.

##### Examples:

    In> Solve(a+x*y==z,x)
    Out> (z-a)/y;
    In> Solve({a*x+y==0,x+z==0},{x,y})
    Out> {{-z,z*a}};

##### See Also:

SuchThat , Subst , Eliminate .

###

SuchThat

Standard math library

##### Calling Sequence:

SuchThat(expression,variable)

##### Parameters:

expression - an expression to solve for
variable - subexpression to look for

##### Description:

SuchThat(expression,var) : try to find a simple expression for variable var, given the equality expression=0. This function basically only handles expressions where the variable only occurs once. It does its work by applying the inverse of the top function, until the variable is reached. Variable can also refer to an expression, in which case it will try to eliminate for that expression.

##### Examples:

    In> SuchThat(a+b*x,x)
    Out> (-a)/b;
    In> SuchThat(Cos(a)+Cos(b)^2,Cos(b))
    Out> (-Cos(a))^(1/2);
    In> Expand(a*x+b*x+c,x)
    Out> c+(a+b)*x;
    In> SuchThat(%,x)
    Out> (-c)/(a+b);

##### See Also:

Solve , Subst , Simplify .

###

Eliminate

Standard math library

##### Calling Sequence:

Eliminate(original,replace,expression)

##### Parameters:

original - expression
replace - expression
expression - expression

##### Description:

Replace all instances of `original` in `expression` with `replace` and call Simplify on the resulting expression.

##### Examples:

    In> Subst(Cos(b),c)(Sin(a)+Cos(b)^2/c)

                2
               c
    Sin( a ) + --
               c

    Out>
    In> Eliminate(Cos(b),c,Sin(a)+Cos(b)^2/c)

    Sin( a ) + c

    Out>

##### See Also:

SuchThat , Subst .

###

PSolve

Standard math library

##### Calling Sequence:

PSolve(expr,var)

##### Parameters:

expr - an expression
var - a variable

##### Description:

solve expr=0 with respect to variable var, treating it expr as a polynomial. It currently solves upto degree 3.

##### Examples:

    In> PSolve(b*x+a,x)
    Out> -a/b;
    In> PSolve(c*x^2+b*x+a,x)
    Out> {(Sqrt(b^2-4*c*a)-b)/(2*c),(-(b+Sqrt(b^2-4*c*a)))/(2*c)};

##### See Also:

Solve , Factor .

###

Pi

Internal function

##### Calling Sequence:

Pi()

##### Description:

Returns pi to the current precision. Usually this function will not be called directly. The constant 'Pi' can (and should) be used to represent pi, so simplification rules can do work. Then when the function N is invoked Pi will be replaced with the value returned by Pi().

##### Examples:

    In> Pi()
    Out> 3.14159265358979323846;
    In> Precision(40)
    Out> True;
    In> Pi()
    Out> 3.1415926535897932384626433832795028841971;

##### See Also:

N , Pi .

###

Random

Standard math library

##### Calling Sequence:

Random()

##### Description:

Returns a random number between 0 and 1.

###

VarList

Standard math library

##### Calling Sequence:

VarList(expression)

##### Parameters:

expression - an expression

##### Description:

Returns a list with all the variables "expression" depends on.

##### Examples:

    In> VarList(Sin(x))
    Out> {x};
    In> VarList(x+a*y)
    Out> {x,a,y};

##### See Also:

IsFreeOf .

###

Limit

Standard math library

##### Calling Sequence:

Limit(variable,value) expression
Limit(variable,value,direction) expression

##### Parameters:

variable - a variable
value - a number
direction - a direction (Left or Right)
expression - an expression

##### Description:

Determine the value "expression" converges to when "variable" goes to "value".

You can also specify a direction for the limit, Left or Right. Specifying Right will take the limit from positive Infinity, and Left will take the limit from -Infinity.

##### Examples:

    In> Limit(x,0) Sin(x)/x
    Out> 1;
    In> Limit(x,0) (Sin(x)-Tan(x))/(x^3)
    Out> -1/2;
    In> Limit(x,0)1/x
    Out> Undefined;
    In> Limit(x,0,Left)1/x
    Out> -Infinity;
    In> Limit(x,0,Right)1/x
    Out> Infinity;

###

TrigSimpCombine

Standard math library

##### Calling Sequence:

TrigSimpCombine(expression)

##### Parameters:

expression - an expression

##### Description:

This is the module that does the trigonometric simplification: Cos(...)*Sin(...) -> Cos(...)+Sin(...)

It also tries to simplify the resulting expression as much as possible, trying to combine all like terms.

This function is used in for instance Integrate, to bring down the expression into a simpler form that can be integrated easily.

##### Examples:

    In> TrigSimpCombine(Cos(a)^2+Sin(a)^2)

    1

    Out>
    In> TrigSimpCombine(Cos(a)^2-Sin(a)^2)

    Cos( 2 * a )

    Out>
    In> TrigSimpCombine(Cos(a)^2*Sin(b))

    Sin( b )   Sin( -2 * a + b )   Sin( -2 * a - b )
    -------- + ----------------- - -----------------
       2               4                   4

    Out>

##### See Also:

Simplify , Integrate .

###

LagrangeInterpolant

Standard math library

##### Calling Sequence:

LagrangeInterpolant(xlist,ylist,var)

##### Parameters:

xlist - list of values
ylist - list f values
var - free variable for resulting polynomial

##### Description:

Given a set of points (x_i,y_i) with all nonzero y_i, find the polynomial that goes through these points. The first argument passed to the function should be the list of x_i values, the second one should be the list of y_i values, and the third argument should be the variable used to build up the polynomial.

This routine uses the Lagrange interpolant formula to build up the polynomial.

##### Examples:

    In> LagrangeInterpolant({x1,x2,x3},{y1,y2,y3},x)

    y1 * ( x - x2 ) * ( x - x3 )   y2 * ( x - x1 ) * ( x - x3 )
    ---------------------------- + ----------------------------
     ( x1 - x2 ) * ( x1 - x3 )      ( x2 - x1 ) * ( x2 - x3 )

      y3 * ( x - x1 ) * ( x - x2 )
    + ----------------------------
       ( x3 - x1 ) * ( x3 - x2 )

    Out>

###

Fibonacci

Standard math library

##### Calling Sequence:

Fibonacci(n)

##### Parameters:

n - an integer

##### Description:

Calculate Fibonacci number "n".

##### Examples:

    In> Fibonacci(4)
    Out> 3;
    In> Fibonacci(8)
    Out> 21;

LeviCivita , Permutations , InProduct , CrossProduct , ZeroVector , BaseVector , Identity , ZeroMatrix , DiagonalMatrix , IsMatrix , Normalize , Transpose , Determinant , Trace , Inverse , Minor , CoFactor , SolveMatrix , CharacteristicEquation , EigenValues , EigenVectors , IsHermitean , IsUnitary .

# Linear Algebra

This chapter describes the commands for doing linear algebra. They can be used to manipulate vectors, represented as lists, and matrices, represented as lists of lists.

###

LeviCivita -- The totally anti-symmetric Levi Civita tensor

Standard math library

##### Calling Sequence:

LeviCivita(list)

##### Parameters:

list - a list of integers 1 .. n in some order

##### Description:

"LeviCivita" implements the Levi Civita symbol. This is generally useful for tensor calculus. {list} should be a list of integers, and this function returns 1 if the integers are in successive order, eg. {1,2,3,...} would return 1. Swapping two elements of this list would return -1. So, LeviCivita( {2,1,3} ) would evaluate to -1.

##### Examples:

    In> LeviCivita({1,2,3})
    Out> 1;
    In> LeviCivita({2,1,3})
    Out> -1;
    In> LeviCivita({2,2,3})
    Out> 0;

##### See Also:

Permutations .

###

Permutations -- Form all permutations of a list

Standard math library

##### Calling Sequence:

Permutations(list)

##### Parameters:

list - a list of elements

##### Description:

Permutations returns a list with all the permutations of the original list.

##### Examples:

    In> Permutations({a,b,c})
    Out> {{a,b,c},{a,c,b},{c,a,b},{b,a,c},{b,c,a},{c,b,a}};

##### See Also:

LeviCivita .

###

InProduct -- Inner product of vectors

Standard math library

##### Calling Sequence:

InProduct(a,b)
a . b (prec. 3)

##### Parameters:

a, b - vectors of equal length

##### Description:

The inner product of the two vectors "a" and "b" is returned. The vectors need to have the same size.

##### Examples:

    In> {a,b,c} . {d,e,f};
    Out> a*d+b*e+c*f;

##### See Also:

CrossProduct .

###

CrossProduct -- Outer product of vectors

Standard math library

##### Calling Sequence:

CrossProduct(a,b)
a X b (prec. 3)

##### Parameters:

a, b - three-dimensional vectors

##### Description:

The outer product (also called 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.

##### Examples:

    In> {a,b,c} X {d,e,f};
    Out> {b*f-c*e,c*d-a*f,a*e-b*d};

##### See Also:

InProduct .

###

ZeroVector -- Create a vector with all zeroes

Standard math library

##### Calling Sequence:

ZeroVector(n)

##### Parameters:

n - length of the vector to return

##### Description:

This command returns a vector of length "n", filled with zeroes.

##### Examples:

    In> ZeroVector(4)
    Out> {0,0,0,0};

##### See Also:

BaseVector , ZeroMatrix , IsZeroVector .

###

BaseVector -- Base vector

Standard math library

##### Calling Sequence:

BaseVector(k, n)

##### Parameters:

k - index of the base vector to construct
n - dimension of the vector

##### Description:

This command returns the "k"-th base vector of dimension "n". This is a vector of length "n" with all zeroes except for the "k"-th entry, which contains a 1.

##### Examples:

    In> BaseVector(2,4)
    Out> {0,1,0,0};

##### See Also:

ZeroVector , Identity .

###

Identity -- Identity matrix

Standard math library

##### Calling Sequence:

Identity(n)

##### Parameters:

n - size of the matrix

##### Description:

This commands returns the identity matrix of size "n" by "n". This matrix has ones on the diagonal while the other entries are zero.

##### Examples:

    In> Identity(3)
    Out> {{1,0,0},{0,1,0},{0,0,1}};

##### See Also:

BaseVector , ZeroMatrix , DiagonalMatrix .

###

ZeroMatrix -- Matrix filled with zeroes

Standard math library

##### Calling Sequence:

ZeroMatrix(n, m)

##### Parameters:

n - number of rows
m - number of columns

##### Description:

This command returns a matrix with "n" rows and "m" columns, completely filled with zeroes.

##### Examples:

    In> ZeroMatrix(3,4)
    Out> {{0,0,0,0},{0,0,0,0},{0,0,0,0}};

##### See Also:

ZeroVector , Identity .

###

DiagonalMatrix -- Construct a diagonal matrix

Standard math library

##### Calling Sequence:

DiagonalMatrix(d)

##### Parameters:

d - list of values to put on the diagonal

##### Description:

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.

##### Examples:

    In> DiagonalMatrix(1 .. 4)
    Out> {{1,0,0,0},{0,2,0,0},{0,0,3,0},{0,0,0,4}};

##### See Also:

Identity , ZeroMatrix .

###

IsMatrix -- Test whether argument is a matrix

Standard math library

##### Calling Sequence:

IsMatrix(M)

##### Parameters:

M - a mathematical object

##### Description:

IsMatrix returns True if M is a matrix, False otherwise. Something is considered to be a matrix if it is a list and all the entries of this list are lists themselves.

##### Examples:

    In> IsMatrix(ZeroMatrix(3,4))
    Out> True;
    In> IsMatrix(ZeroVector(4))
    Out> False;
    In> IsMatrix(3)
    Out> False;

##### See Also:

IsVector .

###

Normalize -- Normalize a vector

Standard math library

##### Calling Sequence:

Normalize(v)

##### Parameters:

v - a vector

##### Description:

Return the normalized vector of v: a vector going in the same direction but with length 1.

##### Examples:

    In> Normalize({3,4})
    Out> {3/5,4/5};
    In> % . %
    Out> 1;

##### See Also:

InProduct , CrossProduct .

###

Transpose -- Transpose of a matrix

Standard math library

##### Calling Sequence:

Transpose(M)

##### Parameters:

M - a matrix

##### Description:

Transpose returns the transpose of a matrix M. Because matrices are just lists of lists, this is a useful operation too for lists.

##### Examples:

    In> Transpose({{a,b}})
    Out> {{a},{b}};

###

Determinant -- Determinant of a matrix

Standard math library

##### Calling Sequence:

Determinant(M)

##### Parameters:

M - a matrix

##### Description:

Returns the determinant of a matrix M.

##### Examples:

    In> DiagonalMatrix(1 .. 4)
    Out> {{1,0,0,0},{0,2,0,0},{0,0,3,0},{0,0,0,4}};
    In> Determinant(%)
    Out> 24;

###

Trace -- Trace of a matrix

Standard math library

##### Calling Sequence:

Trace(M)

##### Parameters:

M - a matrix

##### Description:

Trace returns the trace of a matrix M (defined as the sum of the elements on the diagonal of the matrix).

##### Examples:

    In> DiagonalMatrix(1 .. 4)
    Out> {{1,0,0,0},{0,2,0,0},{0,0,3,0},{0,0,0,4}};
    In> Trace(%)
    Out> 10;

###

Inverse -- Inverse of a matrix

Standard math library

##### Calling Sequence:

Inverse(M)

##### Parameters:

M - a matrix

##### Description:

Inverse returns the inverse of matrix M. The determinant of M should be non-zero. Because this function uses Determinant for calculating the inverse of a matrix, you can supply matrices with non-numeric matrix elements.

##### Examples:

    In> DiagonalMatrix({a,b,c})
    Out> {{a,0,0},{0,b,0},{0,0,c}};
    In> Inverse(%)
    Out> {{(b*c)/(a*b*c),0,0},{0,(a*c)/(a*b*c),0},{0,0,(a*b)/(a*b*c)}};
    In> Simplify(%)
    Out> {{1/a,0,0},{0,1/b,0},{0,0,1/c}};

###

Minor -- Principal minor of a matrix

Standard math library

##### Calling Sequence:

Minor(M,i,j)

##### Parameters:

M - a matrix
i, j - positive integers

##### Description:

Minor returns the minor of a matrix around the element (i,j). The minor is the determinant of the matrix excluding the "i"-th row and "j"-th column.

##### Examples:

    In> A := {{1,2,3}, {4,5,6}, {7,8,9}};
    Out> {{1,2,3},{4,5,6},{7,8,9}};
    In> PrettyForm(A);

    /                    \
    | ( 1 ) ( 2 ) ( 3 )  |
    |                    |
    | ( 4 ) ( 5 ) ( 6 )  |
    |                    |
    | ( 7 ) ( 8 ) ( 9 )  |
    \                    /

    Out> True;
    In> Minor(A,1,2);
    Out> -6;
    In> Determinant({{2,3}, {8,9}});
    Out> -6;

##### See Also:

CoFactor , Determinant , Inverse .

###

CoFactor -- Cofactor of a matrix

Standard math library

##### Calling Sequence:

CoFactor(M,i,j)

##### Parameters:

M - a matrix
i, j - positive integers

##### Description:

CoFactor returns the cofactor of a matrix around the element (i,j). The cofactor is the minor times (-1)^(i+j)

##### Examples:

    In> A := {{1,2,3}, {4,5,6}, {7,8,9}};
    Out> {{1,2,3},{4,5,6},{7,8,9}};
    In> PrettyForm(A);

    /                    \
    | ( 1 ) ( 2 ) ( 3 )  |
    |                    |
    | ( 4 ) ( 5 ) ( 6 )  |
    |                    |
    | ( 7 ) ( 8 ) ( 9 )  |
    \                    /

    Out> True;
    In> CoFactor(A,1,2);
    Out> 6;
    In> Minor(A,1,2);
    Out> -6;
    In> Minor(A,1,2) * (-1)^(1+2);
    Out> 6;

##### See Also:

Minor , Determinant , Inverse .

###

SolveMatrix -- Solve a linear system

Standard math library

##### Calling Sequence:

SolveMatrix(M,v)

##### Parameters:

M - a matrix
v - a vector

##### Description:

SolveMatrix returns the vector x that satisfies the equation "M x = v". The determinant of M should be non-zero.

##### Examples:

    In> A := {{1,2}, {3,4}};
    Out> {{1,2},{3,4}};
    In> v := {5,6};
    Out> {5,6};
    In> x := SolveMatrix(A, v);
    Out> {-4,9/2};
    In> A * x;
    Out> {5,6};

##### See Also:

Inverse , Solve , PSolve .

###

CharacteristicEquation -- Characteristic polynomial of a matrix

Standard math library

##### Calling Sequence:

CharacteristicEquation(matrix,var)

##### Parameters:

matrix - a matrix
var - a free variable

##### Description:

CharacteristicEquation returns the characteristic equation of "matrix", using "var". The zeros of this equation are the eigenvalues of the matrix, Det(matrix-I*var);

##### Examples:

    In> DiagonalMatrix({a,b,c})
    Out> {{a,0,0},{0,b,0},{0,0,c}};
    In> CharacteristicEquation(%,x)
    Out> (a-x)*(b-x)*(c-x);
    In> Expand(%,x)
    Out> (b+a+c)*x^2-x^3-((b+a)*c+a*b)*x+a*b*c;

##### See Also:

EigenValues , EigenVectors .

###

EigenValues -- Eigenvalues of a matrix

Standard math library

##### Calling Sequence:

EigenValues(matrix)

##### Parameters:

matrix - a square matrix

##### Description:

EigenValues returns the eigenvalues of a matrix. The eigenvalues x of a matrix M are the numbers such that M*v=x*v for some vector.
It first determines the characteristic equation, and then factorizes this equation, returning the roots of the characteristic equation det(matrix-x*identity).

##### Examples:

    In> M:={{1,2},{2,1}}
    Out> {{1,2},{2,1}};
    In> EigenValues(M)
    Out> {3,-1};

##### See Also:

EigenVectors , CharacteristicEquation .

###

EigenVectors -- Eigenvectors of a matrix

Standard math library

##### Calling Sequence:

EigenVectors(matrix,eigenvalues) Standard math library

##### Parameters:

matrix - a square matrix
eigenvalues - list of eigenvalues as returned by EigenValues

##### Description:

EigenVectors returns a list of the eigenvectors of a matrix. It uses the eigenvalues and the matrix to set up n equations with n unknowns for each eigenvalue, and then calls Solve to determine the values of each vector.

##### Examples:

    In> M:={{1,2},{2,1}}
    Out> {{1,2},{2,1}};
    In> e:=EigenValues(M)
    Out> {3,-1};
    In> EigenVectors(M,e)
    Out> {{-ki2/ -1,ki2},{-ki2,ki2}};

##### See Also:

EigenValues , CharacteristicEquation .

###

IsHermitean -- Test whether a matrix is Hermitean

Standard math library

##### Calling Sequence:

IsHermitean(A)

##### Parameters:

A - square matrix

##### Description:

IsHermitean(A) returns True if A is Hermitean and False otherwise. A is a Hermitean matrix iff Conjugate(Transpose(A))=A. For real matrices A is tested to be symmetric.

##### Examples:

    In> IsHermitean({{0,I},{-I,0}})
    Out> True;
    In> IsHermitean({{0,I},{2,0}})
    Out> False;

##### See Also:

IsUnitary .

###

IsUnitary -- Test whether a matrix is unitary

Standard math library

##### Calling Sequence:

IsUnitary(A)

##### Parameters:

A - square matrix

##### Description:

This function tries to find out if A is unitary. Matrix A is orthogonal iff A^(-1) = Transpose(Conjugate(A)). This is equivalent to the fact that the columns of A build an orthonormal system (in respect to the scalar product defined by InProduct).

##### Examples:

    In> IsUnitary({{0,I},{-I,0}})
    Out> True;
    In> IsUnitary({{0,I},{2,0}})
    Out> False;

##### See Also:

IsHermitean .

Expand , Degree , Coef , Content , PrimitivePart , LeadingCoef , Monic , RandomPoly , Horner , ExpandBrackets .

# Polynomials

This chapter contains commands to manipulate polynomials.

###

Expand -- Put polynomial in expanded form

Standard math library

##### Calling Sequence:

Expand(expr)
Expand(expr, var)
Expand(expr, varlist)

##### Parameters:

expr - a polynomial expression
var - a variable
varlist - a list of variables

##### Description:

This command brings a polynomial in expanded form, in which polynomials are represented in the form c0 + c1*x + c2*x^2 + ... + cn*x^n. In this form, it is easier to test whether a polynomial is zero, namely by testing whether all coefficients are zero.

If the polynomial "expr" contains only one variable, the first calling sequence can be used. Otherwise, the second form should be used which explicitly mentions that "expr" should be considered as a polynomial in the variable "var". The third calling form can be used for multivariate polynomials. Firstly, the polynomial "expr" is expanded with respect to the first variable in "varlist". Then the coefficients are all expanded with respect to the second variable, and so on.

##### Examples:

    In> PrettyPrinter("PrettyForm");

    True

    Out>
    In> Expand((1+x)^5);

     5        4         3         2
    x  + 5 * x  + 10 * x  + 10 * x  + 5 * x + 1

    Out>
    In> Expand((1+x-y)^2, x);

     2                                2
    x  + 2 * ( 1 - y ) * x + ( 1 - y )

    Out>
    In> Expand((1+x-y)^2, {x,y});

     2                         2
    x  + ( -2 * y + 2 ) * x + y  - 2 * y + 1

    Out>

##### See Also:

ExpandBrackets .

###

Degree -- Degree of a polynomial

Standard math library

##### Calling Sequence:

Degree(expr)
Degree(expr, var)

##### Parameters:

expr - a polynomial
var - a variable occurring in "expr"

##### Description:

This command returns the degree of the polynomial "expr" with respect to the variable "var". The degree is the highest power of "var" occurring in the polynomial. If only one variable occurs in "expr", the first calling sequence can be used. Otherwise the user should use the second form in which the variable is explicitly mentioned.

##### Examples:

    In> Degree(x^5+x-1);
    Out> 5;
    In> Degree(a+b*x^3, a);
    Out> 1;
    In> Degree(a+b*x^3, x);
    Out> 3;

##### See Also:

Expand , Coef .

###

Coef -- Coefficient of a polynomial

Standard math library

##### Calling Sequence:

Coef(expr, var, order)

##### Parameters:

expr - a polynomial
var - a variable occurring in "expr"
order - integer or list of integers

##### Description:

This command returns the coefficient of "var" to the power "order" in the polynomial "expr". The parameter "order" can also be a list of integers, in which case this function returns a list of coefficients.

##### Examples:

    In> e := Expand((a+x)^4,x)
    Out> x^4+4*a*x^3+(a^2+(2*a)^2+a^2)*x^2+(a^2*2*a+2*a^3)*x+a^4;
    In> Coef(e,a,2)
    Out> 6*x^2;
    In> Coef(e,a,0 .. 4)
    Out> {x^4,4*x^3,6*x^2,4*x,1};

##### See Also:

Expand , Degree , LeadingCoef .

###

Content -- Content of a univariate polynomial

Standard math library

##### Calling Sequence:

Content(expr)

##### Parameters:

expr - univariate polynomial

##### Description:

This command determines the content of a univariate polynomial. The content is the greatest common divisor of all the terms in the polynomial. Every polynomial can be written as the product of the content with the primitive part.

##### Examples:

    In> poly := 2*x^2 + 4*x;
    Out> 2*x^2+4*x;
    In> c := Content(poly);
    Out> 2*x;
    In> pp := PrimitivePart(poly);
    Out> x+2;
    In> Expand(pp*c);
    Out> 2*x^2+4*x;

##### See Also:

PrimitivePart , Gcd .

###

PrimitivePart -- Primitive part of a univariate polynomial

Standard math library

##### Calling Sequence:

PrimitivePart(expr)

##### Parameters:

expr - univariate polynomial

##### Description:

This command determines the primitive part of a univariate polynomial. The primitive part is what remains after the content (the greatest common divisor of all the terms) is divided out. So the product of the content and the primitive part equals the original polynomial.

##### Examples:

    In> poly := 2*x^2 + 4*x;
    Out> 2*x^2+4*x;
    In> c := Content(poly);
    Out> 2*x;
    In> pp := PrimitivePart(poly);
    Out> x+2;
    In> Expand(pp*c);
    Out> 2*x^2+4*x;

##### See Also:

Content .

###

LeadingCoef -- Leading coefficient of a polynomial

Standard math library

##### Calling Sequence:

LeadingCoef(poly)
LeadingCoef(poly, var)

##### Parameters:

poly - a polynomial
var - a variable

##### Description:

This function returns the leading coefficient of "poly", regarded as a polynomial in the variable "var". The leading coefficient is the coefficient of the term of highest degree. If only one variable appears in the expression "poly", it is obvious that it should be regarded as a polynomial in this variable and the first calling sequence may be used.

##### Examples:

    In> poly := 2*x^2 + 4*x;
    Out> 2*x^2+4*x;
    In> lc := LeadingCoef(poly);
    Out> 2;
    In> m := Monic(poly);
    Out> x^2+2*x;
    In> Expand(lc*m);
    Out> 2*x^2+4*x;

    In> LeadingCoef(2*a^2 + 3*a*b^2 + 5, a);
    Out> 2;
    In> LeadingCoef(2*a^2 + 3*a*b^2 + 5, b);
    Out> 3*a;

##### See Also:

Coef , Monic .

###

Monic -- Monic part of a polynomial

Standard math library

##### Calling Sequence:

Monic(poly)
Monic(poly, var)

##### Parameters:

poly - a polynomial
var - a variable

##### Description:

This function returns the monic part of "poly", regarded as a polynomial in the variable "var". The monic part of a polynomial is the quotient of this polynomial by its leading coefficient. So the leading coefficient of the monic part is always one. If only one variable appears in the expression "poly", it is obvious that it should be regarded as a polynomial in this variable and the first calling sequence may be used.

##### Examples:

    In> poly := 2*x^2 + 4*x;
    Out> 2*x^2+4*x;
    In> lc := LeadingCoef(poly);
    Out> 2;
    In> m := Monic(poly);
    Out> x^2+2*x;
    In> Expand(lc*m);
    Out> 2*x^2+4*x;

    In> Monic(2*a^2 + 3*a*b^2 + 5, a);
    Out> a^2+(a*3*b^2)/2+5/2;
    In> Monic(2*a^2 + 3*a*b^2 + 5, b);
    Out> b^2+(2*a^2+5)/(3*a);

##### See Also:

LeadingCoef .

###

RandomPoly -- Construct a random polynomial

Standard math library

##### Calling Sequence:

RandomPoly(var,deg,coefmin,coefmax)

##### Parameters:

var - free variable for resulting univariate polynomial
deg - degree of resulting univariate polynomial
coefmin - minimum value for coefficients
coefmax - maximum value for coefficients

##### Description:

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)
    Out> 3*x^3+10*x^2-4*x-6;
    In> RandomPoly(x,3,-10,10)
    Out> -2*x^3-8*x^2+8;

##### See Also:

Random , RandomIntegerVector .

###

Div and Mod for polynomials

Standard math library
Div and Mod are also defined for polynomials.

##### See Also:

Div , Mod .

###

Horner -- Convert polynomial in Horner form

Standard math library

##### Calling Sequence:

Horner(expr, var)

##### Parameters:

expr - a polynomial in "var"
var - a variable

##### Description:

This command turns the polynomial "expr", considered as a univariate polynomial in "var", into Horner form. A polynomial in normal form is an expression like

                                      n-1           n
    c(0) + c(1) * x + ... + c(n-1) * x    + c(n) * x

If one converts this polynomial in Horner form, one gets the equivalent expression

    (...( c(n) * x + c(n-1) ) * x + ...  + c(1) ) * x + c(0)

Both expression are equal, but the latter form gives a more efficient way to evaluate the polynomial as the powers have disappeared.

##### Examples:

    In> expr1:=Expand((1+x)^4)
    Out> x^4+4*x^3+6*x^2+4*x+1
    In>  Horner(expr1,x)
    Out> (((x+4)*x+6)*x+4)*x+1

##### See Also:

Expand , ExpandBrackets .

###

ExpandBrackets -- Expand all terms

Standard math library

##### Calling Sequence:

ExpandBrackets(expr)

##### Parameters:

expr - an expression

##### Description:

This command tries to expand all the brackets by repeatedly using the distributive laws "a * (b+c) = a*b + a*c" and "(a+b) * c = a*c + b*c". It goes further than `Expand`, in that it expands all terms.

##### Examples:

    In> Expand((a-x)*(b-x),x)
    Out> x^2-(b+a)*x+a*b;
    In> Expand((a-x)*(b-x),{x,a,b})
    Out> x^2-(b+a)*x+b*a;
    In> ExpandBrackets((a-x)*(b-x))
    Out> a*b-x*b+x^2-a*x;

##### See Also:

Expand .

Head , Tail , Length , Map , MapSingle , RandomIntegerVector , MakeVector , Select , Nth , DestructiveReverse , List , UnList , Listify , Concat , Delete , Insert , DestructiveDelete , DestructiveInsert , Replace , DestructiveReplace , FlatCopy , Contains , Find , Append , DestructiveAppend , RemoveDuplicates , Push , Pop , PopFront , PopBack , Swap , Count , Intersection , Union , Difference , FillList , Drop , Take , Partition , Assoc , AssocIndices , Flatten , UnFlatten , Type , NrArgs , BubbleSort , Table , TableForm .

# List operations

Most objects that can be of variable size are represented as lists (linked lists internally). Yacas does implement arrays, which are faster when the number of elements in a collection of objects doesn't change. Operations on lists have better support in the current system.

###

Head -- The first element of a list

Internal function

##### Calling Sequence:

Head(list)

##### Parameters:

list - a list

##### Description:

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> Head({a,b,c})
    Out> a;
    In> Head(f(a,b,c));
    Out> a;

##### See Also:

Tail , Length .

###

Tail -- Returns a list without its first element

Internal function

##### Calling Sequence:

Tail(list)

##### Parameters:

list - a list

##### Description:

This function returns "list" without its first element.

##### Examples:

    In> Tail({a,b,c})
    Out> {b,c};

##### See Also:

Head , Length .

###

Length -- The length of a list or string

Internal function

##### Calling Sequence:

Length(object)

##### Parameters:

object - a list, array or string

##### Description:

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

##### Examples:

    In> Length({a,b,c})
    Out> 3;
    In> Length("abcdef");
    Out> 6;

##### See Also:

Head , Tail , Nth , Count .

###

Map -- Apply an n-ary function to all entries in a list

Standard math library

##### Calling Sequence:

Map(fn, list)

##### Parameters:

fn - function to apply
list - list of lists of arguments

##### Description:

This function 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 function can either be given as a string or as a pure function.

##### Examples:

    In> MapSingle("Sin",{a,b,c});
    Out> {Sin(a),Sin(b),Sin(c)};
    In> Map("+",{{a,b},{c,d}});
    Out> {a+c,b+d};

##### See Also:

MapSingle , MapArgs .

###

MapSingle -- Apply a unary function to all entries in a list

Standard math library

##### Calling Sequence:

MapSingle(fn, list)

##### Parameters:

fn - function to apply
list - list of arguments

##### Description:

The function "fn" is successively applied to all entries in "list", and a list containing the respective results is returned. The function can be given either as a string or as a pure function.

The `/@` operator provides a shorthand for `MapSingle`.

##### Examples:

    In> MapSingle("Sin",{a,b,c});
    Out> {Sin(a),Sin(b),Sin(c)};
    In> MapSingle({{x},x^2}, {a,2,c});
    Out> {a^2,4,c^2};

##### See Also:

Map , MapArgs , /@ .

###

RandomIntegerVector -- Generate a vector of random integers

Standard math library

##### Calling Sequence:

RandomIntegerVector(nr, from, to)

##### Parameters:

nr - number of integers to generate
from - lower bound
to - upper bound

##### Description:

This function 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> RandomIntegerVector(4,-3,3)
    Out> {0,3,2,-2};

##### See Also:

Random , RandomPoly .

###

MakeVector -- Vector of uniquely numbered variable names

Standard math library

##### Calling Sequence:

MakeVector(var,n)

##### Parameters:

var - free variable
n - length of the vector

##### Description:

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.

##### Examples:

    In> MakeVector(a,3)
    Out> {a1,a2,a3};

##### See Also:

RandomIntegerVector , ZeroVector .

###

Select -- Select the entries satisfying some predicate

Standard math library

##### Calling Sequence:

Select(pred, list)

##### Parameters:

pred - a predicate
list - a list of elements to select from

##### Description:

`Select` returns a sublist of "list" which contains all the entries for which the predicate "pred" returns `True` when applied to this entry.

##### Examples:

    In> Select("IsInteger",{a,b,2,c,3,d,4,e,f})
    Out> {2,3,4};

##### See Also:

Length , Find , Count .

###

Nth -- Return the n-th element of a list

Internal function

##### Calling Sequence:

Nth(list, n)

##### Parameters:

list - list to choose from
n - index of entry to pick

##### Description:

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]`.

##### Examples:

    In> lst := {a,b,c,13,19};
    Out> {a,b,c,13,19};
    In> Nth(lst, 3);
    Out> c;
    In> lst[3];
    Out> c;
    In> Nth(lst, {3,4,1});
    Out> {c,13,a};
    In> Nth(b*(a+c), 2);
    Out> a+c;

##### See Also:

Select , Nth .

###

DestructiveReverse -- Reverse a list destructively

Internal function

##### Calling Sequence:

DestructiveReverse(list)

##### Parameters:

list - list to reverse

##### Description:

This command reverses "list" in place, so that the original is destroyed. This means that any variable bound to "list" will now be bound to the reversed list. The reversed list is also returned.

Destructive commands are faster than their nondestructive counterparts. Stangely, there is no nondestructive command to reverse a list. Use `FlatCopy` and `DestructiveReverse` to achieve this.

##### Examples:

    In> lst := {a,b,c,13,19};
    Out> {a,b,c,13,19};
    In> revlst := DestructiveReverse(lst);
    Out> {19,13,c,b,a};
    In> lst;
    Out> {a};

##### See Also:

FlatCopy .

###

List -- Construct a list

Internal function

##### Calling Sequence:

List(expr1, expr2, ...)

##### Parameters:

expr1, expr2 - expressions making up the list

##### Descriptions:

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, ...}".

##### Examples:

    In> List();
    Out> {};
    In> List(a,b);
    Out> {a,b};
    In> List(a,{1,2},d);
    Out> {a,{1,2},d};

##### See Also:

UnList , Listify .

###

UnList -- Convert a list to a function application

Internal function

##### Calling Sequence:

UnList(list)

##### Parameters:

list - list to be converted

##### Description:

This command converts a list to a function application. The first entry of "list" is treated as a function, and the following entries are the arguments to this function. So the function refered to in the first element of "list" is applied to the other elements.

Note that "list" is evaluated before the function application is formed, but the resulting expression is not evaluated.

##### Examples:

    In> UnList({Cos, x});
    Out> Cos(x);
    In> UnList({f});
    Out> f();
    In> UnList({Taylor,x,0,5,Cos(x)});
    Out> Taylor(x,0,5)Cos(x);
    In> Eval(%);
    Out> 1-x^2/2+x^4/24;

##### See Also:

List , Listify .

###

Listify -- Convert a function application to a list

Internal function

##### Calling Sequence:

Listify(expr)

##### Parameters:

expr - expression to be converted

##### Description:

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 first 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> Listify(Cos(x));
    Out> {Cos,x};
    In> Listify(3*a);
    Out> {*,3,a};

##### See Also:

List , UnList , IsAtom .

###

Concat -- Concatenate lists

Internal function

##### Calling Sequence:

Concat(list1, list2, ...)

##### Parameters:

list1, list2 - lists to concatenate

##### Description:

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

##### Examples:

    In> Concat({a,b}, {c,d});
    Out> {a,b,c,d};
    In> Concat({5}, {a,b,c}, {{f(x)}});
    Out> {5,a,b,c,{f(x)}};

##### See Also:

ConcatStrings , : , Insert .

###

Delete -- Delete an element from a list

Internal function

##### Calling Sequence:

Delete(list, n)

##### Parameters:

list - list from which an element should be removed
n - index of the element to remove

##### Description:

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,d,e,f}, 4);
    Out> {a,b,c,e,f};

##### See Also:

DestructiveDelete , Insert , Replace .

###

Insert -- Insert an element into a list

Internal function

##### Calling Sequence:

Insert(list, n, expr)

##### Parameters:

list - list in which "expr" should be inserted
n - index at which to insert
expr - expression to insert in "list"

##### Description:

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 (like the `:` operator); if "n" equals the length of "list" plus one, the expression "expr" is placed at the end of the list (like `Append`). In any case, the resulting list is returned.

##### Examples:

    In> Insert({a,b,c,d}, 4, x);
    Out> {a,b,c,x,d};
    In> Insert({a,b,c,d}, 5, x);
    Out> {a,b,c,d,x};
    In> Insert({a,b,c,d}, 1, x);
    Out> {x,a,b,c,d};

##### See Also:

DestructiveInsert , : , Append , Delete , Remove .

###

DestructiveDelete -- Delete an element destructively from a list

Internal function

##### Calling Sequence:

DestructiveDelete(list, n)

##### Parameters:

list - list from which an element should be removed
n - index of the element to remove

##### Description:

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.

##### Examples:

    In> lst := {a,b,c,d,e,f};
    Out> {a,b,c,d,e,f};
    In> Delete(lst, 4);
    Out> {a,b,c,e,f};
    In> lst;
    Out> {a,b,c,d,e,f};
    In> DestructiveDelete(lst, 4);
    Out> {a,b,c,e,f};
    In> lst;
    Out> {a,b,c,e,f};

##### See Also:

Delete , DestructiveInsert , DestructiveReplace .

###

DestructiveInsert -- Insert an element destructively into a list

Internal function

##### Calling Sequence:

DestructiveInsert(list, n, expr)

##### Parameters:

list - list in which "expr" should be inserted
n - index at which to insert
expr - expression to insert in "list"

##### Description:

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.

##### Examples:

    In> lst := {a,b,c,d};
    Out> {a,b,c,d};
    In> Insert(lst, 2, x);
    Out> {a,x,b,c,d};
    In> lst;
    Out> {a,b,c,d};
    In> DestructiveInsert(lst, 2, x);
    Out> {a,x,b,c,d};
    In> lst;
    Out> {a,x,b,c,d};

##### See Also:

Insert , DestructiveDelete , DestructiveReplace .

###

Replace -- Replace an entry in a list

Internal function

##### Calling Sequence:

Replace(list, n, expr)

##### Parameters:

list - list of which an entry should be replaced
n - index of entry to replace
expr - expression to replace the n-th entry with

##### Description:

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)`.

##### Examples:

    In> Replace({a,b,c,d,e,f}, 4, x);
    Out> {a,b,c,x,e,f};

##### See Also:

Delete , Insert , DestructiveReplace .

###

DestructiveReplace -- Replace an entry in a list destructively

Internal function

##### Calling Sequence:

DestructiveReplace(list, n, expr)

##### Parameters:

list - list of which an entry should be replaced
n - index of entry to replace
expr - expression to replace the n-th entry with

##### Description:

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.

##### Examples:

    In> lst := {a,b,c,d,e,f};
    Out> {a,b,c,d,e,f};
    In> Replace(lst, 4, x);
    Out> {a,b,c,x,e,f};
    In> lst;
    Out> {a,b,c,d,e,f};
    In> DestructiveReplace(lst, 4, x);
    Out> {a,b,c,x,e,f};
    In> lst;
    Out> {a,b,c,x,e,f};

##### See Also:

Replace , DestructiveDelete , DestructiveInsert .

###

FlatCopy -- Copy the top level of a list

Internal function

##### Calling Sequence:

FlatCopy(list)

##### Parameters:

list - list to be copied

##### Description:

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

##### Example:

The following shows a possible way to define a command that reverses a list nondestructively.

    In> reverse(l_IsList) <-- DestructiveReverse(FlatCopy(l));
    Out> True;
    In> lst := {a,b,c,d,e};
    Out> {a,b,c,d,e};
    In> reverse(lst);
    Out> {e,d,c,b,a};
    In> lst;
    Out> {a,b,c,d,e};

###

Contains -- Test whether a list contains a certain element

Standard math library

##### Calling Sequence:

Contains(list, expr)

##### Parameters:

list - list to examine
expr - expression to look for in "list"

##### Description:

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 occurence of "expr".

##### Examples:

    In> Contains({a,b,c,d}, b);
    Out> True;
    In> Contains({a,b,c,d}, x);
    Out> False;
    In> Contains({a,{1,2,3},z}, 1);
    Out> False;
    In> Contains(a*b, b);
    Out> True;

##### See Also:

Find , Count .

###

Find -- The index at which a certain element occurs

Standard math library

##### Calling Sequence:

Find(list, expr)

##### Parameters:

list - the list to examine
expr - expression to look for in "list"

##### Description:

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.

##### Examples:

    In> Find({a,b,c,d,e,f}, d);
    Out> 4;
    In> Find({1,2,3,2,1}, 2);
    Out> 2;
    In> Find({1,2,3,2,1}, 4);
    Out> -1;

##### See Also:

Contains .

###

Append -- Append an entry at the end of a list

Standard math library

##### Calling Sequence:

Append(list, expr)

##### Parameters:

list - list to append "expr" to
expr - expression to append to the list

##### Description:

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> Append({a,b,c,d}, 1);
    Out> {a,b,c,d,1};

##### See Also:

Concat , : , DestructiveAppend .

###

DestructiveAppend -- Destructively append an entry to a list

Internal function

##### Calling Sequence:

DestructiveAppend(list, expr)

##### Parameters:

list - list to append "expr" to
expr - expression to append to the list

##### Description:

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.

##### Examples:

    In> lst := {a,b,c,d};
    Out> {a,b,c,d};
    In> Append(lst, 1);
    Out> {a,b,c,d,1};
    In> lst
    Out> {a,b,c,d};
    In> DestructiveAppend(lst, 1);
    Out> {a,b,c,d,1};
    In> lst;
    Out> {a,b,c,d,1};

##### See Also:

Concat , : , Append .

###

RemoveDuplicates -- Remove any duplicates from a list

Standard math library

##### Calling Sequence:

RemoveDuplicates(list)

##### Parameters:

list - list to act on

##### Description:

This command returns "list" after all duplicates are removed. To be precise, the second occurence of any entry is deleted, as are the third, the fourth, etcetera.

##### Examples:

    In> RemoveDuplicates({1,2,3,2,1});
    Out> {1,2,3};
    In> RemoveDuplicates({a,1,b,1,c,1});
    Out> {a,1,b,c};

###

Push -- Add an element on top of a stack

Standard math library

##### Calling Sequence:

Push(stack, expr)

##### Parameters:

stack - a stack (represented as a list)
expr - expression to push on "stack"

##### Description:

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.

##### Examples:

    In> stack := {};
    Out> {};
    In> Push(stack, x);
    Out> {x};
    In> Push(stack, x2);
    Out> {x2,x};
    In> PopFront(stack);
    Out> x2;

##### See Also:

Pop , PopFront , PopBack .

###

Pop -- Remove an element from a stack

Standard math library

##### Calling Sequence:

Pop(stack, n)

##### Parameters:

stack - a stack (represented as a list)
n - index of the element to remove

##### Description:

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.

##### Examples:

    In> stack := {};
    Out> {};
    In> Push(stack, x);
    Out> {x};
    In> Push(stack, x2);
    Out> {x2,x};
    In> Push(stack, x3);
    Out> {x3,x2,x};
    In> Pop(stack, 2);
    Out> x2;
    In> stack;
    Out> {x3,x};

##### See Also:

Push , PopFront , PopBack .

###

PopFront -- Remove an element from the top of a stack

Standard math library

##### Calling Sequence:

PopFront(stack)

##### Parameters:

stack - a stack (represented as a list)

##### Description:

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.

##### Examples:

    In> stack := {};
    Out> {};
    In> Push(stack, x);
    Out> {x};
    In> Push(stack, x2);
    Out> {x2,x};
    In> Push(stack, x3);
    Out> {x3,x2,x};
    In> PopFront(stack);
    Out> x3;
    In> stack;
    Out> {x2,x};

##### See Also:

Push , Pop , PopBack .

###

PopBack -- Remove an element from the bottom of a stack

Standard math library

##### Calling Sequence:

PopBack(stack)

##### Parameters:

stack - a stack (represented as a list)

##### Description:

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.

##### Examples:

    In> stack := {};
    Out> {};
    In> Push(stack, x);
    Out> {x};
    In> Push(stack, x2);
    Out> {x2,x};
    In> Push(stack, x3);
    Out> {x3,x2,x};
    In> PopBack(stack);
    Out> x;
    In> stack;
    Out> {x3,x2};

##### See Also:

Push , Pop , PopFront .

###

Swap -- Swap two elements in a list

Standard math library

##### Calling Sequence:

Swap(list, i1, i2)

##### Parameters:

list - the list in which a pair of entries should be swapped
i1, i2 - indices of the entries in "list" to swap

##### Description:

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.

##### Examples:

    In> lst := {a,b,c,d,e,f};
    Out> {a,b,c,d,e,f};
    In> Swap(lst, 2, 4);
    Out> {a,d,c,b,e,f};

##### See Also:

Replace , DestructiveReplace .

###

Count -- Count the number of occurrences of an expression

Standard math library

##### Calling Sequence:

Count(list, expr)

##### Parameters:

list - the list to examine
expr - expression to look for in "list"

##### Description:

This command counts the number of times that the expression "expr" occurs in "list" and returns this number.

##### Examples:

    In> lst := {a,b,c,b,a};
    Out> {a,b,c,b,a};
    In> Count(lst, a);
    Out> 2;
    In> Count(lst, c);
    Out> 1;
    In> Count(lst, x);
    Out> 0;

##### See Also:

Length , Select , Contains .

###

Intersection -- Return the intersection of two lists

Standard math library

##### Calling Sequence:

Intersection(l1, l2)

##### Parameters:

l1, l2 - two lists

##### Description:

The intersection of the lists "l1" and "l2" is determined and returned. The intersection contains all elements that occur in both lists. The entries in the result are listed in the same order as in "l1". If an expression occurs multiple times in both "l1" and "l2", then it will occur the same number of times in the result.

##### Examples:

    In> Intersection({a,b,c}, {b,c,d});
    Out> {b,c};
    In> Intersection({a,e,i,o,u}, {f,o,u,r,t,e,e,n});
    Out> {e,o,u};
    In> Intersection({1,2,2,3,3,3}, {1,1,2,2,3,3});
    Out> {1,2,2,3,3};

##### See Also:

Union , Difference .

###

Union -- Return the union of two lists

Standard math library

##### Calling Sequence:

Intersection(l1, l2)

##### Parameters:

l1, l2 - two lists

##### Description:

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});
    Out> {a,b,c,d};
    In> Union({a,e,i,o,u}, {f,o,u,r,t,e,e,n});
    Out> {a,e,i,o,u,f,r,t,n};
    In> Union({1,2,2,3,3,3}, {2,2,3,3,4,4});
    Out> {1,2,3,4};

##### See Also:

Intersection , Difference .

###

Difference -- Return the difference of two lists

Standard math library

##### Calling Sequence:

Intersection(l1, l2)

##### Parameters:

l1, l2 - two lists

##### Description:

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});
    Out> {a};
    In> Difference({a,e,i,o,u}, {f,o,u,r,t,e,e,n});
    Out> {a,i};
    In> Difference({1,2,2,3,3,3}, {2,2,3,4,4});
    Out> {1,3,3};

##### See Also:

Intersection , Union .

###

FillList -- Fill a list with a certain expression

Standard math library

##### Calling Sequence:

FillList(expr, n)

##### Parameters:

expr - expression to fill the list with
n - the length of the list to construct

##### Description:

This command creates a list of length "n" in which all slots contain the expression "expr" and returns this list.

##### Examples:

    In> FillList(x, 5);
    Out> {x,x,x,x,x};

##### See Also:

MakeVector , ZeroVector , RandomIntegerVector .

###

Drop -- Drop a range of elements from a list

Standard math library

##### Calling Sequence:

Drop(list, n)
Drop(list, -n)
Drop(list, {m,n})

##### Parameters:

list - list to act on
n, m - positive integers describing the entries to drop

##### Description:

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};
    Out> {a,b,c,d,e,f,g};
    In> Drop(lst, 2);
    Out> {c,d,e,f,g};
    In> Drop(lst, -3);
    Out> {a,b,c,d};
    In> Drop(lst, {2,4});
    Out> {a,e,f,g};

##### See Also:

Take , Select , Remove .

###

Take -- Take a sublist from a list, dropping the rest

Standard math library

##### Calling Sequence:

Take(list, n)
Take(list, -n)
Take(list, {m,n})

##### Parameters:

list - list to act on
n, m - positive integers describing the entries to drop

##### Description:

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.

##### Examples:

    In> lst := {a,b,c,d,e,f,g};
    Out> {a,b,c,d,e,f,g};
    In> Take(lst, 2);
    Out> {a,b};
    In> Take(lst, -3);
    Out> {e,f,g};
    In> Take(lst, {2,4});
    Out> {b,c,d};

##### See Also:

Drop , Select , Remove .

###

Partition -- Partition a list in sublists of equal length

Standard math library

##### Calling Sequence:

Partition(list, n)

##### Parameters:

list - list to partition
n - length of partitions

##### Description:

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" upto "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.

##### Examples:

    In> Partition({a,b,c,d,e,f,}, 2);
    Out> {{a,b},{c,d},{e,f}};
    In> Partition(1 .. 11, 3);
    Out> {{1,2,3},{4,5,6},{7,8,9}};

##### See Also:

Take , Permutations .

###

Assoc -- Return element stored in association list

Standard math library

##### Calling Sequence:

Assoc(key, alist)

##### Parameters:

key - key under which element is stored
alist - association list to examine

##### Description:

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 `Empty` 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 `Assoc(key, alist)` can (probably more intuitively) be accessed as `alist[key]`.

##### Examples:

    In> writer := {};
    Out> {};
    In> writer["Iliad"] := "Homer";
    Out> True;
    In> writer["Henry IV"] := "Shakespeare";
    Out> True;
    In> writer["Ulysses"] := "James Joyce";
    Out> True;
    In> Assoc("Henry IV", writer);
    Out> {"Henry IV","Shakespeare"};
    In> Assoc("War and Peace", writer);
    Out> Empty;

##### See Also:

AssocIndices , [] , := .

###

AssocIndices -- Return the keys in an association list

Standard math library

##### Calling Sequence:

AssocIndices(alist)

##### Parameters:

alist - association list to examine

##### Description:

All the keys in the association list "alist" are assembled in a list and this list is returned.

##### Examples:

    In> writer := {};
    Out> {};
    In> writer["Iliad"] := "Homer";
    Out> True;
    In> writer["Henry IV"] := "Shakespeare";
    Out> True;
    In> writer["Ulysses"] := "James Joyce";
    Out> True;
    In> AssocIndices(writer);
    Out> {"Iliad","Henry IV","Ulysses"};

##### See Also:

Assoc .

###

Flatten -- Flatten expression w.r.t. some operator

Standard math library

##### Calling Sequence:

Flatten(expression,operator)

##### Parameters:

expression - an expression
operator - string with the contents of an infix operator.

##### Description:

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.

##### Examples:

    In> Flatten(a+b*c+d,"+");
    Out> {a,b*c,d};
    In> Flatten({a,{b,c},d},"List");
    Out> {a,b,c,d};

##### See Also:

UnFlatten .

###

UnFlatten -- Inverse operation of Flatten

Standard math library

##### Calling Sequence:

UnFlatten(list,operator,identity)

##### Parameters:

list - list of objects the operator is to work on
operator - infix operator
identity - identity of the operator

##### Description:

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.

##### Examples:

    In> UnFlatten({a,b,c},"+",0)
    Out> a+b+c;
    In> UnFlatten({a,b,c},"*",1)
    Out> a*b*c;

##### See Also:

Flatten .

###

Type -- Return the type of an expression

Internal function

##### Calling Sequence:

Type(expr)

##### Parameters:

expr - expression to examine

##### Description:

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 `""`.

##### Examples:

    In> Type({a,b,c});
    Out> "List";
    In> Type(a*(b+c));
    Out> "*";
    In> Type(123);
    Out> "";

##### See Alsi:

IsAtom , NrArgs .

###

NrArgs -- Return number of top-level arguments

Standard math library

##### Calling Sequence:

NrArgs(expr)

##### Parameters:

expr - expression to examine

##### Description:

This function 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> NrArgs(f(a,b,c))
    Out> 3;
    In> NrArgs(Sin(x));
    Out> 1;
    In> NrArgs(a*(b+c));
    Out> 2;

##### See Also:

Type , Length .

###

BubbleSort -- Sort a list

Standard math library

##### Calling Sequence:

BubbleSort(list, fn)

##### Parameters:

list - list to sort
fn - function used to compare element of "list"

##### Description:

This command returns "list" after it is sorted using "fn" to compare elements. The function "fn" 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.

This function uses the so-called BubbleSort algorithm to do the sorting. This algorithm is chosen because it is easy to implement, though it is not particularly fast.

##### Examples:

    In> BubbleSort({4,7,23,53,-2,1}, "<");
    Out> {-2,1,4,7,23,53};
    In> BubbleSort({4,7,23,53,-2,1}, ">");
    Out> {53,23,7,4,1,-2};

###

Table -- Evaluate while some variable ranges over interval

Standard math library

##### Calling Sequence:

Table(body, var, from, to, step)

##### Parameters:

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

##### Description:

This command generates a list of values from "body", by assigning variable "var" values from "from" upto "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> Table(i!, i, 1, 10, 1);
    Out> {1,2,6,24,120,720,5040,40320,362880,3628800};
    In> Table(i, i, 3, 16, 4);
    Out> {3,7,11,15};
    In> Table(i^2, i, 10, 1, -1);
    Out> {100,81,64,49,36,25,16,9,4,1};

##### See Also:

For , MapSingle , .. , TableForm .

###

TableForm -- Print each entry in a list on a line

Standard math library

##### Calling Sequence:

TableForm(list)

##### Parameters:

list - list to print

##### Description:

This functions writes out "list" in a nicer readable form, by printing every element in the list on a seperate line.

##### Examples:

    In> TableForm(Table(i!, i, 1, 10, 1));
    1
     2
     6
     24
     120
     720
     5040
     40320
     362880
     3628800
    Out> True;

##### See Also:

PrettyForm , Echo , Table .

: , @ , /@ , .. .

# Functional operators

These operators can help the user to program in the style of functional programming languages like Miranda and Haskell.

###

: -- Prepend item to list, or concatenate strings

Standard math library

##### Calling Sequence:

item : list (prec. 7)
string1 : string2 (prec. 7)

##### Parameters:

item - an item to be prepended to a list
list - a list
string1 - a string
string2 - a string

##### Description:

The first form prepends "item" as the first entry to the list "list". The second form concatenates the strings "string1" and "string2".

##### Examples:

    In> a:b:c:{}
    Out> {a,b,c};
    In> "This":"Is":"A":"String"
    Out> "ThisIsAString";

##### See Also:

Concat , ConcatStrings .

###

@ -- Apply a function

Standard math library

##### Calling Sequence:

fn @ arglist (prec. 60)

##### Parameters:

fn - function to apply
arglist - single argument, or a list of arguments

##### Description:

This function is a shorthand for `Apply`. It applies the function "fn" to the argument(s) in "arglist" and returns the result. The first parameter "fn" can either be a string containing the name of a function or a pure function.

##### Examples:

    In> "Sin" @ a
    Out> Sin(a);
    In> {{a},Sin(a)} @ a
    Out> Sin(a);
    In> "f" @ {a,b}
    Out> f(a,b);

##### See Also:

Apply .

###

/@ -- Apply a function to all entries in a list

Standard math library

##### Calling Sequence:

fn /@ list (prec. 60)

##### Parameters:

fn - function to apply
list - list of arguments

##### Description:

This function is a shorthand for `MapSingle`. It successively applies the function "fn" to all the entries in "list" and returns a list contains the results. The parameter "fn" can either be a string containing the name of a function or a pure function.

##### Examples:

    In> "Sin" /@ {a,b}
    Out> {Sin(a),Sin(b)};
    In> {{a},Sin(a)*a} /@ {a,b}
    Out> {Sin(a)*a,Sin(b)*b};

##### See Also:

MapSingle , Map , MapArgs .

###

.. -- Construct a list of consecutive integers

Standard math library

##### Calling Sequence:

n .. m (prec. 60)

##### Parameters:

n - integer. the first entry in the list
m - integer, the last entry in the list

##### Description:

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`.

##### Examples:

    In> 1 .. 4
    Out> {1,2,3,4};

##### See Also:

Table .

MaxEvalDepth , Hold , Eval , While , Until , If , SystemCall , Function , Use , For , ForEach , Apply , MagArgs , Subst , WithValue , /:, /:: , SetHelpBrowser , TraceStack , TraceExp , TraceRule .

# Control flow functions

###

MaxEvalDepth -- Set the maximum evaluation depth

Internal function

##### Calling Sequence:

MaxEvalDepth(n)

##### Parameters:

n - new maximum evalution depth

##### Description:

Use this command to set the maximum evaluation depth to the integer "n". The default value is 1000. The function `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)`, etcetera. The interpreter will halt if the maximum evaluation depth is reached. Also indirect recursion, like the pair of definitions `f(x) := g(x)` and `g(x) := f(x)`, will be caught.

##### Examples:

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

    In> f(x) := f(x)
    Out> 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 function `MaxEvalDepth` is meant for these cases.

    In> 10 # g(0) <-- 1;
    Out> True;
    In> 20 # g(n_IsPositiveInteger) <-- 2 * g(n-1);
    Out> 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);
    Out> True;
    In> g(1001);
    Out> 214301721437253464189685009812000362112280962341106721488750077674070210224
    98722449863967576313917162551893458351062936503742905713846280871969155149397149
    60786913554964846197084214921012474228375590836430609294996716388253479753511833
    1087892154125829142392955373084335320859663305248773674411336138752;

###

Hold -- Do not evaluate the argument

Internal function

##### Calling Sequence:

Hold(expr)

##### Parameters:

expr - expression to hold

##### Description:

The expression "expr" is returned unevaluated. This is useful to prevent the evaluation of a certain expression in a context in which evaluation normally takes place.

##### Example:

    In> Echo({ Hold(1+1), "=", 1+1 });
     1+1 = 2
    Out> True;

##### See Also:

Eval , HoldArg .

###

Eval -- Evaluate the argument

Internal function

##### Calling Sequence:

Eval(expr)

##### Parameters:

expr - expression to evaluate

##### Description:

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

##### Examples:

    In> a := x;
    Out> x;
    In> x := 5;
    Out> 5;
    In> a;
    Out> x;
    In> Eval(a);
    Out> 5;

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 behaviour 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.

##### See Also:

Hold , HoldArg , := .

###

While -- Loop while a condition is met

Internal function

##### Calling Sequence:

While(pred) body

##### Parameters:

pred - predicate deciding whether to keep on looping
body - expression to loop over

##### Description:

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.

##### Examples:

    In> x := 0;
    Out> 0;
    In> While (x! < 10^6) [ Echo({x, x!}); x++; ];
     0  1
     1  1
     2  2
     3  6
     4  24
     5  120
     6  720
     7  5040
     8  40320
     9  362880
    Out> True;

##### See Also:

Until , For .

###

Until -- Loop until a condition is met

Standard math library

##### Calling Sequence:

Until(pred) body

##### Parameters:

pred - predicate deciding whether to stop
body - expression to loop over

##### Description:

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(Not 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.

##### Examples:

    In> x := 0;
    Out> 0;
    In> Until (x! > 10^6) [ Echo({x, x!}); x++; ];
     0  1
     1  1
     2  2
     3  6
     4  24
     5  120
     6  720
     7  5040
     8  40320
     9  362880
    Out> True;

##### See Also:

While , For .

###

If -- Branch point

Internal function

##### Calling Sequence:

If(pred, then)
If(pred, then, else)

##### Parameters:

pred - predicate to test
then - expression to evaluate if "pred" is True
else - expression to evaluate if "pred" is False

##### Description:

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 (ie. if the first calling sequence is used), the `If` expression returns `False`.

##### Examples:

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) := If (IsPositiveReal(x), 1, -1);
    Out> True;
    In> mysign(Pi);
    Out> 1;
    In> mysign(-2.5);
    Out> -1;

Note that this will give incorrect results, if "x" cannot be numerically approximated.

    In> mysign(a);
    Out> -1;

Hence a better implementation would be

    In> mysign(_x)_IsNumber(N(x)) <-- If (IsPositiveReal(x), 1, -1);
    Out> True;

###

SystemCall -- Pass a command to the shell

Internal function

##### Calling Sequence:

SystemCall(str)

##### Parameters:

str - string containing the command to call

##### Description:

The command contained in the string "str" is executed by the underlying Operating System. The return value of `SystemCall` is `True`.

This command is not allowed in the body of the `Secure` command and will lead to an error.

##### Examples:

In a UNIX environment, the command `SystemCall("ls")` would list the contents of the current directory.

##### See Also:

Secure .

###

Function -- Define a function

Standard math library

##### Calling Sequence:

Function("op", {arg,...}) body

##### Parameters:

op - name of the function
arg - formal argument to the function
body - expression compromising the body of the function

##### Description:

This command can be used to declare a simple function. It is equivalent to the rule `op(_arg, ...) <-- body`. Any previous rules associated with "op" (with the same arity) will be discarded. More complicated function can be defined using a rule database.

##### Examples:

    In> Function("FirstOf", {list})  list[1];
    Out> True;
    In> FirstOf({a,b,c});
    Out> a;

This defines a function `FirstOf` which returns the first element of a list. Equivalent definitions would be `FirstOf(_list) <-- list[1]` or `FirstOf(list) := list[1]`.

##### See Also:

TemplateFunction , Rule , RuleBase , := .

###

Use -- Load a file, but not twice

Internal function

##### Calling Sequence:

Use(name)

##### Parameters:

name - name of the file to load

##### Description:

If the file "name" has been loaded before, either by an earlier call to `Use` or via the `DefLoad` mechanism, nothing happens. Otherwise all expressions in the file are read and evaluated. `Use` always returns `True`.

The purpose of this function is to make sure that the file will at least have been loaded, but is not loaded twice.

##### See Also:

Load , DefLoad , DefaultDirectory .

###

For -- C-style for loop

Standard math library

##### Calling Sequence:

For(init, pred, incr) body

##### Parameters:

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

##### Description:

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 traversion 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 like `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;]`.

##### Examples:

    In> For (i:=1, i<=10, i++) Echo({i, i!});
     1  1
     2  2
     3  6
     4  24
     5  120
     6  720
     7  5040
     8  40320
     9  362880
     10  3628800
    Out> True;

##### See Also:

While , Until , ForEach .

###

ForEach -- Loop over all entries in list

Standard math library

##### Calling sequence:

ForEach(var, list) body

##### Parameters:

var - looping variable
list - list of values to assign to "var"
body - expression to evaluate with different values of "var"

##### Description:

The expression "body" is evaluated multiple times. The first time, "var" has the value of the first element of "list", then it gets the value of the second element and so on. `ForEach` returns `True`.

##### Examples:

     In> ForEach(i,{2,3,5,7,11}) Echo({i, i!});
     2  2
     3  6
     5  120
     7  5040
     11  39916800
    Out> True;

##### See Also:

For .

###

Apply -- Apply a function

Standard math library

##### Calling sequence:

Apply(fn, arglist)

##### Parameters:

fn - function to apply
arglist - list of arguments

##### Description:

This function applies the function "fn" to the arguments in "arglist" and returns the result. The first parameter "fn" can either be a string containing the name of a function or a pure function. Pure functions, modelled after lambda-expressions, have the form "{varlist,body}", where "varlist" is the list of formal parameters. Upon application, the formal paramaters are assigned the values in "arglist" (the second parameter of `Apply`) and the "body" is evaluated

An shorthand for `Apply` is provided by the `@` operator.

##### Examples:

    In> Apply("+", {5,9});
    Out> 14;
    In> Apply({{x,y}, x-y^2}, {Cos(a), Sin(a)});
    Out> Cos(a)-Sin(a)^2;

##### See Also:

Map , MapSingle , @ .

###

MagArgs -- Apply a function to all top-level arguments

Standard math library

##### Calling Sequence:

MapArgs(expr, fn)

##### Parameters:

expr - an expression to work on
fn - an operation to perform on each argument

##### Description:

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 function or a pure function.

##### Examples:

    In> MapArgs(f(x,y,z),"Sin");
    Out> f(Sin(x),Sin(y),Sin(z));
    In> MapArgs({3,4,5,6}, {{x},x^2});
    Out> {9,16,25,36};

##### See Also:

MapSingle , Map , Apply .

###

Subst -- Perform a substitution

Standard math library

##### Calling Sequence:

Subst(from, to) expr

##### Parameters:

from - expression to be substituted
to - expression to substitute for "from"
expr - expression in which the substitution takes place

##### Description:

This function substitutes every occurence of "from" in "expr" by "to". This is a syntactical substitution: only places where "from" occurs as a subexpression are affected.

##### Examples:

    In> Subst(x, Sin(y)) x^2+x+1;
    Out> Sin(y)^2+Sin(y)+1;
    In> Subst(a+b, x) a+b+c;
    Out> x+c;
    In> Subst(b+c, x) a+b+c;
    Out> a+b+c;

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.

##### See Also:

WithValue , /: .

###

WithValue -- Temporary assignment during an evaluation

Standard math library

##### Calling Sequence:

WithValue(var, val, expr)
WithValue({var,...}, {val,...}, expr)

##### Parameters:

var - variable to assign to
val - value to be assigned to "var"
expr - expression to evaluate with "var" equal to "val"

##### Description:

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, etcetera.

##### Examples:

    In> WithValue(x, 3, x^2+y^2+1);
    Out> y^2+10;
    In> WithValue({x,y}, {3,2}, x^2+y^2+1);
    Out> 14;

##### See Also:

Subst , /: .

###

/:, /:: -- Local simplification rules

Standard math library

##### Calling Sequence:

expression /: patterns (prec. 10000)
expressions /:: patterns (prec. 10000)

##### Parameters:

expression - an expression
patterns - a list of patterns

##### Description:

Sometimes you have an expression, and you want to use specific simplification 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 like `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:

    In> Sin(x)*Ln(a*b)
    Out> Sin(x)*Ln(a*b);
    In> % /: { Ln(_x*_y) <- Ln(x)+Ln(y) }
    Out> 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 in stead of <-- which defines a global rule.

The /: operator traverses an expression much like Subst does: top down, trying to apply the rules from the begin of the list of rules to the end of the list of rules. If the rules cannot be applied to a sub-expression, it will try the sub expressions of the expression being analyzed.

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 eachother, and that could result in an infinite loop. To detect this situation, just use /: repeatedly on the expression. The repetitive nature should become apparent.

##### Examples:

    In> Sin(u)*Ln(a*b) /: { Ln(_x*_y) <- Ln(x)+Ln(y) }
    Out> Sin(u)*(Ln(a)+Ln(b));
    In> Sin(u)*Ln(a*b) /:: { a <- 2, b <- 3 }
    Out> Sin(u)*Ln(6);

##### See Also:

Subst .

###

SetHelpBrowser -- Set the HTML browser to use for help

Standard math library

##### Calling Sequence:

SetHelpBrowser(helpbrowser)

##### Parameters:

helpbrowser - string containing a html browser to use for help

##### Description:

This function sets the help browser you want to use to browse the help online. It calls helpbrowser with the html page as first argument. The default is lynx. If you want to use a different browser by default it suffices to create a file ~/.yacasrc. and add a line to set the browser in there.

##### Examples:

    In> SetHelpBrowser("netscape")
    Out> "netscape";
    In> ??

##### See Also:

Help .

###

TraceStack -- Show calling stack after an error occurs

Internal function

##### Calling Sequence:

TraceStack(expression)

##### Parameters:

expression - an expression to evaluate

##### Description:

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 Yacas. 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.

##### Examples:

Here is an example of a function calling itself recursively, causing Yacas to flood its stack:

    In> f(x):=f(Sin(x))
    Out> 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 :  IsList (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 Also:

TraceExp , TraceRule .

###

TraceExp -- Evaluate with tracing enabled

Internal function

##### Calling Sequence:

TraceExp(expr)

##### Parameters:

expr - expression to trace

##### Description:

The expression "expr" is evaluated with the tracing facility turned on. This means that every subexpression, which is evaluated, is shown before and after evaluation. Before evaluation, it is shown in the forn `TrEnter(x)`, where `x` denotes the subexpression being evaluated. After the evaluation the line `TrLeave(x,y)` is printed, where `y` is the result of the evaluation. The indentation shows the nesting level.

Note that this command usually generates huge amounts of output. A more specific form of tracing (eg. `TraceRule`) is probably more useful for all but very simple expressions.

##### Examples:

    In> TraceExp(2+3);
      TrEnter(2+3);
        TrEnter(2);
        TrLeave(2, 2);
        TrEnter(3);
        TrLeave(3, 3);
        TrEnter(IsNumber(x));
          TrEnter(x);
          TrLeave(x, 2);
        TrLeave(IsNumber(x),True);
        TrEnter(IsNumber(y));
          TrEnter(y);
          TrLeave(y, 3);
        TrLeave(IsNumber(y),True);
        TrEnter(True);
        TrLeave(True, True);
        TrEnter(MathAdd(x,y));
          TrEnter(x);
          TrLeave(x, 2);
          TrEnter(y);
          TrLeave(y, 3);
        TrLeave(MathAdd(x,y),5);
      TrLeave(2+3, 5);
    Out> 5;

##### See Also:

TraceStack , TraceRule .

###

TraceRule -- Turn on tracing for a particular function

Internal function

##### Calling Sequence:

TraceRule(templ) expr

##### Parameters:

templ - template showing the operator to trace
expr - expression to evaluate with tracing on

##### Description:

The tracing facility is turned on for subexpressions of the form "templ", and the expression "expr" is evaluated. The template "templ" is an example of the function to trace on. Specifically, all subexpressions with the same top-level operator and arity as "templ" are showed. The subexpressions are displayed before (indicated with `TrEnter`) and after (`TrLeave`) evaluation. In between, the arguments are showed before and after evaluation (`TrArg`). Only function 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.

##### Examples:

    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);
    Out> 21;

##### See Also:

TraceStack , TraceExp .

< , > , <= , >= , != , = , Not , And , Or , IsFreeOf , IsZeroVector , IsNonObject , IsEven , IsOdd , IsFunction , IsAtom , IsString , IsNumber , IsList , IsBound , IsBoolean , IsNegativeNumber , IsNegativeInteger , IsPositiveNumber , IsPositiveInteger , IsNotZero , IsNonZeroInteger , IsInfinity , IsPositiveReal , IsNegativeReal , IsConstant .

# Predicates

A predicate is a function that returns a boolean value, i.e. `True` or `False`. Predicates are often used in patterns, For instance, a rule that only holds for a positive integer would use a pattern like `n_IsPositiveInteger`.

###

< -- Test whether lhs is smaller than rhs

Standard math library

##### Calling Sequence:

e1 < e2 (prec. 9)

##### Parameters:

e1, e2 - expressions to be compared

##### Description:

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. `IsNumber` returns `True`), or the quotient of two numbers, or an infinity (i.e. `IsInfinity` returns `True`).

##### Examples:

    In> 2 < 5;
    Out> True;
    In> Cos(1) < 5;
    Out> Cos(1)<5;
    In> N(Cos(1)) < 5;
    Out> True

##### See Also:

IsNumber , IsInfinity , N .

###

> -- Test whether lhs is larger than rhs

Standard math library

##### Calling Sequence:

e1 > e2 (prec. 9)

##### Parameters:

e1, e2 - expressions to be compared

##### Description:

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. `IsNumber` returns `True`), or the quotient of two numbers, or an infinity (i.e. `IsInfinity` returns `True`).

##### Examples:

    In> 2 > 5;
    Out> False;
    In> Cos(1) > 5;
    Out> Cos(1)>5;
    In> N(Cos(1)) > 5;
    Out> False

##### See Also:

IsNumber , IsInfinity , N .

###

<= -- Test whether lhs is smaller or equal rhs

Standard math library

##### Calling Sequence:

e1 <= e2 (prec. 9)

##### Parameters:

e1, e2 - expressions to be compared

##### Description:

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. `IsNumber` returns `True`), or the quotient of two numbers, or an infinity (i.e. `IsInfinity` returns `True`).

##### Examples:

    In> 2 <= 5;
    Out> True;
    In> Cos(1) <= 5;
    Out> Cos(1)<=5;
    In> N(Cos(1)) <= 5;
    Out> True

##### See Also:

IsNumber , IsInfinity , N .

###

>= -- Test whether lhs is larger or equal rhs

Standard math library

##### Calling Sequence:

e1 >= e2 (prec. 9)

##### Parameters:

e1, e2 - expressions to be compared

##### Description:

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. `IsNumber` returns `True`), or the quotient of two numbers, or an infinity (i.e. `IsInfinity` returns `True`).

##### Examples:

    In> 2 >= 5;
    Out> False;
    In> Cos(1) >= 5;
    Out> Cos(1)>=5;
    In> N(Cos(1)) >= 5;
    Out> False

##### See Also:

IsNumber , IsInfinity , N .

###

!= -- Test whether two expressions are not equal

Standard math library

##### Calling Sequence:

e1 != e2 (prec. 9)

##### Parameters:

e1, e2 - expressions to be compared

##### Description:

Both expression 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;
    Out> True;
    In> 1 != 1;
    Out> False;

##### See Also:

= .

###

= -- Test whether two expressoins are equal

Standard math library

##### Calling Sequence:

e1 = e2 (prec. 9)

##### Parameters:

e1, e2 - expressions to be compared

##### Description:

Both expression are evaluated and compared. If they turn out to be equal, the result is `True`. Otherwise, the result is `False`. The function `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 (mathematically) equal; see the examples underneath. Put otherwise, this function tests whether the two expressions would be displayed in the same way if they were printed.

##### Examples:

    In> e1 := (x+1) * (x-1);
    Out> (x+1)*(x-1);
    In> e2 := x^2 - 1;
    Out> x^2-1;

    In> e1 = e2;
    Out> False;
    In> Expand(e1) = e2;
    Out> True;

!= , Equals .

###

Not -- Logical negation

Internal function

##### Calling Sequence:

Not bool

##### Parameters:

bool - a boolean expression

##### Description:

Not returns the logical negation of the argument bool. If bool is False it returns True, and if the argument is True Not returns False. If the argument is neither True nor False it returns the entire expression with evaluated arguments.

##### Examples:

    In> Not True
    Out> False;
    In> Not False
    Out> True;
    In> Not(a)
    Out> Not a;

##### See Also:

And , Or .

###

And -- Logical conjunction

Internal function

##### Calling Sequence:

a1 And a2 (prec. 100)
And(a1,a2,a3,...,an)

##### Parameters:

a1 .. an - boolean values (True or False)

##### Description:

This function returns True if all arguments are true. The And operation is lazy, it returns False as soon as a False argument is found (from left to right). 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.

##### Examples:

    In> True And False
    Out> False;
    In> And(True,True)
    Out> True;
    In> False And a
    Out> False;
    In> True And a
    Out> And(a);
    In> And(True,a,True,b)
    Out> b And a;

##### See Also:

Or , Not .

###

Or -- Logical disjunction

Internal function

##### Calling Sequence:

a1 Or a2 (prec. 101)
Or(a1,a2,a3,...,an)

##### Parameters:

a1 .. an - boolean values (True or False)

##### Description:

This function returns True if an argument is encountered that is true (scanning from left to right). The Or operation is lazy, 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 a new Or expression is returned with all arguments that didn't evaluate to True or False yet.

##### Examples:

    In> True Or False
    Out> True;
    In> False Or a
    Out> Or(a);
    In> Or(False,a,b,True)
    Out> True;

##### See Also:

And , Not .

###

IsFreeOf -- Test whether expression depends on variable

Standard math library

##### Calling Sequence:

IsFreeOf(expr, var)
IsFreeOf(expr, {var, ...})

##### Parameters:

expr - expression to test
var - variable to look for in "expr"

##### Description:

This function 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 any of the variables named in the list. The result is `True` if none of the variables appear in the expression and `False` otherwise.

##### Examples:

    In> IsFreeOf(Sin(x), x);
    Out> False;
    In> IsFreeOf(Sin(x), y);
    Out> True;
    In> IsFreeOf(D(x) a*x+b, x);
    Out> True;
    In> IsFreeOf(Sin(x), {x,y});
    Out> False;

The third command returns `True` because the expression `D(x) a*x+b` evaluates to `a`, which does not depend on `x`.

##### See Also:

Contains .

###

IsZeroVector -- Test whether list contains only zeroes

Standard math library

##### Calling Sequence:

IsZeroVector(list)

##### Parameters:

list - list to compare against the zero vector

##### Description:

The only argument given to `IsZeroVector` should be a list. The result is `True` if the list contains only zeroes and `False` otherwise.

##### Examples:

    In> IsZeroVector({0, x, 0});
    Out> False;
    In> IsZeroVector({x-x, 1 - D(x) x});
    Out> True;

##### See Also:

IsList , ZeroVector .

###

IsNonObject -- Test whether argument is not an Object()

Standard math library

##### Calling Sequence:

IsNonObject(expr)

##### Parameters:

expr - the expression to examine

##### Description:

This function returns `True` if "expr" is not of the form `Object(...)` and `False` otherwise.

##### Bugs:

In fact, the result is always `True`.

##### See Also:

Object .

###

IsEven -- Test whether integer is even

Standard math library

##### Calling Sequence:

IsEven(n)

##### Parameters:

n - integer to test

##### Description:

This function 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, etcetera, and -2, -4, -6, -8, -10, etcetera.

##### Examples:

    In> IsEven(4);
    Out> True;
    In> IsEven(-1);
    Out> False;

##### See Also:

IsOdd , IsInteger .

###

IsOdd -- Test whether integer is odd

Standard math library

##### Calling Sequence:

IsOdd(n)

##### Parameters:

n - integer to test

##### Description:

This function 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, etcetera, and -1, -3, -5, -7, -9, etcetera.

##### Examples:

    In> IsOdd(4);
    Out> False;
    In> IsOdd(-1);
    Out> True;

##### See Also:

IsEven , IsInteger .

###

IsFunction -- Test whether argument is a composite object

Internal function

##### Calling Sequence:

IsFunction(expr)

##### Parameters:

expr - expression to test

##### Description:

This function tests whether "expr" is a composite object, ie. not an atom. This includes not only obvious functions like `f(x)`, but also expressions like `x+5` and lists.

##### Examples:

    In> IsFunction(x+5);
    Out> True;
    In> IsFunction(x);
    Out> False;

##### See Also:

IsAtom , IsList , Type .

###

IsAtom -- Test whether argument is an atom

Internal function

##### Calling Sequence:

IsAtom(expr)

##### Parameters:

expr - expression to test

##### Description:

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

##### Examples:

    In> IsAtom(x+5);
    Out> Falso;
    In> IsAtom(5);
    Out> True;

##### See Also:

IsFunction , IsNumber , IsString .

###

IsString -- Test whether argument is an string

Internal function

##### Calling Sequence:

IsString(expr)

##### Parameters:

expr - expression to test

##### Description:

This function tests whether "expr" is a string. A string is a text within quotes, eg. `"duh"`.

##### Examples:

    In> IsString("duh");
    Out> True;
    In> IsString(duh);
    Out> False;

##### See Also:

IsAtom , IsNumber .

###

IsNumber -- Test whether argument is a number

Internal function

##### Calling Sequence:

IsNumber(expr)

##### Parameters:

expr - expression to test

##### Description:

This function tests whether "expr" is a number. There are two kinds of numbers, integers (like 6) and reals (like -2.75 or 6.0). Note that a complex number is represented by the `Complex` function, so `IsNumber` will return `False`.

##### Examples:

    In> IsNumber(6);
    Out> True;
    In> IsNumber(3.25);
    Out> True;
    In> IsNumber(I);
    Out> False;
    In> IsNumber("duh");
    Out> False;

##### See Also:

IsAtom , IsString , IsInteger , IsPositiveNumber , IsNegativeNumber , Complex .

###

IsList -- Test whether argument is a list

Internal function

##### Calling Sequence:

IsList(expr)

##### Parameters:

expr - expression to test

##### Description:

This function tests whether "expr" is a list. A list is a sequence between curly braces, like `{2, 3, 5}`.

##### Examples:

    In> IsList({2,3,5});
    Out> True;
    In> IsList(2+3+5);
    Out> False;

##### See Also:

IsFunction .

###

IsBound -- Test whether a variable is bound to a value

Internal function

##### Calling Sequence:

IsBound(var)

##### Parameters:

var - variable to test

##### Description:

This function tests whether the variable "var" is bound, ie. whether it has a value. The argument "var" is not evaluated.

##### Examples:

    In> IsBound(x);
    Out> False;
    In> x := 5;
    Out> 5;
    In> IsBound(x);
    Out> True;

##### See Also:

IsAtom .

###

IsBoolean -- Test whether argument is a Boolean

Standard math library

##### Calling Sequence:

IsBoolean(expression)

##### Parameters:

expression - an expression

##### Description:

IsBoolean returns True if the argument is of a boolean type. This means it has to be either True, False, or an expression involving functions that return a boolean result, like =, >, <, >=, <=, !=, And, Not, Or.

##### Examples:

    In> IsBoolean(a)
    Out> False;
    In> IsBoolean(True)
    Out> True;
    In> IsBoolean(a And b)
    Out> True;

##### See Also:

True , False .

###

IsNegativeNumber -- Test whether argument is a negative number

Standard math library

##### Calling Sequence:

IsNegativeNumber(n)

##### Parameters:

n - number to test

##### Description:

`IsNegativeNumber(n)` evaluates to `True` if "n" is (strictly) negative, ie. if n<0. If "n" is not a number, the function returns `False`.

##### Examples:

    In> IsNegativeNumber(6);
    Out> False;
    In> IsNegativeNumber(-2.5);
    Out> True;

##### See Also:

IsNumber , IsPositiveNumber , IsNotZero , IsNegativeInteger , IsNegativeReal .

###

IsNegativeInteger -- Test whether argument is a negative integer

Standard math library

##### Calling Sequence:

IsNegativeInteger(n)

##### Parameters:

n - integer to test

##### Description:

This function tests whether the integer "n" is (strictly) negative. The negative integers are -1, -2, -3, -4, -5, etcetera. If "n" is not a integer, the function returns `False`.

##### Examples:

    In> IsNegativeInteger(31);
    Out> False;
    In> IsNegativeInteger(-2);
    Out> True;

##### See Also:

IsPositiveInteger , IsNonZeroInteger , IsNegativeNumber .

###

IsPositiveNumber -- Test whether argument is a positive number

Standard math library

##### Calling Sequence:

IsPositiveNumber(n)

##### Parameters:

n - number to test

##### Description:

`IsPositiveNumber(n)` evaluates to `True` if "n" is (strictly) positive, ie. if n>0. If "n" is not a number the function returns `False`.

##### Examples:

    In> IsPositiveNumber(6);
    Out> True;
    In> IsPositiveNumber(-2.5);
    Out> False;

##### See Also:

IsNumber , IsNegativeNumber , IsNotZero , IsPositiveInteger , IsPositiveReal .

###

IsPositiveInteger -- Test whether argument is a positive integer

Standard math library

##### Calling Sequence:

IsPositiveInteger(n)

##### Parameters:

n - integer to test

##### Description:

This function tests whether the integer "n" is (strictly) positive. The positive integers are 1, 2, 3, 4, 5, etcetera. If "n" is not a integer the function returns `False`.

##### Examples:

    In> IsPositiveInteger(31);
    Out> True;
    In> IsPositiveInteger(-2);
    Out> False;

##### See Also:

IsNegativeInteger , IsNonZeroInteger , IsPositiveNumber .

###

IsNotZero -- Test whether argument is a nonzero number

Standard math library

##### Calling Sequence:

IsNotZero(n)

##### Parameters:

n - number to test

##### Description:

`IsNotZero(n)` evaluates to `True` if "n" is not zero. In case "n" is not a number, the function returns `False`.

##### Examples:

    In> IsNotZero(3.25);
    Out> True;
    In> IsNotZero(0);
    Out> False;

##### See Also:

IsNumber , IsPositiveNumber , IsNegativeNumber , IsNonZeroInteger .

###

IsNonZeroInteger -- Test whether argument is a nonzero integer

Standard math library

##### Calling Sequence:

IsNonZeroInteger(n)

##### Parameters:

n - integer to test

##### Description:

This function tests whether the integer "n" is not zero. If "n" is not an integer, the result is `False`.

##### Examples:

    In> IsNonZeroInteger(0)
    Out> False;
    In> IsNonZeroInteger(-2)
    Out> True;

##### See Also:

IsPositiveInteger , IsNegativeInteger , IsNotZero .

###

IsInfinity -- Test whether argument is an infinity

Standard math library

##### Calling Sequence:

IsInfinity(expr)

##### Parameters:

expr - expression to test

##### Description:

This function tests whether "expr" is an infinity. This is only the case if "expr" is either `Infinity` or `-Infinity`.

##### Examples:

    In> IsInfinity(10^1000);
    Out> False;
    In> IsInfinity(-Infinity);
    Out> True;

##### See Also:

Integer .

###

IsPositiveReal -- Test whether argument is numerically positive

Standard math library

##### Calling Sequence:

IsPositiveReal(expr)

##### Parameters:

expr - expression to test

##### Description:

This function tries to approximate "expr" numerically. It returns `True` if this approximation is positive. In case no approximation can be found, the function returns `False`. Note that round-off errors may cause incorrect results.

##### Examples:

    In> IsPositiveReal(Sin(1)-3/4);
    Out> True;
    In> IsPositiveReal(Sin(1)-6/7);
    Out> False;
    In> IsPositiveReal(Exp(x));
    Out> False;

The last result is because `Exp(x)` cannot be numerically approximated if `x` is not known. Hence Yacas can not determine the sign of this expression.

##### See Also:

IsNegativeReal , IsPositiveNumber , N .

###

IsNegativeReal -- Test whether argument is numerically negative

Standard math library

##### Calling Sequence:

IsNegativeReal(expr)

##### Parameters:

expr - expression to test

##### Description:

This function tries to approximate "expr" numerically. It returns `True` if this approximation is negative. In case no approximation can be found, the function returns `False`. Note that round-off errors may cause incorrect results.

##### Examples:

    In> IsNegativeReal(Sin(1)-3/4);
    Out> False;
    In> IsNegativeReal(Sin(1)-6/7);
    Out> True;
    In> IsNegativeReal(Exp(x));
    Out> False;

The last result is because `Exp(x)` cannot be numerically approximated if `x` is not known. Hence Yacas can not determine the sign of this expression.

##### See Also:

IsPositiveReal , IsNegativeNumber , N .

###

IsConstant -- Test whether argument is constant

Standard math library

##### Calling Sequence:

IsConstant(expr)

##### Parameters:

expr - some expression

##### Description:

`IsConstant` returns `True` if the expression is some constant or a function with constant arguments. It does this by checking that no variables are referenced in the expression.

##### Examples:

    In> IsConstant(Cos(x))
    Out> False;
    In> IsConstant(Cos(2))
    Out> True;
    In> IsConstant(Cos(2+x))
    Out> False;

##### See Also:

IsNumber , IsInteger , VarList .

CanProve .

# Propositional logic theorem prover

###

CanProve

Standard math library

##### Calling Sequence:

CanProve(proposition)

##### Parameters:

proposition - a logical proposition

##### Description:

Yacas has a small built-in propositional logic theorem prover. It can be invoked with a call to CanProve.
An example of a proposition is 'if a implies b and b implies c then a implies c'. Yacas supports the following operators

Not negation, read as 'not'
And conjunction, read as 'and'
Or disjunction, read as 'or'
=> implication, read as 'implies'
So the above mentioned proposition would be represented by

    ( (a=>b) And (b=>c) ) => (a=>c)

Yacas can prove that is correct by applying `CanProve` to it:

    In> CanProve(( (a=>b) And (b=>c) ) => (a=>c))
    Out> True;

It does this the following way: in order to prove proposition p, it suffices to prove that Not p is false. It continues to simplify Not p using the rules

     Not  ( Not x)      --> x        eliminate double negation
    x=>y        -->  Not x  Or  y   eliminate implication
     Not (x And y)      -->  Not x  Or   Not y  De Morgan's law
     Not (x  Or  y)    -->  Not x  And   Not y  De Morgan's law
    (x  And  y)  Or  z --> (x Or z) And (y Or z)  Distribution
    x  Or  (y  And  z) --> (x Or y) And (x Or z)  Distribution

And the obvious other rules: 'True Or x --> True' etc. The above rules will translate the proposition into a form

    (p1  Or  p2  Or  ...)  And  (q1  Or  q2  Or  ...)  And ...

If any of the clauses is false, the entire expression will be false. In the next step, clauses are scanned for situations of the form:

    (p Or Y)  And  ( Not p Or Z) --> (Y Or Z)

If this combination `(Y Or Z)` is empty, it is false, and thus the entire proposition is false.

As a last step, the algorithm negates the result again. This has the added advantage of simplifying the expression further.

##### Examples:

    In> CanProve(a  Or   Not a)
    Out> True;
    In> CanProve(True  Or  a)
    Out> True;
    In> CanProve(False  Or  a)
    Out> a;
    In> CanProve(a  And   Not a)
    Out> False;
    In> CanProve(a  Or b Or (a And b))
    Out> a Or b;

##### See Also:

True , False , And , Or , Not .

% , True, False , EndOfFile , Infinity , Pi , Undefined .

# Constants

###

% -- Previous result

Internal function

##### Calling Sequence:

%

##### Parameters:

##### Description:

% 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 functionality offered by the LazyGlobal command).

Typical examples are `Simplify(%)` and `PrettyForm(%)`to simplify and show the result in a nice form respectively.

##### Examples:

    In> Taylor(x,0,5)Sin(x)
    Out> x-x^3/6+x^5/120;
    In> PrettyForm(%)

         3    5
        x    x
    x - -- + ---
        6    120

##### See Also:

LazyGlobal .

###

True, False -- Boolean constants

Internal function

##### Calling Sequence:

True
False

##### Description:

`True` and `False` are typically the result of boolean expressions like `2 < 3` and `True And False`.

##### See Also:

And , Or , Not .

###

EndOfFile -- End-of-file marker

Internal function

##### Calling Sequence:

EndOfFile

##### Description:

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.

###

Infinity -- Constant representing mathematical infinity

Standard math library

##### Calling Sequence:

Infinity

##### Description:

Infinity represents infinity. It can be the result of certain calculations.

Note that for most analytic functions Yacas understands Infinity. Thus `Infinity*2` will return Infinity, and `a < Infinity` will evaluate to True.

##### Examples:

    In> 2*Infinity
    Out> Infinity;
    In> 2 True;

###

Pi -- Mathematical constant, 3.14159...

Standard math library

##### Calling Sequence:

Pi

##### Description:

Pi represents the value of pi. When the N(..) function is used, Pi is set to the correct value. It is probably better to use Pi than Pi(), for simplification purposes.

##### Examples:

    In> Sin(3*Pi/2)
    Out> -1;
    In> Pi
    Out> Pi;
    In> N(Pi)
    Out> 3.1415926535;

##### See Also:

Sin , Cos .

###

Undefined -- Constant signifying an undefined result

Standard math library

##### Calling Sequence:

Undefined

##### Description:

Undefined is a token that can be returned by a function when it considers its input to be invalid. The resulting output is then undefined.

##### Examples:

    In> 2*Infinity
    Out> Infinity;
    In> 0*Infinity
    Out> Undefined;

##### See Also:

Infinity .

:= , Set , Clear , ++ , -- , Object , LazyGlobal , UniqueConstant .

# Variables

###

:= -- Assignment

Standard math library

##### Calling sequence:

var := exp
{var, ...} := {exp, ...}
var[i] := exp
fn(param, ...) := exp (all prec. 1000)

##### Parameters:

var - variable which should be assigned
exp - expression to assign to the variable
i - index (can be integer or string)
fn - name of a function to define
param - argument of the function "fn"

##### Description:

As one can see above, the `:=` operator can be used in a number of ways. In all cases, some sort of assignment takes place.

The first 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 second form is a small extension, which allows one to do multiple assignments. The first entry in the list on the right-hand side is assigned to the first variable mentionedon the left-hand side, the second entry on the right-hand side to the second variable on the left-hand side, etcetera. 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 assigment and the result of the assignment is `True`.

The last form defines a function. For example, the assignment `f(x) := x^2` removes all rules associated with `f(x)` and defines the rule `f(_x) <-- x^2`. Note that the left-hand side may take a different form if "f" is defined to be a prefix, infix or bodied function. This case is a bit special since the right-hand side is not evaluated immediately, but only if the function "f" is used. If this takes time, it may be better to force an immediate evaluation with `Eval` (see the last example).

##### Examples:

A simple assignment:

    In> a := Sin(x) + 3;
    Out> Sin(x)+3;
    In> a;
    Out> Sin(x)+3;

Multiple assignments:

    In> {a,b,c} := {1,2,3};
    Out> {1,2,3};
    In> a;
    Out> 1;
    In> b+c;
    Out> 5;

Assignment to a list:

    In> xs := { 1,2,3,4,5 };
    Out> {1,2,3,4,5};
    In> xs[3] := 15;
    Out> True;
    In> xs;
    Out> {1,2,15,4,5};

Building an associative list:

    In> alist := {};
    Out> {};
    In> alist["cherry"] := "red";
    Out> True;
    In> alist["banana"] := "yellow";
    Out> True;
    In> alist["cherry"];
    Out> "red";
    In> alist;
    Out> {{"banana","yellow"},{"cherry","red"}};

Defining a function:

    In> f(x) := x^2;
    Out> True;
    In> f(3);
    Out> 9;
    In> f(Sin(a));
    Out> Sin(a)^2;

    In> Infix("*&*",10);
    Out> True;
    In> x1 *&* x2 := x1/x2 + x2/x1;
    Out> True;
    In> Sin(a) *&* Cos(a);
    Out> Tan(1)+Cos(1)/Sin(1);
    In> Clear(a);
    Out> True;
    In> Sin(a) *&* Exp(a);
    Out> 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 function `f` is called.

    In> f(a) := Taylor(x,0,25) Sin(x);
    Out> True;
    In> f(1);
    Out> x-x^3/6+x^5/120-x^7/5040+x^9/362880-x^11/39916800+x^13/6227020800-x^15/1307
    674368000+x^17/355687428096000-x^19/121645100408832000+x^21/51090942171709440000
    -x^23/25852016738884976640000+x^25/15511210043330985984000000;
    In> f(2);
    Out> x-x^3/6+x^5/120-x^7/5040+x^9/362880-x^11/39916800+x^13/6227020800-x^15/1307
    674368000+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));
    Out> True;
    In> f(1);
    Out> x-x^3/6+x^5/120-x^7/5040+x^9/362880-x^11/39916800+x^13/6227020800-x^15/1307
    674368000+x^17/355687428096000-x^19/121645100408832000+x^21/51090942171709440000
    -x^23/25852016738884976640000+x^25/15511210043330985984000000;
    In> f(2);
    Out> x-x^3/6+x^5/120-x^7/5040+x^9/362880-x^11/39916800+x^13/6227020800-x^15/1307
    674368000+x^17/355687428096000-x^19/121645100408832000+x^21/51090942171709440000
    -x^23/25852016738884976640000+x^25/15511210043330985984000000;

##### See Also:

Set , Clear , [] , Rule , Infix , Eval .

###

Set -- Assignment

Internal function

##### Calling Sequence:

Set(var, exp)

##### Parameters:

var - variable which should be assigned
exp - expression to assign to the variable

##### Description:

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 `Set(var, exp)` is equivalent to `var := exp`, but the `:=` operator has more uses like changing individual entries in a list.

##### Examples:

    In> Set(a, Sin(x)+3);
    Out> True;
    In> a;
    Out> Sin(x)+3;

##### See Also:

Clear , := .

###

Clear -- Undo an assignment

Internal function

##### Calling Sequence:

Clear(var, ...)

##### Parameters:

var - name of variable to be cleared

##### Description:

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). The result of the expression is True.

##### Examples:

    In> a := 5;
    Out> 5;
    In> a^2;
    Out> 25;

    In> Clear(a);
    Out> True;
    In> a^2;
    Out> a^2;

##### See Also:

Set , := .Internal function

##### Calling Sequence:

Local(var, ...)

##### Parameters:

var - name of variable to be declared as local

##### Description:

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 Yacas 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 `Prog` 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`.

##### Examples:

    In> a := 3;
    Out> 3;

    In> [ a := 4; a; ];
    Out> 4;
    In> a;
    Out> 4;

    In> [ Local(a); a := 5; a; ];
    Out> 5;
    In> a;
    Out> 4;

In the first block, `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.

##### See Also:

LocalSymbols , Prog , [] , UnFence .

###

++ -- Increment variable

Standard math library

##### Calling Sequence:

var++

##### Parameters:

var - variable to increment

##### Description:

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`, except that the assignment returns the new value of `x` while `x++` always returns true. In this respect, Yacas' `++` differs from the corresponding operator in the programming language C.

##### Examples:

    In> x := 5;
    Out> 5;
    In> x++;
    Out> True;
    In> x;
    Out> 6;

##### See Also:

-- , := .

###

-- -- Decrement variable

Standard math library

##### Calling Sequence:

var--

##### Parameters:

var - variable to decrement

##### Description:

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`, except that the assignment returns the new value of `x` while `x--` always returns true. In this respect, Yacas' `--` differs from the corresponding operator in the programming language C.

##### Examples:

    In> x := 5;
    Out> 5;
    In> x--;
    Out> True;
    In> x;
    Out> 4;

##### See Also:

++ , := .

###

Object -- Create an incomplete type

Standard math library

##### Calling Sequence:

Object("pred", exp)

##### Parameters:

pred - name of the predicate to apply
exp - expression on which "pred" should be applied

##### Description:

This function returns "obj" as soon as "pred" returns `True` when applied on "obj". This is used to declare so-called incomplete types.

##### Examples:

    In> a := Object("IsNumber", x);
    Out> Object("IsNumber",x);
    In> Eval(a);
    Out> Object("IsNumber",x);
    In> x := 5;
    Out> 5;
    In> Eval(a);
    Out> 5;

##### See Also:

IsNonObject .

###

LazyGlobal -- Global variable is to be evaluated lazily

Internal function

##### Calling Sequence:

LazyGlobal(var)

##### Parameters:

var - variable (held argument)

##### Description:

LazyGlobal enforces that a global variable will re-evaluate when used. The global variable needs to exist for this function to work. Also, this functionality doesn't survive if Clear(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 LazyGlobal property only holds once: after that, the result of evaluation is stored in the global variable, and it won't be reevaluated again:

    In> a:=Hold(Taylor(x,0,30)Sin(x))
    Out> Taylor(x,0,30)Sin(x);
    In> LazyGlobal(a)

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. LazyGlobal is called for "%" each time "%" changes.

##### Examples:

    In> a:=Hold(2+3)
    Out> 2+3;
    In> a
    Out> 2+3;
    In> LazyGlobal(a)
    Out> True;
    In> a
    Out> 5;

##### See Also:

Set , Clear , Local , % , I .

###

UniqueConstant -- Create a unique identifier

Standard math library

##### Calling Sequence:

UniqueConstant()

##### Parameters:

none

##### Description:

This function 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.

##### Examples:

    In> UniqueConstant()
    Out> C9
    In>  UniqueConstant()
    Out> C10

##### See Also:

LocalSymbols .

FullForm , Echo , PrettyForm , EvalFormula , Write , WriteString , Space , NewLine , FromFile , FromString , ToFile , ToString , Read , LispRead , ReadToken , Load , Use , DefLoad , FindFile , PatchLoad , Nl .

# Input/Output

This chapter contains command to use for input and output. All output commands write to the same destination, called the "current output". This is initially the screen, but the current output is redirected by some commands. Similarly, most input commands read from the "current input", which can also be redirected. The exception to this rule are the commands for reading in script files, which simply read the specified file.

###

FullForm -- Print an expression in LISP-format

Internal function

##### Calling Sequence:

FullForm(expr)

##### Parameters:

expr - The expression to be printed in LISP-format

##### Description:

Evaluates "expr", and prints it in LISP-format on the current output. It is followed by a newline. The evaluated expression is also returned. This can be useful if you want to study the internal representation of a certain expression.

##### Examples:

    In> FullForm(a+b+c);
    (+ (+ a b )c )
    Out> a+b+c;
    In> FullForm(2*I*b^2);
    (* (Complex 0 2 )(^ b 2 ))
    Out> 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 Also:

LispRead , Listify , Unlist .

###

Echo -- High-level printing routine

Standard math library

##### Calling Sequence:

Echo(item)
Echo(list)

##### Parameters:

item - the item to be printed
list - a list of items to be printed

##### Description:

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 the second calling sequence is used, Echo will print all the entries in the list subsequently to the current output, followed by a newline. Any strings in the list are printed without quotation marks. All other entries are followed by a space.

Echo always returns True.

##### Examples:

    In> Echo(5+3);
     8
    Out> True;
    In> Echo({"The square of two is ", 2*2});
    The square of two is  4
    Out> True;

Note that one must use the second calling sequence if one wishes to print a list:

    In> Echo({a,b,c});
    a  b  c
    Out> True;
    In> Echo({{a,b,c}});
    {a,b,c}
    Out> True;

##### See Also:

PrettyForm , Write , WriteString .

###

PrettyForm -- Print an expression nicely with ASCII art

Standard math library

##### Calling Sequence:

PrettyForm(expr)

##### Parameters:

expr - an expression

##### Description:

PrettyForm 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> Taylor(x,0,9)Sin(x)
    Out> x-x^3/6+x^5/120-x^7/5040+x^9/362880;
    In> PrettyForm(%)

         3    5      7       9
        x    x      x       x
    x - -- + --- - ---- + ------
        6    120   5040   362880

    Out> True;

##### See Also:

EvalFormula , PrettyPrinter .

###

EvalFormula -- Print an evaluation nicely with ASCII art

Standard math library

##### Calling Sequence:

EvalFormula(expr)

##### Parameters:

expr - an expression

##### Description:

Show an evaluation in a nice way, using PrettyPrinter to show 'input = output'.

##### Examples:

    In> EvalFormula(Taylor(x,0,7)Sin(x))

                                          3    5      7
                                         x    x      x
    Taylor( x , 0 , 7 , Sin( x ) ) = x - -- + --- - ----
                                         6    120   5040

    Out> True

##### See Also:

PrettyForm .

###

Write -- Low-level printing routine

Internal function

##### Calling Sequence:

Write(expr, ...)

##### Parameters:

expr - the expression to be printed

##### Description:

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.

##### Examples:

    In> Write(1);
    1Out> True;
    In> Write(1,2);
     1 2Out> True;

Write does not write a newline, so the `Out>` prompt immediately follows the output of Write.

##### See Also:

Echo , WriteString .

###

WriteString -- Low-level printing routine for strings

Internal function

##### Calling Sequence:

WriteString(string)

##### Parameters:

string - the string to be printed

##### Description:

The expression "string" is evaluated and written to the current output without quotation marks. The argument should be a string. WriteString always returns True.

##### Examples:

    In> Write("Hello, world!");
    "Hello, world!"Out> True;
    In> WriteString("Hello, world!");
    Hello, world!Out> True;

This example clearly shows the difference between Write and WriteString. Note that Write and WriteString do not write a newline, so the `Out>` prompt immediately follows the output.

##### See Also:

Echo , Write .

###

Space -- Print one or more spaces

Standard math library

##### Calling Sequence:

Space()
Space(nr)

##### Parameters:

nr - the number of spaces to print

##### Description:

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.

##### Examples:

    In> Space(5);
         Out> True;

##### See Also:

Echo , Write , NewLine .

###

NewLine -- Print one or more newline characters

Standard math library

##### Calling Sequence:

NewLine()
NewLine(nr)

##### Parameters:

nr - the number of newlines to print

##### Description:

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.

##### Examples:

    In> NewLine();

    Out> True;

##### See Also:

Echo , Write , Space .

###

FromFile -- Connect current input to a file

Internal function

##### Calling Sequence:

FromFile(name) body

##### Parameters:

name - the name of the file to read
body - the command to be executed

##### Description:

The current input is connected to the file "name". Then the command "body" is executed. Everything that the commands in "body" read from current input, is now read from the file "name". Finally, the file is closed and the result of evaluating "body" is returned.

##### Examples:

Suppose that the file `foo` contains

    2 + 5;

Then we can have the following dialogue:

    In> FromFile("foo") res := Read();
    Out> 2+5;
    In> FromFile("foo") res := ReadToken();
    Out> 2;

##### See Also:

ToFile , FromString , Read , ReadToken .

###

FromString -- Connect current input to a string

Internal function

##### Calling Sequence:

FromString(str) body;

##### Parameters:

str - a string containing the text to parse
body - the command to be executed

##### Description:

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.

##### Examples:

    In> FromString("2+5; this is never read") res := Read();
    Out> 2+5;
    In> FromString("2+5; this is never read") res := Eval(Read());
    Out> 7;

##### See Also:

ToString , FromFile , Read , ReadToken .

###

ToFile -- Connect current output to a file

Internal function

##### Calling Sequence:

ToFile(name) body

##### Parameters:

name - the name of the file to write the result to
body - the command to be executed

##### Description:

The current output is connected to the file "name". Then the command "body" is executed. 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.

##### Examples:

Take first a look at the following command:

    In> [ Echo("Result:");  PrettyForm(Taylor(x,0,9) Sin(x)); ];
    Result:

         3    5      7       9
        x    x      x       x
    x - -- + --- - ---- + ------
        6    120   5040   362880

    Out> True;

Now suppose one wants to send the output of this command to a file. This can be achieved as follows:

    In> ToFile("out") [ Echo("Result:");  PrettyForm(Taylor(x,0,9) Sin(x)); ];
    Out> True;

After this command the file `out` contains:

    Result:

         3    5      7       9
        x    x      x       x
    x - -- + --- - ---- + ------
        6    120   5040   362880

##### See Also:

FromFile , ToString , Echo , Write , WriteString , PrettyForm , Taylor .

###

ToString -- Connect current output to a string

Internal function

##### Calling Sequence:

ToString() body

##### Parameters:

body - the command to be executed

##### Description:

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.

##### Examples:

    In> str := ToString() \
    In>        [ WriteString("The square of 8 is "); Write(8^2); ];
    Out> "The square of 8 is  64";

##### See Also:

FromFile , ToString , Echo , Write , WriteString .

###

Read -- Read an expression from current input

Internal function

##### Calling Sequence:

Read()

##### Parameters:

none

##### Description:

Read an expression from the current input, and return it unevaluated. When the end of an input file is encountered, the token atom `EndOfFile` is returned.

##### Examples:

    In> FromString("2+5;") Read();
    Out> 2+5;
    In> FromString("") Read();
    Out> EndOfFile;

##### See Also:

FromFile , FromString , LispRead , ReadToken , Write .

###

LispRead -- Read an expression in LISP-syntax

Internal function

##### Calling Sequence:

LispRead()

##### Parameters:

none

##### Description:

Read an expression in LISP syntax from the current input, and return it unevaluated. When the end of an input file is encountered, the token atom `EndOfFile` is returned.

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

##### Examples:

    In> FromString("(+ a b)") LispRead();
    Out> a+b;
    In> FromString("(List (Sin x) (- (Cos x)))") LispRead();
    Out> {Sin(x),-Cos(x)};

##### See Also:

FromFile , FromString , Read , ReadToken , FullForm .

###

ReadToken -- Read an token from current input

Internal function

##### Calling Sequence:

ReadToken()

##### Parameters:

none

##### Description:

Read a token from the current input, and return it unevaluated. 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`.

##### Examples:

    In> FromString("a := Sin(x)") \
    In>    While((tok := ReadToken()) != EndOfFile) Echo(tok);
    a
    :=
    Sin
    (
    x
    )
    Out> True;

##### See Also:

FromFile , FromString , Read , LispRead .

###

Load -- Evaluate all expressions in a file

Internal function

##### Calling Sequence:

Load(name)

##### Parameters:

name - name of the file to load

##### Description:

The file "name" is opened. All expressions in the file are read and evaluated. `Load` always returns `true`.

##### See Also:

Use , DefLoad , DefaultDirectory , FindFile .

###

Use -- Load a file, but not twice

Internal function

##### Calling Sequence:

Use(name)

##### Parameters:

name - name of the file to load

##### Description:

If the file "name" has been loaded before, either by an earlier call to `Use` or via the `DefLoad` mechanism, nothing happens. Otherwise all expressions in the file are read and evaluated. `Use` always returns `true`.

The purpose of this function is to make sure that the file will at least have been loaded, but is not loaded twice.

##### See Also:

Load , DefLoad , DefaultDirectory .

###

DefLoad -- Load a .def file

Internal function

##### Calling Sequence:

DefLoad(name)

##### Parameters:

name - name of the file (without `.def` suffix)

##### Description:

The suffix `.def` is appended to "name" and the file with this name is loaded. It should contain a list of functions, terminated by a `}` (end-of-list character). This tells the system to load the file "name" as soon as the user calls one of the functions named in the file (if not done so already). This allows for faster startup times, since not all of the rules databases need to be loaded, just the descriptions on which files to load for which functions.

##### See Also:

Load , Use , DefaultDirectory .

###

FindFile -- Find a file in the current path

Internal function

##### Calling Sequence:

FindFile(name)

##### Parameters:

name - name of the file to find

##### Description:

The result of this command is the full path to the file that would be opened when the command `Load(name)` would be invoked. This means that the input directories are subsequently searched for a file called "name". If such a file is not found, `FindFile` returns an empty string.

##### See Also:

Load , DefaultDirectory .

###

PatchLoad -- Execute commands between <? and ?> in file

Internal function

##### Calling Sequence:

PatchLoad(name)

##### Parameters:

name - the file to patch

##### Description:

PatchLoad loads in a file and outputs the contents to the current output. The file can contain blocks delimited by <? and ?> (meaning Yacas Begin and Yacas End). The piece of text between such delimiters is treated as a separate file with Yacas instructions, which is then loaded and executed. All output of write statements in that block will be written to the same current output.

This is similar to the way php works. You can have a static text file with dynamic content generated by Yacas.

##### See Also:

PatchString , Load .

###

Nl -- A newline character

Standard math library

##### Calling Sequence:

Nl()

##### Description:

This function returns a string with one element in it, namely a newline character. This may be useful for building strings to send to some output in the end.

Note that the second letter in the name of this command is a lower case `L` (from "line").

##### Examples:

    In> WriteString("First line" : Nl() : "Second line" : Nl());
    First line
    Second line
    Out> True;

##### See also:

NewLine .

SetStringMid , StringMid , String, Atom , ConcatStrings , LocalSymbols , PatchString .

# String manipulation

###

SetStringMid -- Change a substring

Internal function

##### Calling Sequence:

SetStringMid(index,substring,string)

##### Parameters:

index - index of substring to get
substring - substring to store
string - string to store substring in.

##### Description:

Set (change) a part of a string. It leaves the original alone, returning a new changed copy.

##### Examples:

    In> SetStringMid(3,"XY","abcdef")
    Out> "abXYef";

##### See Also:

StringMid , Length .

###

StringMid -- Retrieve a substring

Internal function

##### Calling Sequence:

StringMid(index,length,string)

##### Parameters:

index - index of substring to get
length - length of substring to get
string - string to get substring from

##### Description:

StringMid returns a part of a string. Substrings can also be accessed using the [] operator.

##### Examples:

    In> StringMid(3,2,"abcdef")
    Out> "cd";
    In> "abcdefg"[2 .. 4]
    Out> "bcd";

##### See Also:

SetStringMid , Length .

###

String, Atom -- Convert atom to string and vice versa

Internal function

##### Calling Sequence:

Atom(string)
String(atom)

##### Parameters:

atom - an atom
string - a string

##### Description:

Atom(string) : Returns an atom with the string representation given as the evaluated argument. Example: "Atom("foo");" returns foo.

String is the inverse of Atom: turns atom into "atom".

##### Examples:

    In> String(a)
    Out> "a";
    In> Atom("a")
    Out> a;

###

ConcatStrings -- Concatenate strings

Internal function

##### Calling Sequence:

ConcatStrings(strings)

##### Parameters:

strings - one or more strings

##### Description:

ConcatStrings concatenates strings. Example: "ConcatStrings("a","b","c");" will return "abc".

##### Examples:

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

##### See Also:

: .

###

LocalSymbols -- Create unique local symbols with given prefix

Standard math library

##### Calling Sequence:

LocalSymbols(...)body

##### Parameters:

... - list of symbols
body - expression to execute

##### Description:

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 $, where symbol was the symbol entered by the user, and number is a unique number. This scheme was used to such a generated symbol can not accientally be entered by a user.

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

##### Examples:

    In> LocalSymbols(a,b)a+b
    Out> $a6+ $b6;

##### See Also:

UniqueConstant .

###

PatchString -- Execute commands between <? and ?> in string

Internal function

##### Calling Sequence:

PatchString(string)

##### Parameters:

string - a string to patch

##### Description:

This function does the same as PatchLoad, but it works on a string in stead of on the contents of a text file. See PatchLoad for more details.

##### Examples:

    In> PatchString("Two plus three is <? Write(2+3); ?> ");
    Out> "Two plus three is 5 ";

##### See Also:

PatchLoad .

Prog , Check , Prefix , Postfix , Bodied , Infix , IsInfix , IsPrefix , IsPostfix , OpPrecedence , RightAssociative , LeftPrecedence , RightPrecedence , RuleBase , Rule , HoldArg , Retract , UnFence , MacroSet , MacroClear , MacroLocal , MacroRuleBase , MacroRule , Secure .

# Programming

###

/* comment */

A comment block in a source file.

###

Prog(...)

Prog(...) : Evaluate the arguments in order, and return the result of the last evaluated expression. This is the same as the "[ ... ]" constuct, that is, "Prog(a,b);" is the same as typing "[a;b;];" and is very useful for writing out function bodies (the "[...]" construct is converted into "Prog(...)" during the parsing stage)

###

Check(predicate,"error")

Check(predicate,"error") : If "predicate" doesn't evaluate to "True", then current operation will be stopped, and execution will jump right back to the command line, showing "error". Use this to assure that some condition is met during evaluation of expressions (guarding against internal errors).

###

Prefix("operator")

Prefix("operator") : Defines a new operator for the prefix parser to understand. This function can also be called with an additional argument for the precedence of the prefix operator.

###

Postfix("oper")

Postfix("oper") : Defines a new operator for the postfix parser to understand.

###

Bodied("oper",precedence)

Bodied("oper",precedence) : Defines a new operator for the bodied parser to understand.

###

Infix("oper",precedence)

Infix("oper",precedence) : Defines a new operator for the infix parser to understand. "precedence" is evaluated.

###

IsInfix("str"), IsPrefix("str"), IsPostfix("str")

Returns wether str is an infix, prefix, or postfix operator. IsInfix("+") should return True. IsInfix("a") should return False.

###

OpPrecedence("str")

Returns the precedence of the infix operator str. OpPrecedence("+") should return 6.

###

RightAssociative("operator")

makes the operator right-associative. Example: RightAssociative("*") would make multiplication right-associative. Take care not to abuse this function, because the reverse, making an infix operator left-associative, is not implemented.

###

LeftPrecedence("oper",precedence), RightPrecedence("oper",precedence)

oper should be an infix operator. This function call tells the infix expression printer to bracket the left or right hand side of the expression if its precedence is larger than precedence. This functionality was required in order to display a-(b-c) correctly. a+b+c is the same as a+(b+c), but a-(b-c) is not the same as a-b-c.

###

RuleBase("operator",{params})

RuleBase("operator",{params}) : Define a new rules table entry for a function "operator", with {params} as the parameter list.

###

Rule("operator",arity,precedence,predicate) body

Rule("operator",arity,precedence,predicate) body : Define a rule for the function "operator" with "arity", "precedence", "predicate" and "body". "precedence" is checked from low to high. The arity for a rules database equals the number of arguments. Different rules data bases can be built for functions with the same name but with a different number of arguments. Rules with a low 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.

###

HoldArg("operator",parameter)

HoldArg("operator",parameter) : Specify that parameter (which should be part of a parameter list for a function "operator") should not be evaluated before used. This will be declared for all arities of "operator", at the moment this function is called, so it is best called after all RuleBase calls for this operator.

###

Retract("operator",arity)

Retract("operator",arity) : Remove a rulebase with some specific arity, if it exists at all.

###

UnFence("operator",arity)

UnFence("operator",arity) : When applied to a user function, the bodies defined for the rules for "operator" with given arity can see the local variables from the calling function. This is useful for defining macro-like procedures (looping and the such). The For and ForEach functions defined in the standard packages use this, for instance.

###

MacroSet, MacroClear,MacroLocal, MacroRuleBase,MacroRule

Same as their non-macro counterparts, except that their arguments are evaluated before the required action is performed. This is useful in macro-like procedures.

###

Secure(body)

Secure evaluates body in a safe environment, where file opening and system calls are not allowed. This can protect the system when an unsafe evaluation is done (Like a script sent over the internet to be evaluated on a computer).

MathNot , MathAnd , MathOr , BitAnd , BitOr , BitXor , Equals , LessThan , GreaterThan , ShiftLeft , ShiftRight .

# Built-in functions

###

MathNot(expression)

MathNot(expression) : Returns "False" if "expression" evaluates to "True", and vice versa.

###

MathAnd(...)

MathAnd(...) : Lazy and: returns True" if all args evaluate to "True", and does this by looking at first, and then at the second argument, until one is "False". If one is "False" it immediately returns "False" without evaluating the rest. This is faster, but also means that none of the arguments should cause side effects when they are evaluated.

###

MathOr(...)

MathOr(...) : MathOr is the or equivalent of And. It is lazy-evaluated too. "And(...)" and "Or(...)" do also exist. You can define 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 And expr".

###

BitAnd(n,m), BitOr(n,m), BitXor(n,m)

BitAnd(n,m), BitOr(n,m), BitXor(n,m) : return bitwise and, or and xor of two numbers.

###

Equals(a,b)

Equals(a,b) : Compares evaluated a and b recursively (stepping into expressions). so "Equals(a,b)" returns "True" if the expressions would be printed exactly the same, and "False" otherwise.

###

LessThan(a,b), GreaterThan(a,b)

LessThan(a,b), GreaterThan(a,b) : Comparing numbers.

###

Math...

MathGcd(n,m) (Greatest Common Divisor), MathAdd(x,y), MathSubtract(x,y), MathMultiply(x,y), MathDivide(x,y), MathSqrt(x) (Square root), MathFloor(x), MathCeil(x), MathAbs(x), MathMod(x,y), MathExp(x), MathLog(x) (Natural logarithm), MathPower(x,y), MathSin(x), MathCos(x), MathTan(x), MathArcSin(x), MathArcCos(x), MathArcTan(x), MathDiv(x,y), MathMod(x,y) : MathSqrt(x) (Square root), Calculation of sin,cos,tan etc. of x. x HAS to be a number. The reason Math is prepended to the names is you might want to derive equivalent non-evaluating functions. The Math... versions require the arguments to be numbers.

###

Fast...

FastExp(x), FastLog(x) (Natural logarithm), FastPower(x,y), FastSin(x), FastCos(x), FastTan(x), FastArcSin(x), FastArcCos(x), FastArcTan(x) : Versions of these functions using the internal c version. These should then at least be faster than the arbitrary precision versions.

###

ShiftLeft(number,bits), ShiftRight(number,bits)

ShiftLeft(number,bits), ShiftRight(number,bits) : Shift number bits to left or right.

DllLoad , StubApiCStart , StubApiCShortIntegerConstant , StubApiCInclude , StubApiCFunction , StubApiCRemark , StubApiCSetEnv , StubApiCFile , StubApiCStruct .

# The Yacas plugin structure

Yacas supports dynamically loading libraries at runtime. This allows it to interface with other libraries that support additional functionality. For example, there could be a plugin enabling the user to script a user interface from within Yacas, or a specific powerful library to do numeric calculations.

The plugin feature is currently in an experimental stage. There are some examples in the plugins/ directory. These are not built by default because they cannot be guaranteed to compile on every platform (yet). The plugins need to be compiled after Yacas itself has been compiled and installed successfully. The plugins/ directory contains a README file with more details on compilation.

In addition to the plugin structure in the Yacas engine, there is a 'cstubgen' module (currently still in development) that allows rapid scripting of a plugin. Essentially all that is required is to write a file that looks like the header file of the original library, but written in Yacas syntax. the 'cstubgen' module is then able to write out a c++ file that can be compiled and linked with the original library, and then loaded from within Yacas. Including a function in the plugin will typically take just one line of Yacas code. There are a few examples in the plugins/ directory (the files ending with api.stub). The make file makefile.plugin is configured to automatically convert these to the required c++ files.

In addition to the c++ stub file cstubgen also automatically generates some documentation on the functions included in the stub. This documentation is put in a file with extension 'description'.

The plugin facility is not supported for each platform yet. Specifically, it is only supported on platforms that support the elf binary format. (loading DLLs is platform-dependent).

This chapter assumes the reader is comfortable programming in c++.

###

DllLoad

Internal function

##### Calling Sequence:

DllLoad(file)

##### Parameters:

file - file name of the plugin

##### Description:

DllLoad forces Yacas to load the dynamic link library (.so file under Linux). The full path to the DLL has to be specified, or the file needs to be in a path where dlopen can find it.

##### Examples:

    In> DllLoad("./libopengl.so");
    Out> True;

##### See Also:

###

StubApiCStart

Standard math library

##### Calling Sequence:

StubApiCStart()

##### Parameters:

##### Description:

To start up generating a c stub file for linking a c library with Yacas. A stub specification file needs to start with this function call, to reset the internal state of Yacas for emitting a stub c++ file.

##### See Also:

StubApiCShortIntegerConstant , StubApiCInclude , StubApiCFunction , StubApiCFile , StubApiCSetEnv .

###

StubApiCShortIntegerConstant

Standard math library

##### Calling Sequence:

StubApiCShortIntegerConstant(const,value)

##### Parameters:

const - string representing the global variable to be bound runtime
value - integer value the global should be bound to

##### Description:

define a constant 'const' to have value 'value'. The value should be short integer constant. This is useful for linking in defines and enumerated values into Yacas. If the library for instance has a define
#define FOO 10
Then
StubApiCShortIntegerConstant("FOO","FOO")
will bind the global variable FOO to the value for FOO defined in the library header file.

##### See Also:

StubApiCStart , StubApiCInclude , StubApiCFunction , StubApiCFile , StubApiCSetEnv .

###

StubApiCInclude

Standard math library

##### Calling Sequence:

StubApiCInclude(file)

##### Parameters:

file - file to include from the library the plugin is based on

##### Description:

Declare an include file (a header file for the library, for instance) The delimiters need to be specified too. So, for a standard library like the one needed for opengl, you need to specify
StubApiCInclude("<GL/gl.h>")
and for user include file: StubApiCInclude("\"GL/gl.h\"")

##### See Also:

StubApiCStart , StubApiCShortIntegerConstant , StubApiCFunction , StubApiCFile , StubApiCSetEnv .

###

StubApiCFunction

Standard math library

##### Calling Sequence:

StubApiCFunction(returntype,fname,args)
StubApiCFunction(returntype,fname,fname2,args)

##### Parameters:

returntype - return type of library function
fname - function of built-in function
fname2 - (optional) function name to be used from within Yacas
args - list of arguments to the function

##### Description:

This function declares a library function, along with its calling sequence. cstubgen will then generate the c++ code required to call this function.

Return type, function name, and list of arguments should be literal strings (surrounded by quotes).

If fname2 is not supplied, it will be assumed to be the same as fname.

The return types currently supported are "int", "double" and "void". The argument values that are currently supported are "int", "double", and "input_string". Argument types can be specified simply as a string referring to their type, like "int", or they can be lists with an additional element stating the name of the variable: {"int","n"}. The variable will then show up in the automatically generated documentation as having the name n.

##### Examples:

To define the opengl function glVertex3d that accepts three doubles and returns void:

    StubApiCFunction("void","glVertex3d",{"double","double","double"});

##### See Also:

StubApiCStart , StubApiCShortIntegerConstant , StubApiCInclude , StubApiCFile , StubApiCSetEnv .

###

StubApiCRemark

Standard math library

##### Calling Sequence:

StubApiCRemark(string)

##### Parameters:

string - remark string to be added to the documentation

##### Description:

StubApiCRemark adds a piece of text to the stub documentation file that gets generated automatically. The documentation is put in a .description file while the input file is being processed, so adding a remark on a function just after a function declaration adds a remark on that function.

##### See Also:

StubApiCShortIntegerConstant , StubApiCInclude , StubApiCFunction , StubApiCSetEnv , StubApiCFile .

###

StubApiCSetEnv

Standard math library

##### Calling Sequence:

StubApiCSetEnv(func)

##### Parameters:

func - function to call to set the environment variable

##### Description:

This function forces the plugin to call the function func, with as argument LispEnvironment& aEnvironment. This lets the plugin store the environment class (which is needed for almost any thing to do with Yacas), somewhere in a global variable. aEnvironment can then be used from within a callback function in the plugin that doesn't take the extra argument by design.

There needs to ba a function in the plugin somewhere of the form

    static LispEnvironment* env = NULL;
    void GlutSetEnv(LispEnvironment& aEnv)
    {
        env = &aEnv;
    }

Then calling

    StubApiCSetEnv("GlutSetEnv");

will force the plugin to call GlutSetEnv at load time. All functions in the plugin will then have access to the Yacas environment.

##### See Also:

StubApiCStart , StubApiCShortIntegerConstant , StubApiCInclude , StubApiCFunction , StubApiCFile .

###

StubApiCFile

Standard math library

##### Calling Sequence:

StubApiCFile(basename)

##### Parameters:

basename - basename for the generation of the stub file

##### Description:

Generate the c++ stub file, "basename.cc", and a documentation file named "basename.description". The descriptions are automatically generated while adding functions and constants to the stub.

##### See Also:

StubApiCStart , StubApiCShortIntegerConstant , StubApiCInclude , StubApiCFunction , StubApiCSetEnv .

###

StubApiCStruct

Standard math library

##### Calling Sequence:

StubApiCStruct(name)
StubApiCStruct(name,freefunction)

##### Parameters:

name - name of structure
freefunction - function that can be called to clean up the object

##### Description:

StubApiCStruct declares a struct in a specific library. The name should be followed by an asterisk (clearly showing it is a pointer). After that, in the stub api definition, this type can be used as argument or return type to functions to the library.

By default the struct will be deleted from memory with a normal call to free(...). This can be overriden with a function given as second argument, freefunction. This is needed in the case where there are additional operations that need to be performed in order to delete the object from memory.

##### Examples:

in a library header file, define:

    typedef struct SomeStruct
    {
      int a;
      int b;
    } SomeStruct;

Then in the stub file you can declare this struct by calling:

    StubApiCStruct("SomeStruct*")

##### See Also:

, .

IsGeneric , GenericTypeName , ArrayCreate , ArraySize , ArrayGet , ArraySet , ArrayCreateFromList , ListFromArray .

# Generic objects

Generic objects are objects that are implemented in c++, but can be accessed through the Yacas interpreter.

###

IsGeneric(object)

IsGeneric(object) : returns whether an object is a generic object type.

###

GenericTypeName(object)

GenericTypeName(object) : returns a string representation of the name of a generic object.
Example: GenericTypeName(ArrayCreate(10,1)) sould return "Array".

###

ArrayCreate(size,init)

Create an array the with size elements, all initialized to the value init.

###

ArraySize(array)

Return the size of an array (number of elements in the array).

###

ArrayGet(array,index)

Get the element at position index in the array passed. Arrays are treated as base-one, so index set to 1 would return the first element.
Arrays can also be accessed through the [] operators. So array[index] would return the same as ArrayGet(array,index).

###

ArraySet(array,index,element)

Set 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 first element.
Arrays can also be accessed through the [] operators. So array[index]:=element would do the same as ArraySet(array,index,element).

###

ArrayCreateFromList(list)

Creates an array from the contents of the list passed in.

###

ListFromArray(array)

Creates a list from the contents of the array passed in.