# Yacas user's function reference

- Startup configuration
- Arithmetic and other operations on numbers
- Calculus and elementary functions
- Special functions
- Linear Algebra
- Polynomials
- List operations
- Functional operators
- Control flow functions
- Predicates
- Propositional logic theorem prover
- Constants
- Variables
- Input/Output
- String manipulation
- Platform-dependent packages
- Programming
- Built-in (core) functions

- Full listing of core functions

- The Yacas plugin structure
- Generic objects
- The Yacas test suite

DefaultDirectory , PrettyPrinter , Help , HistorySize .

# Startup configuration

Yacas allows you to configure a few things at startup. The file `~/.yacasrc` is written in the Yacas language and will be executed when Yacas is run. The following functions can be useful in the `~/.yacasrc` file.

###

DefaultDirectory -- Add directory to path for Yacas scripts

Internal function

##### Calling format:

    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 -- Set routine to use as pretty-printer

Standard math library

##### Calling format:

PrettyPrinter(printer)

##### Parameters:

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

##### Description:

This function sets up the function printer to print out the results on the command line. This 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 -- Show documentation for some command

Standard math library

##### Calling format:

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 -- Set size of history file

Internal function

##### Calling format:

    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 hard disk. This can be overridden with this function. Passing -1 tells the system to save all lines.

##### Examples:

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

+, -, *, /, ^ , Div, Mod , Gcd , Lcm , <<, >> , FromBase, ToBase , Precision , GetPrecision , N , Rationalize , IsPrime , IsPrimePower , Factors , Factor , PAdicExpand , ContFrac , ContFracList, ContFracEval , GuessRational, NearRational , Decimal , TruncRadian , Floor , Ceil , Round , Pslq .

# Arithmetic and other operations on numbers

Besides the usual arithmetical operations, Yacas defines some more advanced operations on numbers. Many of them also work on polynomials.

###

+, -, *, /, ^ -- Arithmetic operations

Standard math library

##### Calling format:

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

###

Div, Mod -- Division with remainder

Standard math library

##### Calling format:

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

##### Parameters:

`x`, `y` - integers or univariate polynomials

##### Description:

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

If `Div(x,y)` returns "a" and `Mod(x,y)` equals "b", then these numbers satisfy x=a*y+b and 0<=b<y.

##### Examples:

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

##### See also:

Gcd , Lcm .

###

Gcd -- Greatest common divisor

Standard math library

##### Calling format:

    Gcd(n,m)
    Gcd(list)

##### Parameters:

`n`, `m` - integers or univariate polynomials

`list` - a list of all integers or all univariate polynomials

##### Description:

This function returns the greatest common divisor of "n" and "m". The gcd is the largest number that divides "n" and "m". It is also known as the highest common factor (hcf). The library code calls `MathGcd`, which is an internal function. This function implements the "binary Euclidean algorithm" for determining the greatest common divisor:

##### Routine for calculating `Gcd(n,m)`

- if n=m then return n
- if both n and m are even then return 2*Gcd(n/2,m/2)
- if exactly one of n or m (say n) is even then return Gcd(n/2,m)
- 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.

If the second calling form is used, `Gcd` will return the greatest common divisor of all the integers or polynomials in "list". It uses the identity

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

##### Examples:

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

##### See also:

Lcm .

###

Lcm -- Least common multiple

Standard math library

##### Calling format:

    Lcm(n,m)

##### Parameters:

`n`, `m` -- integers or univariate polynomials

##### Description:

This command returns the least common multiple of "n" and "m". The least common multiple of two numbers "n" and "m" is the lowest number which is an integer multiple of both "n" and "m". It is calculated with the formula:

    $$Lcm(n,m) = 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 .

###

<<, >> -- Shift operators

Standard math library

##### Calling format:

    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:

    In> 1 << 10
    Out> 1024;
    In> -1024 >> 10
    Out> -1;

###

FromBase, ToBase -- Conversion from/to non-decimal base

Internal function

##### Calling format:

    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:

`FromBase` converts "number", written in base "base", to base 10. `ToBase` converts "number", written in base 10, to base "base".

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;

The first command writes the binary number `111111` in decimal base. The second command converts `255` (in decimal base) to hexadecimal base.

##### See also:

PAdicExpand .

###

Precision -- Sets the precision

Internal function

##### Calling format:

    Precision(n)

##### Parameters:

n - new precision

##### Description:

This command sets the number of binary digits to be used in calculations. 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:

GetPrecision , N .

###

GetPrecision -- Returns the current precision

Internal function

##### Calling format:

    GetPrecision()

##### Description:

This command returns the current precision, as set by `Precision`.

##### Examples:

    In> GetPrecision();
    Out> 10;
    In> Precision(20);
    Out> True;
    In> GetPrecision();
    Out> 20;

##### See also:

Precision , N .

###

N -- Numerical approximation

Standard math library

##### Calling format:

N(expr)

N(expr, prec)

##### Parameters:

expr - expression to evaluate

prec - precision to use

##### Description:

This function forces Yacas to give a numerical approximation to the expression "expr", using "prec" digits if the second calling sequence is used, and the precision as set by `SetPrecision` otherwise. This overrides the normal behaviour, in which expressions are kept in symbolic form (eg. `Sqrt(2)` instead of `1.41421`).

Application of the `N` operator will make Yacas calculate floating point representations of functions whenever possible. 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 , Pi .

###

Rationalize -- Convert floating point numbers to fractions

Standard math library

##### Calling format:

    Rationalize(expr)

##### Parameters:

expr - an expression containing real numbers

##### Description:

This command converts every real number in the expression "expr" into a rational number. This is useful when a calculation needs to be done on floating point numbers and the algorithm is unstable. Converting the floating point numbers to rational numbers will force calculations to be done with infinite precision (by using rational numbers as representations).

It does this by finding the smallest integer n such that multiplying the number with 10^n is an integer. Then it divides by 10^n again, depending on the internal gcd calculation to reduce the resulting division of integers.

##### Examples:

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

##### See also:

IsRational .

###

IsPrime -- Test for a prime number

Standard math library

##### Calling format:

    IsPrime(n)

##### Parameters:

n - integer to test

##### Description:

This command checks whether "n", which should be a positive integer, is a prime number. A number is a prime number if it is only divisible by 1 and itself. As a special case, 1 is not a prime number.

This function essentially checks for all integers between 2 and the square root of "n" whether they divide "n", and hence may take a long time for large numbers.

##### Examples:

    In> IsPrime(1)
    Out> False;
    In> IsPrime(2)
    Out> True;
    In> IsPrime(10)
    Out> False;
    In> IsPrime(23)
    Out> True;
    In> Select("IsPrime", 1 .. 100)
    Out> {2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,
      53,59,61,67,71,73,79,83,89,97};

##### See also:

IsPrimePower , Factors .

###

IsPrimePower -- Test for a power of a prime number

Standard math library

##### Calling format:

    IsPrimePower(n)

##### Parameters:

n - integer to test

##### Description:

This command tests whether "n", which should be a positive integer, is a prime power, that is whether it is of the form p^m, with "p" prime and "m" an integer.

This function essentially checks for all integers between 2 and the square root of "n" for the largest divisor, and then tests whether "n" is a power of this divisor. So it will take a long time for large numbers.

##### Examples:

    In> IsPrimePower(9)
    Out> True;
    In> IsPrimePower(10)
    Out> False;
    In> Select("IsPrimePower", 1 .. 50)
    Out> {2,3,4,5,7,8,9,11,13,16,17,19,23,25,27,
      29,31,32,37,41,43,47,49};

##### See also:

IsPrime , Factors .

###

Factors -- Factorization

Standard math library

##### Calling format:

    Factors(x)

##### Parameters:

x - integer or univariate polynomial

##### Description:

This function decomposes the integer number "x" into a product of numbers. Alternatively, if "x" is a univariate polynomial, it is decomposed in irreducible polynomials.

The factorization is returned as a list of pairs. The first member of each pair is the factor, while the second member denotes the power to which this factor should be raised. So the factorization x=p1^n1*...*p9^n9 is returned as `{{p1,n1}, ..., {p9,n9}}`.

##### Examples:

    In> Factors(24);
    Out> {{2,3},{3,1}};
    In> Factors(2*x^3 + 3*x^2 - 1);
    Out> {{2,1},{x+1,2},{x-1/2,1}};

##### See also:

Factor , IsPrime .

###

Factor -- Factorization, in pretty form

Standard math library

##### Calling format:

    Factors(x)

##### Parameters:

x - integer or univariate polynomial

##### Description:

This function factorizes "x", like `Factors`, but it shows the result in a nicer human readable format.

##### Examples:

    In> PrettyForm(Factor(24));

     3
    2  * 3

    Out> True;
    In> PrettyForm(Factor(2*x^3 + 3*x^2 - 1));

                 2   /     1 \
    2 * ( x + 1 )  * | x - - |
                     \     2 /

    Out> True;

##### See also:

Factors , IsPrime , PrettyForm .

###

PAdicExpand -- p-adic expansion

Standard math library

##### Calling format:

    PAdicExpand(n, p)

##### Parameters:

`n` - number, or polynomial, to expand

`p` - base to expand in

##### Description:

This command computes the p-adic expansion of "n". In other words, "n" is expanded in powers of "p". The argument "n" can be either an integer or a univariate polynomial. The base "p" should be of the same type.

##### Examples:

    In> PrettyForm(PAdicExpand(1234, 10));

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

    Out> True;
    In> PrettyForm(PAdicExpand(x^3, x-1));

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

    Out> True;

##### See also:

Mod , ContFrac , FromBase , ToBase .

###

ContFrac -- continued fraction expansion

Standard math library

##### Calling format:

    ContFrac(x)
    ContFrac(x, depth)

##### Parameters:

`x` - expression to expand in continued fractions

`depth` - maximum required depth of result

##### Description:

This command returns the continued fraction expansion of `x`, which should be either a floating point number or a polynomial. If `depth` is not specified, it defaults to 6. The remainder is denoted by `rest`.

This is especially useful for polynomials, since series expansions that converge slowly will typically converge a lot faster if calculated using a continued fraction expansion.

##### Examples:

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

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

    Out> True;
    In> PrettyForm(ContFrac(x^2+x+1, 3))

           x
    ---------------- + 1
             x
    1 - ------------
           x
        -------- + 1
        rest + 1

    Out> True;

##### See also:

ContFracList , NearRational , GuessRational , PAdicExpand , N .

###

ContFracList, ContFracEval -- manipulate continued fractions

Standard math library

##### Calling format:

    ContFracList(frac)
    ContFracList(frac, depth)
    ContFracEval(list)
    ContFracEval(list, rest)

##### Parameters:

`frac` -- a number to be expanded

`depth` -- desired number of terms

`list` -- a list of coefficients

`rest` -- expression to put at the end of the continued fraction

##### Description:

The function `ContFracList` computes terms of the continued fraction representation of a rational number `frac`. It returns a list of terms of length `depth`. If `depth` is not specified, it returns all terms.

The function `ContFracEval` converts a list of coefficients into a continued fraction expression. The optional parameter `rest` specifies the symbol to put at the end of the expansion. If it is not given, the result is the same as if `rest=0`.

##### Examples:

    In> A:=ContFracList(33/7 + 0.000001)
    Out> {4,1,2,1,1,20409,2,1,13,2,1,4,1,1,3,3,2};
    In> ContFracEval(Take(A, 5))
    Out> 33/7;
    In> ContFracEval(Take(A,3), remainder)
    Out> 1/(1/(remainder+2)+1)+4;

##### See also:

ContFrac , GuessRational .

###

GuessRational, NearRational -- find optimal rational approximations

Standard math library

##### Calling format:

    GuessRational(x)
    GuessRational(x, digits)
    NearRational(x)
    NearRational(x, digits)

##### Parameters:

`x` -- a number to be approximated

`digits` -- desired number of decimal digits

##### Description:

The functions `GuessRational(x)` and `NearRational(x)` attempt to find "optimal" rational approximations to a given value `x`. The approximations are "optimal" in the sense of having smallest numerators and denominators among all rational numbers close to `x`. This is done by computing a continued fraction representation of `x` and truncating it at a suitably chosen term. Both functions return a rational number which is an approximation of `x`.

Unlike the function `Rationalize()` which converts floating-point numbers to rationals without loss of precision, the functions `GuessRational()` and `NearRational()` are intended to find the best rational that is approximately equal to a given value.

The function `GuessRational()` is useful if you have obtained a floating-point representation of a rational number and you know approximately how many digits its exact representation should contain. This function takes an optional second parameter `digits` which limits the number of decimal digits in the denominator of the resulting rational number. If this parameter is not given, it defaults to half the current precision. This function truncates the continuous fraction expansion when it encounters an unusually large value (see example). This procedure does not always give the "correct" rational number; a rule of thumb is that the floating-point number should have at least as many digits as the combined number of digits in the numerator and the denominator of the correct rational number.

The function `NearRational(x)` is useful if you would like to simply approximate a given value, i.e. to find an "optimal" rational number that lies in a certain small interval around a certain value `x`. This function takes an optional second parameter `digits` which has slightly different meaning: it specifies the number of digits of precision of the approximation; in other words, the difference between `x` and the resulting rational number should be at most one digit of that precision. The parameter `digits` also defaults to half of the current precision.

##### Examples:

Start with a rational number and obtain a floating-point approximation:

    In> x:=N(956/1013)
    Out> 0.9437314906
    In> Rationalize(x)
    Out> 4718657453/5000000000;
    In> V(GuessRational(x))
    GuessRational: using 10 terms of the
      continued fraction
    Out> 956/1013;
    In> ContFracList(x)
    Out> {0,1,16,1,3,2,1,1,1,1,508848,3,1,2,1,2,2};

The first 10 terms of this continued fraction correspond to the correct continued fraction for the original rational number.

    In> NearRational(x)
    Out> 218/231;

This function found a different rational number closeby because the precision was not high enough.

    In> NearRational(x, 10)
    Out> 956/1013;

##### See also:

ContFrac , ContFracList , Rationalize .

###

Decimal -- decimal representation of a rational

Standard math library

##### Calling format:

    Decimal(frac)

##### Parameters:

`frac` - a rational number

##### Description:

This function returns the infinite decimal representation of a rational number `frac`. It returns a list, with the first element being the number before the decimal point and the last element the sequence of digits that will repeat forever. All the intermediate list elements are the initial digits before the period sets in.

##### Examples:

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

##### See also:

N .

###

TruncRadian -- remainder modulo 2*Pi

Standard math library

##### Calling format:

    TruncRadian(r)

##### Parameters:

`r` - a number

##### Description:

`TruncRadian` calculates Mod(r,2*Pi), returning a value between 0 and 2*Pi. This function is used in the trigonometry functions, just before doing a numerical calculation using a Taylor series. It greatly speeds up the calculation if the value passed is a large number.

The library uses the formula

TruncRadian(r)=r-Floor(r/(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 -- Round a number downwards

Standard math library

##### Calling format:

    Floor(x)

##### Parameters:

x - a number

##### Description:

This function 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 -- Round a number upwards

Standard math library

##### Calling format:

    Ceil(x)

##### Parameters:

x - a number

##### Description:

This function 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 -- Round a number to the nearest integer

Standard math library

##### Calling format:

    Round(x)

##### Parameters:

x - a number

##### Description:

This function returns the integer closest to "x". Half-integers (i.e. numbers of the form n+0.5, with n an integer) are rounded upwards.

##### Examples:

    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 -- Search for integer relations between reals

Standard math library

##### Calling format:

    Pslq(xlist,precision)

##### Parameters:

`xlist` - list of numbers

precision - required number of digits precision of calculation

##### Description:

This function is an integer relation detection algorithm. This means that, given the numbers x[i] in the list "xlist", it tries to find integer coefficients a[i] such that a[1]*x[1] + ... + a[n]*x[n]=0. The list of integer coefficients is returned.

The numbers in "xlist" must evaluate to floating point numbers if the `N` operator is applied on them.

##### Example:

    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:

N .

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 , Curl , Diverge , Integrate , Simplify , RadSimp , Rationalize , Solve , SuchThat , Eliminate , PSolve , Pi() , Random , VarList , Limit , TrigSimpCombine , LagrangeInterpolant , Fibonacci .

# Calculus and elementary functions

In this chapter, some facilities for doing calculus are described. These include functions implementing differentiation, integration, standard mathematical functions, and solving of equations.

###

Sin, Cos, Tan -- Trigonometric functions

Standard math library

##### Calling format:

    Sin(x)
    Cos(x)
    Tan(x)

##### Parameters:

`x` -- argument to the function, in radians

##### Description:

These functions represent the trigonometric functions sine, cosine, and tangent respectively. 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` function.

Yacas knows some trigonometric identities, so it can simplify to exact results even if `N` is not used. This is the case, for instance, when the argument is a multiple of Pi/6 or Pi/4.

These functions are threaded, meaning that if the argument "x" is a list, the function is applied to all the entries in the list.

##### 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:

ArcSin , ArcCos , ArcTan , N , Pi .

###

ArcSin, ArcCos, ArcTan -- Inverse trigonometric functions

Standard math library

##### Calling format:

ArcSin(x)

ArcCos(x)

ArcTan(x)

##### Parameters:

x - argument to the function

##### Description:

These functions represent the inverse trigonometric functions. For instance, the value of "ArcSin(x)" is the number "y" such that "Sin(y)" equals "x".

Note that the number "y" is not unique. For instance, "Sin(0)" and "Sin(Pi)" both equal 0, so what should "ArcSin(0)" be? In Yacas, it is agreed that the value of "ArcSin(x)" should be in the interval [-Pi/2,Pi/2]. The same goes for "ArcTan(x)". However, "ArcCos(x)" is in the interval [0,Pi].

Usually, Yacas leaves these functions alone unless it is forced to do a numerical evaluation by the `N` function. If the argument is -1, 0, or 1 however, Yacas will simplify the expression. If the argument is complex, the expression will be rewritten as a `Ln` function.

These functions are threaded, meaning that if the argument "x" is a list, the function is applied to all the entries in the list.

##### Examples:

    In> ArcSin(1)
    Out> Pi/2;

    In> ArcSin(1/3)
    Out> ArcSin(1/3);
    In> Sin(ArcSin(1/3))
    Out> 1/3;

    In> N(ArcSin(0.75))
    Out> 0.848062;
    In> N(Sin(%))
    Out> 0.7499999477;

##### See also:

Sin , Cos , Tan , N , Pi , Ln .

###

Exp -- Exponential function

Standard math library

##### Calling format:

    Exp(x)

##### Parameters:

x - argument to the function

##### Description:

This function calculates e raised to the power "x", where e is the mathematic constant 2.71828... One can use `Exp(1)` to represent e.

This function is threaded, meaning that if the argument "x" is a list, the function is applied to all the entries in the list.

##### Examples:

    In> Exp(0)
    Out> 1;
    In> Exp(I*Pi)
    Out> -1;
    In> N(Exp(1))
    Out> 2.7182818284;

##### See also:

Ln , Sin , Cos , Tan , N .

###

Ln -- Natural logarithm

Standard math library

##### Calling format:

    Ln(x)

##### Parameters:

x - argument to the function

##### Description:

This function calculates the natural logarithm of "x". This is the inverse function of the exponential function, `Exp`, ie. "Ln(x) = y" implies that "Exp(y) = x". For complex arguments, the imaginary part of the logarithm is in the interval (- Pi, Pi]. This is compatible with the branch cut of `Arg`.

This function is threaded, meaning that if the argument "x" is a list, the function is applied to all the entries in the list.

##### Examples:

    In> Ln(1)
    Out> 0;
    In> Ln(Exp(x))
    Out> x;
    In> D(x) Ln(x)
    Out> 1/x;

##### See also:

Exp , Arg .

###

Sqrt -- Square root

Standard math library

##### Calling format:

    Sqrt(x)

##### Parameters:

x - argument to the function

##### Description:

This function calculates the square root of "x". If the result is not rational, the call is returned unevaluated unless a numerical approximation is forced with the `N` function. This function can also handle negative and complex arguments.

This function is threaded, meaning that if the argument "x" is a list, the function is applied to all the entries in the list.

##### Examples:

    In> Sqrt(16)
    Out> 4;
    In> Sqrt(15)
    Out> Sqrt(15);
    In> N(Sqrt(15))
    Out> 3.8729833462;
    In> Sqrt(4/9)
    Out> 2/3;
    In> Sqrt(-1)
    Out> Complex(0,1);

##### See also:

Exp , ^ , N .

###

Abs -- Absolute value or modulus

Standard math library

##### Calling format:

    Abs(x)

##### Parameters:

x - argument to the function

##### Description:

This function returns the absolute value (also called the modulus) of "x". If "x" is positive, the absolute value is "x" itself; if "x" is negative, the absolute value is "-x". For complex "x", the modulus is the "r" in the polar decomposition x=r*Exp(I*phi).

This function is connected to the `Sign` function by the identity "Abs(x) * Sign(x) = x" for real "x".

This function is threaded, meaning that if the argument "x" is a list, the function is applied to all the entries in the list.

##### Examples:

    In> Abs(2);
    Out> 2;
    In> Abs(-1/2);
    Out> -1/2;
    In> Abs(3+4*I);
    Out> 5;

##### See also:

Sign , Arg .

###

Sign -- Sign of a number

Standard math library

##### Calling format:

Sign(x)

##### Parameters:

x - argument to the function

##### Description:

This function returns the sign of the real number "x". It is "1" for positive numbers and "-1" for negative numbers. Somewhat arbitrarily, `Sign(0)` is defined to be 1.

This function is connected to the `Abs` function by the identity "Abs(x) * Sign(x) = x" for real "x".

This function is threaded, meaning that if the argument "x" is a list, the function is applied to all the entries in the list.

##### Examples:

    In> Sign(2)
    Out> 1;
    In> Sign(-3)
    Out> -1;
    In> Sign(0)
    Out> 1;
    In> Sign(-3) * Abs(-3)
    Out> -3;

##### See also:

Arg , Abs .

###

Complex -- Construct a complex number

Standard math library

##### Calling format:

    Complex(r, c)

##### Parameters:

r - real part

c - imaginary part

##### Description:

This function represents the complex number "r + I*c", where "I" is the imaginary unit. It is the standard representation used in Yacas to represent complex numbers. Both "r" and "c" are supposed to be real.

Note that, at the moment, many functions in Yacas assume that all numbers are real unless it is obvious that it is a complex number. Hence `Im(Sqrt(x))` evaluates to `0` which is only true for nonnegative "x".

##### Examples:

    In> I
    Out> Complex(0,1);
    In> 3+4*I
    Out> Complex(3,4);
    In> Complex(-2,0)
    Out> -2;

##### See also:

Re , Im , I , Abs , Arg .

###

Re -- Real part of a complex number

Standard math library

##### Calling format:

Re(x)

##### Parameters:

x - argument to the function

##### Description:

This function returns the real part of the complex number "x".

##### Examples:

    In> Re(5)
    Out> 5;
    In> Re(I)
    Out> 0;
    In> Re(Complex(3,4))
    Out> 3;

##### See also:

Complex , Im .

###

Im -- Imaginary part of a complex number

Standard math library

##### Calling format:

    Im(x)

##### Parameters:

x - argument to the function

##### Description:

This function returns the imaginary part of the complex number "x".

##### Examples:

    In> Im(5)
    Out> 0;
    In> Im(I)
    Out> 1;
    In> Im(Complex(3,4))
    Out> 4;

##### See also:

Complex , Re .

###

I -- Imaginary unit

Standard math library

##### Calling format:

    I

##### Description:

This symbol represents the imaginary unit, which equals the square root of -1. It evaluates to `Complex(0,1)`.

##### Examples:

    In> I
    Out> Complex(0,1);
    In> I = Sqrt(-1)
    Out> True;

##### See also:

Complex .

###

Conjugate -- Complex conjugate

Standard math library

##### Calling format:

    Conjugate(x)

##### Parameters:

x - argument to the function

##### Description:

This function returns the complex conjugate of "x". The complex conjugate of a+I*b is a-I*b. This function assumes that all unbound variables are real.

##### Examples:

    In> Conjugate(2)
    Out> 2;
    In> Conjugate(Complex(a,b))
    Out> Complex(a,-b);

##### See also:

Complex , Re , Im .

###

Arg -- Argument of a complex number

Standard math library

##### Calling format:

    Arg(x)

##### Parameters:

x - argument to the function

##### Description:

This function returns the argument of "x". The argument is the angle with the positive real axis in the Argand diagram, or the angle "phi" in the polar representation r*Exp(I*phi) of "x". The result is in the range (-Pi, Pi], that is, excluding -Pi but including Pi. The argument of 0 is `Undefined`.

##### Examples:

    In> Arg(2)
    Out> 0;
    In> Arg(-1)
    Out> Pi;
    In> Arg(1+I)
    Out> Pi/4;

##### See also:

Abs , Sign .

###

! -- Factorial

Standard math library

##### Calling format:

    n!

##### Parameters:

n - argument to the function

##### Description:

This function calculates the factorial of integer or half-integer numbers. For nonnegative integers, n! equals n*(n-1)*(n-2)*...*1. The factorial of half-integers, defined via the gamma function, is also evaluated.

This function is threaded, meaning that if the argument "x" is a list, the function is applied to all the entries in the list.

For reasons of Yacas syntax, the factorial sign `!` cannot precede other non-letter symbols such as `+` or `*`. Therefore, you should enter a space after `!` in expressions such as `x! +1`.

##### Examples:

    In> 5!
    Out> 120;
    In> 1 * 2 * 3 * 4 * 5
    Out> 120;
    In> (1/2)!
    Out> Sqrt(Pi)/2;

##### See also:

Bin , Factorize .

###

Bin -- Binomial coefficients

Standard math library

##### Calling format:

Bin(n, m)

##### Parameters:

n, m - integers

##### Description:

This function calculates the binomial coefficient "n" above "m", which equals

n! /(n! *(n-m)!)

This is equal to the number of ways to choose "m" objects out of a total of "n" objects if order is not taken into account. The binomial coefficient is defined to be zero if "m" is negative or greater than "n".

##### Examples:

    In> Bin(10, 4)
    Out> 210;
    In> 10! / (4! * 6!)
    Out> 210;

##### See also:

! .

###

Sum -- Sum of a list of values

Standard math library

##### Calling format:

Sum(list)

Sum(var, from, to, body)

##### Parameters:

list - list of values to sum

var - variable to iterate over

from - integer value to iterate from

to - integer value to iterate up to

body - expression to evaluate for each iteration

##### Description:

The first form of the `Sum` command simply adds all the entries in "list" and returns their sum.

If the second calling sequence is used, the expression "body" is evaluated while the variable "var" ranges over all integers from "from" up to "to", and the sum of all the results is returned. Obviously, "to" should be greater than or equal to "from".

##### Examples:

    In> Sum({1,4,9});
    Out> 14;
    In> Sum(i, 1, 3, i^2);
    Out> 14;

##### See also:

Average , Factorize , Apply .

###

Average -- Average of a list of values

Standard math library

##### Calling format:

Average(list)

##### Parameters:

list - list of values to average

##### Description:

This command calculates the (arithmetical) average of all the entries in "list", which is the sum of all entries divided by the number of entries.

##### Examples:

    In> Average({1,2,3,4,5});
    Out> 3;
    In> Average({2,6,7});
    Out> 5;

##### See also:

Sum .

###

Factorize -- Product of a list of values

Standard math library

##### Calling format:

Factorize(list)

Factorize(var, from, to, body)

##### Parameters:

list - list of values to multiply

var - variable to iterate over

from - integer value to iterate from

to - integer value to iterate up to

body - expression to evaluate for each iteration

##### Description:

The first form of the `Factorize` command simply multiplies all the entries in "list" and returns their product.

If the second calling sequence is used, the expression "body" is evaluated while the variable "var" ranges over all integers from "from" up to "to", and the product of all the results is returned. Obviously, "to" should be greater than or equal to "from".

##### Examples:

    In> Factorize({1,2,3,4});
    Out> 24;
    In> Factorize(i, 1, 4, i);
    Out> 24;

##### See also:

Sum , Apply .

###

Min -- Minimum of a number of values

Standard math library

##### Calling format:

Min(x,y)

Min(list)

##### Parameters:

x, y - pair of values to determine the minimum of

list - list of values from which the minimum is sought

##### Description:

This function returns the minimum value of its argument(s). If the first calling sequence is used, the smaller of "x" and "y" is returned. If one uses the second form, the smallest of the entries in "list" is returned. In both cases, this function can only be used with numerical values and not with symbolic arguments.

##### Examples:

    In> Min(2,3);
    Out> 2;
    In> Min({5,8,4});
    Out> 4;

##### See also:

Max , Sum , Average .

###

Max -- Maximum of a number of values

Standard math library

##### Calling format:

Max(x,y)

Max(list)

##### Parameters:

x, y - pair of values to determine the maximum of

list - list of values from which the maximum is sought

##### Description:

This function returns the maximum value of its argument(s). If the first calling sequence is used, the larger of "x" and "y" is returned. If one uses the second form, the largest of the entries in "list" is returned. In both cases, this function can only be used with numerical values and not with symbolic arguments.

##### Examples:

    In> Max(2,3);
    Out> 3;
    In> Max({5,8,4});
    Out> 8;

##### See also:

Min , Sum , Average .

###

IsZero -- Test whether argument is zero

Standard math library

##### Calling format:

IsZero(n)

##### Parameters:

n - number to test

##### Description:

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

##### Examples:

    In> IsZero(3.25)
    Out> False;
    In> IsZero(0)
    Out> True;
    In> IsZero(x)
    Out> False;

##### See also:

IsNumber , IsNotZero .

###

IsRational -- Test whether argument is a rational

Standard math library

##### Calling format:

IsRational(expr)

##### Parameters:

expr - expression to test

##### Description:

This commands tests whether the expression "expr" is a rational number. This is the case if the top-level operator of "expr" is `/`.

##### Examples:

    In> IsRational(5)
    Out> False;
    In> IsRational(2/7)
    Out> True;
    In> IsRational(a/b)
    Out> True;
    In> IsRational(x + 1/x)
    Out> False;

##### See also:

Numer , Denom .

###

Numer -- Numerator of an expression

Standard math library

##### Calling format:

Numer(expr)

##### Parameters:

expr - expression to determine numerator of

##### Description:

This function determines the numerator of the rational expression "expr" and returns it. As a special case, if its argument is numeric but not rational, it returns this number. If "expr" is neither rational nor numeric, the function returns unevaluated.

##### Examples:

    In> Numer(2/7)
    Out> 2;
    In> Numer(a / x^2)
    Out> a;
    In> Numer(5)
    Out> 5;

##### See also:

Denom , IsRational , IsNumber .

###

Denom -- Denominator of an expression

Standard math library

##### Calling format:

Denom(expr)

##### Parameters:

expr - expression to determine denominator of

##### Description:

This function determines the denominator of the rational expression "expr" and returns it. As a special case, if its argument is numeric but not rational, it returns `1`. If "expr" is neither rational nor numeric, the function returns unevaluated.

##### Examples:

    In> Denom(2/7)
    Out> 7;
    In> Denom(a / x^2)
    Out> x^2;
    In> Denom(5)
    Out> 1;

##### See also:

Numer , IsRational , IsNumber .

###

Commutator -- Commutator of two objects

Standard math library

##### Calling format:

Commutator(a, b)

##### Parameters:

a, b - two objects whose commutator should be computed

##### Description:

This command computes the commutator of 'a" and "b", ie. the expression "a b - b a". For numbers and other objects for which multiplication is commutative, the commutator is zero. But this is not necessarily the case for matrices.

##### Examples:

    In> Commutator(2,3)
    Out> 0;
    In> PrettyPrinter("PrettyForm");

    True

    Out>
    In> A := { {0,x}, {0,0} }

    /              \
    | ( 0 ) ( x )  |
    |              |
    | ( 0 ) ( 0 )  |
    \              /

    Out>
    In> B := { {y,0}, {0,z} }

    /              \
    | ( y ) ( 0 )  |
    |              |
    | ( 0 ) ( z )  |
    \              /

    Out>
    In> Commutator(A,B)

    /                          \
    | ( 0 ) ( x * z - y * x )  |
    |                          |
    | ( 0 ) ( 0 )              |
    \                          /

    Out>

###

Taylor -- Univariate Taylor series expansion

Standard math library

##### Calling format:

Taylor(var, at, order) expr

##### Parameters:

var - variable

at - point to get Taylor series around

order - order of approximation

expr - expression to get Taylor series for

##### Description:

This function returns the Taylor series expansion of the expression "expr" with respect to the variable "var" around "at" up to order "order". This is a polynomial which agrees with "expr" at the point "var = at", and furthermore the first "order" derivatives of the polynomial at this point agree with "expr". Taylor expansions around removable singularities are correctly handled by taking the limit as "var" approaches "at".

##### Examples:

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

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

    Out> True;

##### See also:

D , InverseTaylor , ReversePoly , BigOh .

###

InverseTaylor -- Taylor expansion of inverse

Standard math library

##### Calling format:

InverseTaylor(var, at, order) expr

##### Parameters:

var - variable

at - point to get inverse Taylor series around

order - order of approximation

expr - expression to get inverse Taylor series for

##### Description:

This function builds the Taylor series expansion of the inverse of the expression "expr" with respect to the variable "var" around "at" up to order "order". It uses the function `ReversePoly` to perform the task.

##### Examples:

    In> PrettyPrinter("PrettyForm")

    True

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

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

    Out>
    In> exp2 := InverseTaylor(x,0,7) 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 -- Solve h(f(x))=g(x)+O(x^n) for h

Standard math library

##### Calling format:

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

##### Parameters:

f, g - expressions in "var"

var - a variable

newvar - a new variable to express the result in

degree - the degree of the required solution

##### Description:

This function returns a polynomial in "newvar", say "h(newvar)", with the property that "h(f(var))" equals "g(var)" up to order "degree". The degree of the result will be at most "degree-1". The only requirement is that the first derivative of "f" should not be zero.

This function is used to determine the Taylor series expansion of the inverse of a function "f": if we take "g(var)=var", then "h(f(var))=var" (up to order "degree"), so "h" will be the inverse of "f".

##### 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 -- Drop all terms of a certain order in a polynomial

Standard math library

##### Calling format:

BigOh(poly, var, degree)

##### Parameters:

poly - a univariate polynomial

var - a free variable

degree - positive integer

##### Description:

This function drops all terms of order "degree" or higher in "poly", which is a polynomial in the variable "var".

##### Examples:

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

##### See also:

Taylor , InverseTaylor .

###

Newton -- Solve an equation numerically with Newton's method

Standard math library

##### Calling format:

Newton(expr, var, initial, accuracy)

##### Parameters:

expr - an expression to find a zero for

var - free variable to adjust to find a zero

initial - initial value for "var" to use in the search

accuracy - minimum required accuracy of the result

##### Description:

This function tries to numerically find a zero of the expression "expr", which should depend only on the variable "var". It uses the value "initial" as an initial guess.

The function will iterate using Newton's method until it estimates that it has come within a distance "accuracy" of the correct solution, and then it will return its best guess. In particular, it may loop forever if the algorithm does not converge.

##### Examples:

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

##### See also:

Solve .

###

D -- Differentiation

Standard math library

##### Calling format:

D(var) expr

D(list) expr

D(var,n) expr

##### Parameters:

var - variable

list - a list of variables

expr - expression to take derivative of

n - order of derivative

##### Description:

This function calculates the derivative of the expression "expr" with respect to the variable "var" and returns it. If the third calling sequence is used, the "n"-th derivative is determined. Yacas knows how the differentiate standard functions like `Ln` and `Sin`.

The `D` operator is threaded in both "var" and "expr". This means that if either of them is a list, the function is applied to each entry in the list. The results are collected in another list which is returned. If both "var" and "expr" are a list, their lengths should be equal. In this case, the first entry in the list "expr" is differentiated with respect to the first entry in the list "var", the second entry in "expr" is differentiated with respect to the second entry in "var", and so on.

##### 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 , Curl .

###

Curl -- Curl of a vector field

Standard math library

##### Calling format:

Curl(vector, basis)

##### Parameters:

vector - vector field to take the curl of

basis - list of variables forming the basis

##### Description:

This function takes the curl of the vector field "vector" with respect to the variables "basis". The curl is defined in the usual way,

    Curl(f,x) = {
        D(x[2]) f[3] - D(x[3]) f[2],
        D(x[3]) f[1] - D(x[1]) f[3],
        D(x[1]) f[2] - D(x[2]) f[1]
    }

Both "vector" and "basis" should be lists of length 3.

##### Example:

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

##### See also:

D , Diverge .

###

Diverge -- Divergence of a vector field

Standard math library

##### Calling format:

Diverge(vector, basis)

##### Parameters:

vector - vector field to calculate the divergence of

basis - list of variables forming the basis

##### Description:

This function calculates the divergence of the vector field "vector" with respect to the variables "basis". The divergence is defined as

    Diverge(f,x) = D(x[1]) f[1] + ...
        + D(x[n]) f[n],

where `n` is the length of the lists "vector" and "basis". These lists should have equal length.

##### Example:

    In> Diverge({x*y,x*y,x*y},{x,y,z})
    Out> y+x;

##### See also:

D , Curl .

###

Integrate -- Integration

Standard math library

##### Calling format:

Integrate(var, from, to) expr

Integrate(var) expr

##### Parameters:

var - variable to integrate over

from - begin of interval to integrate over

to - end of interval to integrate over

expression - expression to integrate

##### Description:

This function integrates the expression "expr" with respect to the variable "var". The first calling sequence is used to perform definite integration: the integration is carried out from "var=form" to "var=to". The second form signifies indefinite integration. In this case, the function `UniqueConstant` is called to get a variable of the form `C`n (where "n" is an integer) which represent the integration constant.

Some simple integration rules have currently been implemented. Polynomials, quotients of polynomials, the transcendental functions `Sin`, `Cos`, `Exp`, and `Ln`, and products of these functions with polynomials can all be integrated.

##### 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 , UniqueConstant .

###

Simplify -- Try to simplify an expression

Standard math library

##### Calling format:

Simplify(expr)

##### Parameters:

expression - expression to simplify

##### Description:

This function tries to simplify the expression "expr" 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 -- Simplify expression with nested radicals

Standard math library

##### Calling format:

RadSimp(expr)

##### Parameters:

expr - an expression containing nested radicals

##### Description:

This function tries to write the expression "expr" as a sum of roots of integers: Sqrt(e1)+Sqrt(e2)+..., where e1, e2 and so on are natural numbers. The expression "expr" may not contain free variables.

It does this by trying all possible combinations for e1, e2, ... Every possibility is numerically evaluated using `N` and compared with the numerical evaluation of "expr". If the approximations are equal (up to a certain margin), this possibility is returned. Otherwise, the expression is returned unevaluated.

Note that due to the use of numerical approximations, there is a small chance that the expression returned by `RadSimp` is close but not equal to "expr". The last example underneath illustrates this problem. Furthermore, if the numerical value of "expr" is large, the number of possibilities becomes exorbitantly big so the evaluation may take very long.

##### Examples:

    In> RadSimp(Sqrt(9+4*Sqrt(2)))
    Out> Sqrt(8)+1;
    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> Sqrt(2)+3;

But this command may yield incorrect results:

    In> RadSimp(Sqrt(1+10^(-6)))
    Out> 1;

##### See also:

Simplify , N .

###

Rationalize -- Convert floating point numbers to fractions

Standard math library

##### Calling format:

Rationalize(expr)

##### Parameters:

expr - an expression containing real numbers

##### Description:

This command converts every real number in the expression "expr" into a rational number. This is useful when a calculation needs to be done on floating point numbers and the algorithm is unstable. Converting the floating point numbers to rational numbers will force calculations to be done with infinite precision (by using rational numbers as representations).

It does this by finding the smallest integer n such that multiplying the number with 10^n is an integer. Then it divides by 10^n again, depending on the internal gcd calculation to reduce the resulting division of integers.

##### Examples:

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

##### See also:

IsRational .

###

Solve -- Solve one or more algebraic equations

Standard math library

##### Calling format:

Solve(eq, var)

Solve(eqlist, varlist)

##### Parameters:

eq - single identity equation

var - single variable

eqlist - list of identity equations

varlist - list of variables

##### Description:

This command tries to solve one or more equations. Use the first form to solve a single equation and the second one for systems of equations.

The first calling sequence solves the equation "eq" for the variable "var". Use the `==` operator to form the equation. The value of "var" which satisfies the equation, is returned. Note that only one solution is found and returned.

To solve a system of equations, the second form should be used. It solves the system of equations contained in the list "eqlist" for the variables appearing in the list "varlist". A list of results is returned, and each result is a list containing the values of the variables in "varlist". Again, at most a single solution is returned.

The task of solving a single equation is simply delegated to `SuchThat`. Multiple equations are solved recursively: firstly, an equation is sought in which one of the variables occurs exactly once; then this equation is solved with `SuchThat`; and finally the solution is substituted in the other equations by `Eliminate` decreasing the number of equations by one. This suffices for all linear equations and a large group of simple nonlinear 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}};

This means that "x = (z-a)/y" is a solution of the first equation and that "x = -z", "y = z*a" is a solution of the systems of equations in the second command.

An example which `Solve` cannot solve:

    In> Solve({x^2-x == y^2-y,x^2-x == y^3+y},{x,y});
    Out> {};

##### See also:

SuchThat , Eliminate , PSolve , == .

###

SuchThat -- Find a value which makes some expression zero

Standard math library

##### Calling format:

    SuchThat(expr, var)

##### Parameters:

expr - expression to make zero

var - variable (or subexpression) to solve for

##### Description:

This functions tries to find a value of the variable "var" which makes the expression "expr" zero. It is also possible to pass a subexpression as "var", in which case `SuchThat` will try to solve for that subexpression.

Basically, only expressions in which "var" occurs only once are handled; in fact, `SuchThat` may even give wrong results if the variables occurs more than once. This is a consequence of the implementation, which repeatedly applies the inverse of the top function until the variable "var" is reached.

##### 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> (a+b)*x+c;
    In> SuchThat(%, x)
    Out> (-c)/(a+b);

##### See also:

Solve , Subst , Simplify .

###

Eliminate -- Substitute and simplify

Standard math library

##### Calling format:

    Eliminate(var, value, expr)

##### Parameters:

var - variable (or subexpression) to substitute

value - new value of "var"

expr - expression in which the substitution should take place

##### Description:

This function uses `Subst` to replace all instances of the variable (or subexpression) "var" in the expression "expr" with "value", calls `Simplify` to simplify the resulting expression, and returns the result.

##### Examples:

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

##### See also:

SuchThat , Subst , Simplify .

###

PSolve -- Solve a polynomial equation

Standard math library

##### Calling format:

    PSolve(poly, var)

##### Parameters:

poly - a polynomial in "var"

var - a variable

##### Description:

This commands returns a list containing the roots of "poly", considered as a polynomial in the variable "var". If there is only one root, it is not returned as a one-entry list but just by itself. A double root occurs twice in the result, and similarly for roots of higher multiplicity. All polynomials of degree up to 4 are handled.

##### 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() -- Numerical approximation of Pi

Internal function

##### Calling format:

    Pi()

##### Description:

This commands returns the value of the mathematical constant pi at the current precision, as set by `Precision`. Usually this function should not be called directly. The constant `Pi` can (and should) be used to represent the exact value of pi, as it is recognized by the simplification rules. When the function `N` is invoked on an expression, `Pi` will be replaced with the value returned by `Pi()`.

##### Examples:

    In> Pi()
    Out> 3.14159265358979323846;
    In> Sin(3*Pi/2)
    Out> -1;
    In> Sin(3*Pi()/2)
    Out> Sin(4.7123889804);
    In> Precision(35)
    Out> True;
    In> Pi()
    Out> 3.14159265358979323846264338327950288;

##### See also:

N , Pi , Precision .

###

Random -- Random number between 0 and 1

Standard math library

##### Calling format:

    Random()

##### Description:

This function returns a random number, uniformly distributed in the interval between 0 and 1. The same sequence of random numbers is generated in every Yacas session.

##### See also:

RandomInteger , RandomPoly .

###

VarList -- List of variables appearing in some expression

Standard math library

##### Calling format:

    VarList(expr)

##### Parameters:

expr - an expression

##### Description:

This command returns a list of all the variables that appear in the expression "expr".

##### Examples:

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

##### See also:

IsFreeOf , IsVariable .

###

Limit -- Limit of an expression

Standard math library

##### Calling format:

    Limit(var, val) expr
    Limit(var, val, dir) expr

##### Parameters:

var - a variable

val - a number

dir - a direction (`Left` or `Right`)

expr - an expression

##### Description:

This command tries to determine the value that the expression "expr" converges to when the variable "var" approaches "val". One may use `Infinity` or `-Infinity` for "val". The result of `Limit` may be one of the symbols `Undefined` (meaning that the limit does not exist), `Infinity`, or `-Infinity`.

The second calling sequence is used for unidirectional limits. If one gives "dir" the value `Left`, the limit is taken as "var" approaches "val" from the positive infinity; and `Right` will take the limit from the negative 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 -- Combine products of trigonometric functions

Standard math library

##### Calling format:

TrigSimpCombine(expr)

##### Parameters:

expr - expression to simplify

##### Description:

This function applies the product rules of trigonometry, like Cos(u)*Sin(v)=1/2*(Sin(v-u)+Sin(v+u)). As a result, all products of the trigonometric functions `Cos` and `Sin` disappear. The function also tries to simplify the resulting expression as much as possible by combining all like terms.

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

##### Examples:

    In> PrettyPrinter("PrettyForm");

    True

    Out>
    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 )
    -------- + -----------------
       2               4

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

    Out>

##### See also:

Simplify , Integrate , Expand , Sin , Cos , Tan .

###

LagrangeInterpolant -- Polynomial interpolation

Standard math library

##### Calling format:

LagrangeInterpolant(xlist, ylist, var)

##### Parameters:

xlist - list of argument values

ylist - list of function values

var - free variable for resulting polynomial

##### Description:

This function returns a polynomial in the variable "var" which interpolates the points "(xlist, ylist)". Specifically, the value of the resulting polynomial at "xlist[1]" is "ylist[1]", the value at "xlist[2]" is "ylist[2]", etc. The degree of the polynomial is not greater than the length of "xlist".

The lists "xlist" and "ylist" should be of equal length. Furthermore, the entries of "xlist" should be all distinct to ensure that there is one and only one solution.

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

##### Examples:

    In> f := LagrangeInterpolant({0,1,2}, \
      {0,1,1}, x);
    Out> (x*(x-1))/2-x*(x-2);
    In> Eval(Subst(x,0) f);
    Out> 0;
    In> Eval(Subst(x,1) f);
    Out> 1;
    In> Eval(Subst(x,2) f);
    Out> 1;

    In> PrettyPrinter("PrettyForm");

    True

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

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

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

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

    Out>

##### See also:

Subst .

###

Fibonacci -- Fibonacci sequence

Standard math library

##### Calling format:

    Fibonacci(n)

##### Parameters:

n - an integer

##### Description:

This command calculates and returns the "n"-th Fibonacci number.

The Fibonacci sequence is 1, 1, 2, 3, 5, 8, 13, 21, ... where every number is the sum of the two preceding numbers. Formally, it is defined by F(1)=1, F(2)=1, and F(n+1)=F(n)+F(n-1), where F(n) denotes the n-th Fibonacci number.

##### Examples:

    In> Fibonacci(4)
    Out> 3;
    In> Fibonacci(8)
    Out> 21;
    In> Table(Fibonacci(i), i, 1, 10, 1)
    Out> {1,1,2,3,5,8,13,21,34,55};

Gamma, GammaNum , Zeta, ZetaNum , Bernoulli, BernoulliArray .

# Special functions

In this chapter, special and transcendental mathematical functions are described.

###

Gamma, GammaNum -- Euler's Gamma function

Standard math library

##### Calling format:

    Gamma(x)
    GammaNum(number)

##### Parameters:

`x` -- expression

`number` -- expression that can be evaluated to a number

##### Description:

`Gamma(x)` is an interface to Euler's Gamma function Gamma(x). It returns exact values on integer and half-integer arguments. `GammaNum(x)` or equivalently `N(Gamma(x)` takes a numeric parameter and always returns a floating-point number in the current precision.

##### Examples:

    In> Precision(30)
    Out> True;
    In> Gamma(1.3)
    Out> Gamma(1.3);
    In> N(%)
    Out> 0.897470696306277188493754954771;
    In> Gamma(1.5)
    Out> Sqrt(Pi)/2;
    In> GammaNum(1.5);
    Out> 0.88622692545275801364908374167;

##### See also:

! , N .

###

Zeta, ZetaNum -- Riemann's Zeta function

Standard math library

##### Calling format:

    Zeta(x)
    ZetaNum(number)

##### Parameters:

`x` -- expression

`number` -- expression that can be evaluated to a number

##### Description:

`Zeta(x)` is an interface to Riemann's Zeta function zeta(s). It returns exact values on integer and half-integer arguments. `ZetaNum(x)` or equivalently `N(Zeta(x)` takes a numeric parameter and always returns a floating-point number in the current precision.

##### Examples:

    In> Precision(30)
    Out> True;
    In> Zeta(1)
    Out> Infinity;
    In> Zeta(1.3)
    Out> Zeta(1.3);
    In> N(%)
    Out> 3.93194921180954422697490751058798;
    In> Zeta(2)
    Out> Pi^2/6;
    In> ZetaNum(2);
    Out> 1.64493406684822643647241516664602;

##### See also:

! , N .

###

Bernoulli, BernoulliArray -- Bernoulli numbers and polynomials

Standard math library

##### Calling format:

    Bernoulli(index)
    BernoulliArray(index)
    Bernoulli(index, x)

##### Parameters:

`x` -- expression that will be the variable in the polynomial

`index` -- expression that can be evaluated to an integer

##### Description:

`Bernoulli(n)` evaluates the n-th Bernoulli number. `Bernoulli(n, x)` returns the n-th Bernoulli polynomial in the variable x. The polynomial is returned in the Horner form.

An auxiliary function `BernoulliArray(n)` might be useful too: it returns an array (of type `GenericArray`) of Bernoulli numbers up to n. The array is 1-based, so that the n-th Bernoulli number is `BernoulliArray(n)[n+1]`.

##### Example:

    In> Bernoulli(20);
    Out> -174611/330;
    In> Bernoulli(4, x);
    Out> ((x-2)*x+1)*x^2-1/30;

##### See also:

Gamma , Zeta .

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

# 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 symbol

Standard math library

##### Calling format:

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 format:

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 format:

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 format:

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 format:

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 format:

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 format:

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 format:

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 format:

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 format:

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 themselves lists.

##### 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 format:

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 format:

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 format:

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 format:

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 format:

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 format:

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 format:

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 format:

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 format:

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 format:

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 format:

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 format:

IsHermitean(A)

##### Parameters:

A - square matrix

##### Description:

IsHermitean(A) returns `True` if `A` is Hermitian and `False` otherwise. A is a Hermitian matrix iff Conjugate( Transpose A )= A. If A is a real matrix, it must be symmetric to be Hermitian.

##### 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 format:

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 .

###

SylvesterMatrix -- calculate the Sylvester matrix of two polynomials

Standard math library

##### Calling format:

    SylvesterMatrix(poly1,poly2,variable)

##### Parameters:

`poly1` - polynomial

`poly2` - polynomial

`variable` - variable to express the matrix for

##### Description:

The function `SylvesterMatrix` calculates the Sylvester matrix for a pair of polynomials.

The Sylvester matrix is closely related to the resultant, which is defined as the determinant of the Sylvester matrix. Two polynomials share common roots only if the resultant is zero.

##### Examples:

    In> ex1:= x^2+2*x-a
    Out> x^2+2*x-a;
    In> ex2:= x^2+a*x-4
    Out> x^2+a*x-4;
    In> SylvesterMatrix(ex1,ex2,x)
    Out> {{1,2,-a,0},{0,1,2,-a},{1,a,-4,0},{0,1,a,-4}};
    In> Determinant(%)
    Out> 16-a^2*a- -8*a-4*a+a^2- -2*a^2-16-4*a;
    In> Simplify(%)
    Out> 3*a^2-a^3;

The above example shows that the two polynomials have common zeros if a=3.

##### See also:

Determinant , Simplify , Solve , PSolve .

Expand , Degree , Coef , Content , PrimitivePart , LeadingCoef , Monic , RandomPoly , Horner , ExpandBrackets , OrthoP , OrthoH , OrthoG , OrthoL , OrthoT , OrthoU , OrthoPSum, OrthoHSum, OrthoLSum, OrthoGSum, OrthoTSum, OrthoUSum , OrthoPoly , OrthoPolySum .

# Polynomials

This chapter contains commands to manipulate polynomials. This includes functions for constructing and evaluating orthogonal polynomials.

###

Expand -- Put polynomial in expanded form

Standard math library

##### Calling format:

    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+...+c[n]*x^n. In this form, it is easier to test whether a polynomial is zero, namely by testing whether all coefficients are zero.

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 format:

    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 format:

    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 format:

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 format:

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 format:

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 format:

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 format:

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 format:

    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 such as

c[0]+c[1]*x+...+c[n]*x^n

If one converts this polynomial into 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 format:

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 .

###

OrthoP -- Legendre and Jacobi orthogonal polynomials

Standard math library

##### Calling format:

    OrthoP(n, x);
    OrthoP(n, a, b, x);

##### Parameters:

n - degree of polynomial

x - point to evaluate polynomial at

a, b - parameters for Jacobi polynomial

##### Description:

The first calling format with two arguments evaluates the Legendre polynomial of degree "n" at the point "x". The second form does the same for the Jacobi polynomial with parameters "a" and "b", which should be greater than -1.

The Jacobi polynomials are orthogonal with respect to the weight function (1-x)^a*(1+x)^b on the interval [-1,1]. They satisfy the recurrence relations:

    P(0,a,b,x) = 1

                 a - b     /     a + b \
    P(1,a,b,x) = ----- + x | 1 + ----- |
                   2       \       2   /

    P(n,a,b,x) = (2n + a + b - 1) *

        2   2
       a - b + x (2n+a+b-2) (n+a+b)
       ---------------------------- P(n-1,a,b,x)
          2n (2n+a+b-2) (n+a+b)

        (n+a-1) (n+b-1) (2n+a+b)
     -  ------------------------ P(n-2,a,b,x),
          n (n+a+b) (2n+a+b-2)

for n>1.

Legendre polynomials are a special case of Jacobi polynomials with the specific parameter values a = b = 0. So they form an orthogonal system with respect to the weight function identically equal to 1 on the interval [-1,1], and they satisfy the recurrence relations:

    P(0,x) = 1

    P(1,x) = x

             (2n - 1) x            n - 1
    P(n,x) = ---------- P(n-1,x) - ----- P(n-2,x),
                 2n                  n

for n>1.

Most of the work is performed by the internal function `OrthoPoly`.

##### Examples:

    In> PrettyPrinter("PrettyForm");

    True

    Out>
    In> OrthoP(3, x);

        /      2     \
        | 5 * x    3 |
    x * | ------ - - |
        \   2      2 /

    Out>
    In> OrthoP(3, 1, 2, x);

    1       /     / 21 * x   7 \   7 \
    - + x * | x * | ------ - - | - - |
    2       \     \   2      2 /   2 /

    Out>
    In> Expand(%)

          3        2
    21 * x  - 7 * x  - 7 * x + 1
    ----------------------------
                 2

    Out>
    In> OrthoP(3, 1, 2, 0.5);

    -0.8124999999

    Out>

##### See also:

OrthoPSum , OrthoG , OrthoPoly .

###

OrthoH -- Hermite orthogonal polynomials

Standard math library

##### Calling format:

    OrthoH(n, x);

##### Parameters:

n - degree of polynomial

x - point to evaluate polynomial at

##### Description:

This function evaluates the Hermite polynomial of degree "n" at the point "x".

The Hermite polynomials are orthogonal with respect to the weight function Exp(-x^2/2) on the entire real axis. They satisfy the recurrence relations:

    H(0,x) = 1

    H(1,x) = 2x

    H(n,x) = 2x H(n-1,x) - 2(n-1) H(n-2,x),

for n>1.

Most of the work is performed by the internal function `OrthoPoly`.

##### Examples:

    In> OrthoH(3, x);
    Out> x*(8*x^2-12);
    In> OrthoH(6, 0.5);
    Out> 31;

##### See also:

OrthoHSum , OrthoPoly .

###

OrthoG -- Gegenbauer orthogonal polynomials

Standard math library

##### Calling format:

    OrthoG(n, a, x);

##### Parameters:

n - degree of polynomial

a - parameter

x - point to evaluate polynomial at

##### Description:

This function evaluates the Gegenbauer (or ultraspherical) polynomial with parameter "a" and degree "n" at the point "x". The parameter "a" should be greater than -1/2.

The Gegenbauer polynomials are orthogonal with respect to the weight function (1-x^2)^(a-1/2) on the interval [-1,1]. Hence they are connected to the Jacobi polynomials via G(n, a, x) = P(n, a-1/2, a-1/2, x). They satisfy the recurrence relations:

    G(0,a,x) = 1

    G(1,a,x) = 2 x

                 /     a - 1 \
    G(n,a,x) = 2 | 1 + ----- | x G(n-1,a,x)
                 \       n   /

      /     2 (a-2) \
    - | 1 + ------- | G(n-2,a,x),
      \        n    /

for n>1.

Most of the work is performed by the internal function `OrthoPoly`.

##### Examples:

    In> OrthoG(5, 1, x);
    Out> x*((32*x^2-32)*x^2+6);
    In> OrthoG(5, 2, -0.5);
    Out> 2;

##### See also:

OrthoP , OrthoT , OrthoU , OrthoGSum , OrthoPoly .

###

OrthoL -- Laguerre orthogonal polynomials

Standard math library

##### Calling format:

    OrthoL(n, a, x);

##### Parameters:

n - degree of polynomial

a - parameter

x - point to evaluate polynomial at

##### Description:

This function evaluates the Laguerre polynomial with parameter "a" and degree "n" at the point "x". The parameter "a" should be greater than -1.

The Laguerre polynomials are orthogonal with respect to the weight function x^a*Exp(-x) on the positive real axis. They satisfy the recurrence relations:

    L(0,a,x) = 1

    L(1,a,x) = a + 1 - x

               /     a - 1 - x \
    L(n,a,x) = | 2 + --------- | L(n-1,a,x) -
               \         n     /

      /     a - 1 \
      | 1 + ----- | L(n-2,a,x),
      \  	  n   /

for n>1.

Most of the work is performed by the internal function `OrthoPoly`.

##### Examples:

    In> OrthoL(3, 1, x);
    Out> x*(x*(2-x/6)-6)+4;
    In> OrthoL(3, 1/2, 0.25);
    Out> 1.2005208334;

##### See also:

OrthoLSum , OrthoPoly .

###

OrthoT -- Tschebyscheff polynomials of the first kind

Standard math library

##### Calling format:

    OrthoT(n, x);

##### Parameters:

n - degree of polynomial

x - point to evaluate polynomial at

##### Description:

This function evaluates the Tschebyscheff polynomial of the first kind of degree "n" at the point "x". The name is also spelled Chebyshev.

The Tschebyscheff polynomials of the first kind are orthogonal with respect to the weight function (1-x^2)^(-1/2). Hence they are a special case of the Gegenbauer polynomials, with a=0. They satisfy the recurrence relations:

    T(0,x) = 1
    T(1,x) = x
    T(n,x) = 2 x T(n-1,x) - T(n-2,x),

for n>1.

Most of the work is performed by the internal function `OrthoPoly`.

##### Examples:

    In> OrthoT(3, x);
    Out> x*(4*x^2-3);
    In> OrthoT(10, 0.9);
    Out> -0.2007474688;

##### See also:

OrthoG , OrthoU , OrthoTSum , OrthoPoly .

###

OrthoU -- Tschebyscheff polynomials of the second kind

Standard math library

##### Calling format:

    OrthoU(n, x);

##### Parameters:

n - degree of polynomial

x - point to evaluate polynomial at

##### Description:

This function evaluates the Tschebyscheff polynomial of the second kind of degree "n" at the point "x". (The name of this Russian mathematician is also sometimes spelled "Chebyshev".)

The Tschebyscheff polynomials of the second kind are orthogonal with respect to the weight function (1-x^2)^(1/2). Hence they are a special case of the Gegenbauer polynomials, with a=1. They satisfy the recurrence relations:

    U(0,x) = 1
    U(1,x) = 2 x
    U(n,x) = 2 x U(n-1,x) - U(n-2,x),

for n>1.

Most of the work is performed by the internal function `OrthoPoly`.

##### Examples:

    In> OrthoU(3, x);
    Out> x*(8*x^2-4);
    In> OrthoU(10, 0.9);
    Out> -2.2234571776;

##### See also:

OrthoG , OrthoT , OrthoUSum , OrthoPoly .

###

OrthoPSum, OrthoHSum, OrthoLSum, OrthoGSum, OrthoTSum, OrthoUSum -- Sums of series of orthogonal polynomials

Standard math library

##### Calling format:

    OrthoPSum(c, x);
    OrthoPSum(c, a, b, x);
    OrthoHSum(c, x);
    OrthoLSum(c, a, x);
    OrthoGSum(c, a, x);
    OrthoTSum(c, x);
    OrthoUSum(c, x);

##### Parameters:

c - list of coefficients

a, b - parameters of specific polynomials

x - point to evaluate polynomial at

##### Description:

These functions evaluate the sum of series of orthogonal polynomials at the point "x", with given list of coefficients "c" of the series and fixed polynomial parameters "a", "b" (if applicable).

The list of coefficients starts with the lowest order, so that for example OrthoLSum(c, a, x) = c[1]* L[0](a,x) + c[2] L[1](a,x) + ... + c[N] L[N-1](a,x).

See pages for specific orthogonal polynomials for more details on the parameters of the polynomials.

Most of the work is performed by the internal function `OrthoPolySum`. The individual polynomials entering the series are not computed, only the sum of the series.

##### Examples:

    In> Expand(OrthoPSum({1,0,0,1/7,1/8}, 3/2, \
      2/3, x));
    Out> (7068985*x^4)/3981312+(1648577*x^3)/995328+
    (-3502049*x^2)/4644864+(-4372969*x)/6967296
    +28292143/27869184;

##### See also:

OrthoP , OrthoG , OrthoH , OrthoL , OrthoT , OrthoU , OrthoPolySum .

###

OrthoPoly -- Internal function for constructing orthogonal polynomials

Standard math library

##### Calling format:

OrthoPoly(name, n, par, x)

##### Parameters:

name - string containing name of orthogonal family

n - degree of the polynomial

par - list of values for the parameters

x - point to evaluate at

##### Description:

This function is used internally to construct orthogonal polynomials. It returns the "n"-th polynomial from the family "name" with parameters "par" at the point "x".

All known families are stored in the association list `KnownOrthoPoly`. The name serves as key. At the moment the following names are known to Yacas: `"Jacobi"`, `"Gegenbauer"`, `"Laguerre"`, `"Hermite"`, `"Tscheb1"`, and `"Tscheb2"`. The value associated to the key is a pure function that takes two arguments: the order `n` and the extra parameters `p`, and returns a list of two lists: the first list contains the coefficients `A,B` of the n=1 polynomial, i.e. A+B*x; the second list contains the coefficients `A,B,C` in the recurrence relation, i.e. P[n]=(A+B*x)*P[n-1]+C*P[n-2]. (There are only 3 coefficients in the second list, because none of the polynomials use C+D*x instead of C in the recurrence relation. This is assumed in the implementation!)

If the argument `x` is numerical, the function `OrthoPolyNumeric` is called. Otherwise, the function `OrthoPolyCoeffs` computes a list of coefficients, and `EvaluateHornerScheme` converts this list into a polynomial expression.

##### See also:

OrthoP , OrthoG , OrthoH , OrthoL , OrthoT , OrthoU , OrthoPolySum .

###

OrthoPolySum -- Internal function for computing series of orthogonal polynomials

Standard math library

##### Calling format:

OrthoPolySum(name, c, par, x)

##### Parameters:

`name` - string containing name of orthogonal family

`c` - list of coefficients

`par` - list of values for the parameters

`x` - point to evaluate at

##### Description:

This function is used internally to compute series of orthogonal polynomials. It is similar to the function `OrthoPoly` and returns the result of the summation of series of polynomials from the family `name` with parameters `par` at the point `x`, where `c` is the list of coefficients of the series.

The algorithm used to compute the series without first computing the individual polynomials is the Clenshaw-Smith recurrence scheme. See: Yudell L. Luke. Mathematical functions and their approximations. Academic Press, N. Y., 1975.

If the argument `x` is numerical, the function `OrthoPolySumNumeric` is called. Otherwise, the function `OrthoPolySumCoeffs` computes the list of coefficients of the resulting polynomial, and `EvaluateHornerScheme` converts this list into a polynomial expression.

##### See also:

OrthoPSum , OrthoGSum , OrthoHSum , OrthoLSum , OrthoTSum , OrthoUSum , OrthoPoly .

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, HeapSort , PrintList , 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 format:

    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 format:

    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 format:

    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 format:

    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 format:

    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 format:

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 format:

    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 format:

    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 format:

    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 format:

    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. Strangely, 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 format:

    List(expr1, expr2, ...)

##### Parameters:

`expr1`, `expr2` -- expressions making up the list

##### Description:

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 format:

    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 left unevaluated. The functions `UnList()` and `Hold()` both stop the process of evaluation.

##### 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 , Hold .

###

Listify -- Convert a function application to a list

Internal function

##### Calling format:

    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 format:

    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 format:

    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 format:

    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 format:

    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 format:

    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 format:

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 format:

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 format:

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

##### Examples:

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 format:

    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 format:

    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 format:

    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
CALL

    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 format:

    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 format:

    Push(stack, expr)

##### Parameters:

`stack` -- a list (which serves as the stack container)

`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 format:

    Pop(stack, n)

##### Parameters:

`stack` -- a list (which serves as the stack container)

`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 format:

    PopFront(stack)

##### Parameters:

`stack` -- a list (which serves as the stack container)

##### 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 format:

    PopBack(stack)

##### Parameters:

`stack` -- a list (which serves as the stack container)

##### 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 format:

    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.

`Swap()` works also on generic arrays.

##### 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 , ArrayCreate .

###

Count -- Count the number of occurrences of an expression

Standard math library

##### Calling format:

    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 format:

    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 format:

    Union(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 format:

    Difference(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 format:

    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 format:

    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 format:

    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 format:

    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 format:

    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 format:

    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 format:

    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 format:

    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 format:

    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 also:

IsAtom , NrArgs .

###

NrArgs -- Return number of top-level arguments

Standard math library

##### Calling format:

    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, HeapSort -- sort a list

Standard math library

##### Calling format:

    BubbleSort(list, compare)
    HeapSort(list, compare)

##### Parameters:

`list` -- list to sort

`compare` -- function used to compare elements of `list`

##### Description:

This command returns `list` after it is sorted using `compare` to compare elements. The function `compare` should accept two arguments, which will be elements of `list`, and compare them. It should return `True` if in the sorted list the second argument should come after the first one, and `False` otherwise.

The function `BubbleSort` uses the so-called "bubble sort" algorithm to do the sorting by swapping elements that are out of order. This algorithm is easy to implement, though it is not particularly fast. The sorting time is proportional to n^2 where n is the length of the list.

The function `HeapSort` uses a recursive algorithm "heapsort" and is much faster for large lists. The sorting time is proportional to n*Ln(n) where n is the length of the list.

##### Examples:

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

###

PrintList -- print list with padding

Standard math library

##### Calling format:

    PrintList(list)
    PrintList(list, padding);

##### Parameters:

`list` -- a list to be printed `padding` -- (optional) a string

##### Description:

Prints `list` and inserts the `padding` string between each pair of items of the list. Items of the list which are strings are printed without quotes, unlike `Write()`. Items of the list which are themselves lists are printed inside braces `{}`. If padding is not specified, a standard one is used (comma, space).

##### Examples:

    In> PrintList({a,b,{c, d}}, " .. ")
    Out> " a ..  b .. { c ..  d}";

##### See also:

Write , WriteString .

###

Table -- Evaluate while some variable ranges over interval

Standard math library

##### Calling format:

    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 format:

    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 .

: , @ , /@ , .. , NFunction .

# 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 format:

    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 format:

    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 format:

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 format:

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

##### Example:

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

##### See also:

Table .

###

NFunction -- make wrapper for numeric functions

Standard math library

##### Calling format:

    NFunction("newname","funcname", {arglist})

##### Parameters:

"newname" -- name of new function

`"funcname"` -- name of an existing function

`arglist` -- symbolic list of arguments

##### Description:

This function will define a function named "newname" with the same arguments as an existing function named "funcname". The new function will evaluate and return the expression "funcname(arglist)" only when all items in the argument list `arglist` are numbers, and return unevaluated otherwise.

This can be useful when plotting functions defined through other Yacas routines that cannot return unevaluated.

##### Example:

Suppose we need to define a complicated function `t(x)` which cannot be evaluated unless `x` is a number:

    In> t(x) := If(x<=0.5, 2*x, 2*(1-x));
    Out> True;
    In> t(0.2);
    Out> 0.4;
    In> t(x);
    In function "If" :
    bad argument number 1 (counting from 1)
    CommandLine(1) : Invalid argument

Then, we can use `NFunction()` to define a wrapper `t1(x)` around `t(x)` which will not try to evaluate `t(x)` unless `x` is a number.

    In> NFunction("t1", "t", {x})
    Out> True;
    In> t1(x);
    Out> t1(x);
    In> t1(0.2);
    Out> 0.4;

Now we can plot the function.

    In> GnuPlot(-0.1, 1.1, 30, t1(x))
    Out> True;

##### See also:

MacroRule .

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

# Control flow functions

###

MaxEvalDepth -- Set the maximum evaluation depth

Internal function

##### Calling format:

    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> 21430172143725346418968500981200036211228096234
    1106721488750077674070210224987224498639675763139171
    6255189345835106293650374290571384628087196915514939
    7149607869135549648461970842149210124742283755908364
    3060929499671638825347975351183310878921541258291423
    92955373084335320859663305248773674411336138752;

###

Hold -- Do not evaluate the argument

Internal function

##### Calling format:

    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.

The function `UnList()` also leaves its result unevaluated. Both functions stop the process of evaluation (no more rules will be applied).

##### Examples:

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

##### See also:

Eval , HoldArg , UnList .

###

Eval -- Evaluate the argument

Internal function

##### Calling format:

    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 format:

    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 format:

    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 format:

    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 format:

    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 format:

    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 format:

    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 format:

    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 format:

    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 format:

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

###

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

Standard math library

##### Calling format:

    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 format:

    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 format:

    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 format:

    expression /: patterns
    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 instead of `<--` which would be used in a global rule.

The `/:` operator traverses an expression much like `Subst` does, that is, top down, trying to apply the rules from the begining of the list of rules to the end of the list of rules. If the rules cannot be applied to an expression, it will try subexpressions of that expression and so on.

It might be necessary sometimes to use the `/::` operator, which repeatedly applies the `/:` operator until the result doesn't change any more. Caution is required, since rules can contradict each other, which could result in an infinite loop. To detect this situation, just use /: repeatedly on the expression. The repetitive nature should become apparent.

##### 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 format:

    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 the help browser with the html page as first argument. The default value 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 format:

    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 format:

    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 format:

    TraceRule(template) expr

##### Parameters:

`template` -- 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 "template", and the expression "expr" is evaluated. The template "template" is an example of the function to trace on. Specifically, all subexpressions with the same top-level operator and arity as "template" are shown. The subexpressions are displayed before (indicated with `TrEnter`) and after (`TrLeave`) evaluation. In between, the arguments are shown before and after evaluation (`TrArg`). Only functions defined in scripts can be traced.

This is useful for tracing a function that is called from within another function. This way you can see how your function behaves in the environment it is used in.

##### 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 , IsNumericList , 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 for "less than"

Standard math library

##### Calling format:

    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 for "greater than"

Standard math library

##### Calling format:

    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 for "less or equal"

Standard math library

##### Calling format:

    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 for "greater or equal"

Standard math library

##### Calling format:

    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 for "not equal"

Standard math library

##### Calling format:

    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 for equality of expressions

Standard math library

##### Calling format:

    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 below. 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;

##### See also:

!= , Equals .

###

Not -- Logical negation

Internal function

##### Calling format:

    Not expr

##### Parameters:

`expr` -- a boolean expression

##### Description:

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

##### 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 format:

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

##### Parameters:

a1, ..., aN - boolean values (may evaluate to `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 format:

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

##### Parameters:

a1, ..., aN - boolean expressions (may evaluate to `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, an unevaluated `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 format:

    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 format:

    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 format:

    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 for an even integer

Standard math library

##### Calling format:

    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 for an odd integer

Standard math library

##### Calling format:

    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 for a composite object

Internal function

##### Calling format:

    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 for an atom

Internal function

##### Calling format:

    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 for an string

Internal function

##### Calling format:

    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 for a number

Internal function

##### Calling format:

    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 for a list

Internal function

##### Calling format:

    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 .

###

IsNumericList -- test for a list of numbers

Standard math library

##### Calling format:

    IsNumericList({list})

##### Parameters:

`{list}` -- a list

##### Description:

Returns `True` when called on a list of numbers or expressions that evaluate to numbers using `N()`. Returns `False` otherwise.

##### See also:

N , IsNumber .

###

IsBound -- test for a bound variable

Internal function

##### Calling format:

    IsBound(var)

##### Parameters:

var - variable to test

##### Description:

This function tests whether the variable "var" is bound, ie. whether it has been assigned 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 for a Boolean value

Standard math library

##### Calling format:

    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 for a negative number

Standard math library

##### Calling format:

    IsNegativeNumber(n)

##### Parameters:

`n` - number to test

##### Description:

`IsNegativeNumber(n)` evaluates to `True` if n is (strictly) negative, i.e. if n<0. If `n` is not a number, the functions return `False`.

##### Examples:

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

##### See also:

IsNumber , IsPositiveNumber , IsNotZero , IsNegativeInteger , IsNegativeReal .

###

IsNegativeInteger -- Test for a negative integer

Standard math library

##### Calling format:

    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 for a positive number

Standard math library

##### Calling format:

    IsPositiveNumber(n)

##### Parameters:

`n` - number to test

##### Description:

`IsPositiveNumber(n)` evaluates to `True` if n is (strictly) positive, i.e. 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 for a positive integer

Standard math library

##### Calling format:

    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 for a nonzero number

Standard math library

##### Calling format:

    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 for a nonzero integer

Standard math library

##### Calling format:

    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 for an infinity

Standard math library

##### Calling format:

    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 for a numerically positive value

Standard math library

##### Calling format:

    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 for a numerically negative value

Standard math library

##### Calling format:

    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 for a constant

Standard math library

##### Calling format:

    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. `Pi` is considered a constant.

##### 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 -- try to prove statement

Standard math library

##### Calling format:

    CanProve(proposition)

##### Parameters:

proposition -- an expression with logical operations

##### 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 logical operations:

`Not` : negation, read as "not"

`And` : conjunction, read as "and"

`Or` : disjunction, read as "or"

`=>` : implication, read as "implies"

The abovementioned proposition would be represented by the following expression,

    ( (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 in the following way: in order to prove a 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, such as,

    True Or x --> True

etc. The above rules will translate a 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 format:

    %

##### 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 format:

    True
    False

##### Description:

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

##### See also:

And , Or , Not .

###

EndOfFile -- End-of-file marker

Internal function

##### Calling format:

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 format:

    Infinity

##### Description:

Infinity represents infinitely large values. It can be the result of certain calculations.

Note that for most analytic functions Yacas understands `Infinity` as a positive number. 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, pi

Standard math library

##### Calling format:

    Pi

##### Description:

Pi symbolically represents the exact value of pi. When the `N()` function is used, `Pi` evaluates to a numerical value according to the current precision. This is performed by the function `Pi()` which always returns the numerical value. It is probably better to use `Pi` than `Pi()`, because exact simplification will be possible.

##### Examples:

    In> Sin(3*Pi/2)
    Out> -1;
    In> Sin(3*Pi()/2)
    Out> Sin(4.7123889804);
    In> Pi+1
    Out> Pi+1;
    In> N(Pi)
    Out> 3.14159265358979323846;

##### See also:

Sin , Cos , Precision , N , Pi() .

###

Undefined -- Constant signifying an undefined result

Standard math library

##### Calling format:

    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 format:

    var := exp
    {var1, var2, ...} := {exp1, exp2, ...}
    var[i] := exp
    fn(param, ...) := exp

(all are of precedence 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/
    1307674368000+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
    /1307674368000+x^17/355687428096000-x^19/
    121645100408832000+x^21/51090942171709440000
    -x^23/25852016738884976640000+x^25/
    15511210043330985984000000;

The remedy is to evaluate the Taylor expansion immediately. Now the expansion is computed only once.

    In> f(a) := Eval(Taylor(x,0,25) Sin(x));
    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/
    1307674368000+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
    /1307674368000+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 format:

    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 format:

    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 format:

    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 format:

    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 format:

    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 format:

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 format:

    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 format:

    UniqueConstant()

##### 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 , TeXForm , CForm , Write , WriteString , Space , NewLine , FromFile , FromString , ToFile , ToString , Read , LispRead , ReadToken , Load , Use , DefLoad , FindFile , PatchLoad , Nl , V .

# Input/Output

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

###

FullForm -- Print an expression in LISP-format

Internal function

##### Calling format:

    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 format:

    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 format 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 format:

    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 format:

    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
                                         x    x
    Taylor( x , 0 , 5 , Sin( x ) ) = x - -- + ---
                                         6    120

    Out> True

##### See also:

PrettyForm .

###

TeXForm -- export expressions to LaTeX

Standard math library

##### Calling format:

    TeXForm(expr)

##### Parameters:

expr -- an expression to be exported

##### Description:

`TeXForm()` returns a string containing a LaTeX representation of the Yacas expression `expr`. Currently the exporter handles most expression types but not all.

##### Example:

    In> TeXForm(Sin(a1)+2*Cos(b1))
    Out> "$\sin a_{1} + 2 \cos b_{1}$";

##### See also:

PrettyForm , CForm , ShowPS .

###

CForm -- export expression to C code

Standard math library

##### Calling format:

    CForm(expr)

##### Parameters:

`expr` -- expression to be exported

##### Description:

`CForm()` returns a string containing a C/C++ code implementing the Yacas expression `expr`. Currently the exporter handles most expression types but not all.

##### Example:

    In> CForm(Sin(a1)+2*Cos(b1));
    Out> "sin(a1) + 2 * cos(b1)";

##### See also:

PrettyForm , TeXForm .

###

Write -- Low-level printing routine

Internal function

##### Calling format:

    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 format:

    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 format:

    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 format:

    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 format:

    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 format:

    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 format:

    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 format:

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() [ 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 format:

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 format:

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 format:

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)") 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 format:

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 format:

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 format:

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 closing brace \} (the end-of-list delimiter). 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 format:

    FindFile(name)

##### Parameters:

name - name of the file or directory 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.

`FindFile("")` returns the name of the default directory (the first one on the search path).

##### See also:

Load , DefaultDirectory .

###

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

Internal function

##### Calling format:

    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 format:

    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 .

###

V -- Verbose mode output

Standard math library

##### Calling format:

    V(expression)

##### Parameters:

`expression` - expression to be evaluated in verbose mode

##### Description:

The function `V(expression)` will evaluate the expression in verbose mode. Various parts of Yacas can show extra information about the work done while doing a calculation when using `V`.

##### Examples:

    In> Solve({x+2==0},{x})
    Out> {{-2}};
    In> V(Solve({x+2==0},{x}))
    Entering Solve
    From  x+2==0  it follows that  x  = -2
       x+2==0  simplifies to  True
    Leaving Solve
    Out> {{-2}};

##### See also:

Echo , N , Solve .

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

# String manipulation

###

SetStringMid -- Change a substring

Internal function

##### Calling format:

    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 format:

    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 format:

    Atom("string")
    String(atom)

##### Parameters:

atom - an atom

"string" - a string

##### Description:

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 format:

    ConcatStrings(strings)

##### Parameters:

strings - one or more strings

##### Description:

Concatenates strings.

##### Examples:

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

##### See also:

: .

###

LocalSymbols -- Create unique local symbols with given prefix

Standard math library

##### Calling format:

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

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

##### Examples:

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

##### See also:

UniqueConstant .

###

PatchString -- Execute commands between `<?` and `?>` in strings

Internal function

##### Calling format:

    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  ");
    Out> "Two plus three is 5 ";

##### See also:

PatchLoad .

GetYacasPID , ShowPS , MakeFunctionPlugin , GnuPlot , Version , Vi .

# Platform-dependent packages

Certain facilities have been developed for use on the Unix platform, which is currently the main development platform for Yacas. These packages are described in this chapter.

###

GetYacasPID -- obtain Yacas process number

Unix-specific add-on

##### Calling format:

    GetYacasPID()

##### Description:

Returns an integer containing the process number (PID) of the Yacas session.

Requires: a Unix shell.

##### Example:

    In> GetYacasPID()
    Out> 26456;

##### See also:

SystemCall .

###

ShowPS -- view equations graphically

Unix-specific add-on

##### Calling format:

    ShowPS(expr)

##### Parameters:

`expr` -- any expression (not evaluated)

##### Description:

Exports a Yacas expression to LaTeX, generates a Postscript file and shows it in a viewer. The free viewer `gv` must be available on the Unix shell path. An alternative viewer can be specified by assigning to the global variable PSViewCommand.

Requires: a Unix shell, `latex`, `dvips`, `gv` or another Postscript viewer.

##### Example:

    In> [ PSViewCommand := "ghostview"; \
      ShowPS(x+2*Sin(x)); ]
    Expression exported as /tmp/yacas-tmp
    file-28802.tex
    Out> True;

##### See also:

TeXForm .

###

MakeFunctionPlugin -- compile numerical functions into plugins

Unix-specific add-on

##### Calling format:

    MakeFunctionPlugin("name", body)

##### Parameters:

`"name"` -- string, name of a new function

`body` -- expression, function of arguments, must evaluate to a function of some variables.

##### Description:

Compiles an external plugin library that computes a user-defined numerical function and dynamically loads it into Yacas, enabling a new function called "name".

Requires: a Unix shell, a compiler named `c++` with ELF `.so` support, Yacas headers in `FindFile("")/include`; current directory must be writable.

The `body` expression must be a `CForm()`-exportable function of the arguments and may contain numerical constants. `Pi` is allowed and will be converted to floating-point.

All arguments and the return value of the function are assumed to be double precision real numbers. The result of passing a non-numerical argument will be an unevaluated expression.

    Example:

    In> MakeFunctionPlugin("f1", {x,y}, Sin(x/y))
    Function f1(x,y) loaded from
    plugins.tmp/libf1_plugin_cc.so
    Out> True;
    In> f1(2,3)
    Out> 0.618369803069736989620253;
    In> f1(x,5)
    Out> f1(x,5);

The function creates the following files in subdirectory `plugins.tmp/` of current directory:

- `f1_plugin.h`, `f1_plugin.cc` -- C++ code of the plugin; the function in the above example is implemented in C++ as

      double f1_plugin_cc(double x, double y)
        { return sin(x/y); }

- `f1_plugin.stub` -- Yacas-language stub
- `f1_plugin_api.cc` -- Yacas-generated C++ stub
- `f1_plugin_api.description` - Yacas-generated documentation
- `f1_plugin.compile` -- command line to compile
- `libf1_plugin_cc.so` -- compiled plugin Note that all files have names matching "`*_plugin*`".

After creating these files, `MakeFunctionPlugin()` will:

- Run a `c++` compiler command; if compilation fails, all error messages will appear on the screen;
- Load resulting .so object with `DllLoad()`;
- Print an information message on success.

If you call `MakeFunctionPlugin()` repeatedly to define a function with the same name, old files will be overwritten and old libraries will be unloaded with `DllUnload()`.

##### See also:

DllLoad , DllUnload , DllEnumerate , CForm .

###

GnuPlot -- plot functions of one variable

Unix-specific add-on

##### Calling format:

    GnuPlot(x1, x2, numpoints, function)
    GnuPlot(x1, x2, numpoints, {expression_list}

##### Parameters:

`x1`, `x2` -- interval in which to plot the function

`numpoints` -- number of points in the interval

`function` -- unevaluated expression containing a variable

`expression_list` -- list of functions to plot

##### Description:

Requires `gnuplot` software. Calls the `gnuplot` plotting program to plot a graph of the given function in the given range, using `numpoints` equally spaced points. Creates data files `gnuplot.in` and `gnudata.in` in the `plot.tmp/` subdirectory of the current working directory, so you can use those files to prepare better graphs. If several functions are to be plotted at once, it creates files `gnudata.in1`, `gnudata.in2` etc.

Most frequently encountered problem: the `function` parameter must evaluate to an expression that contains a variable. Test your function for this! If you have defined some `f(x)` which accepts a number but does not accept an undefined variable, `GnuPlot()` will fail to plot it. Use `NFunction()` to overcome this difficulty.

##### Examples:

    In> f(x) := Cos(( Abs(Pi/x))^1.5);
    Out> True;
    In> GnuPlot(-1, 1, 101, f(x) );
    GnuPlot: created file gnuplot.tmp/gnudata.in
    Out> True;

We find that 101 is not enough points to accurately represent this function. However, calculations with more points would take a long time. To speed up the calculation, compile this function online:

    In> MakeFunctionPlugin("f1", f(x));
    Function f1(x) loaded from plugins.tmp/
    libf1_plugin_cc.so
    Out> True;
    In> GnuPlot(-1, 1, 10001, f1(x))
    GnuPlot: created file gnuplot.tmp/gnudata.in
    Out> True;

##### See also:

NFunction , MakeFunctionPlugin .

###

Version -- Show version of Yacas

Internal function

##### Calling format:

    Version()

##### Description:

The function `Version()` returns a string representing the version of the currently running Yacas interpreter.

##### Examples:

    In> Version()
    Out> "1.0.48rev3";
    In> LessThan(Version(), "1.0.47")
    Out> False;
    In> GreaterThan(Version(), "1.0.47")
    Out> True;

The last two calls show that the `LessThan` and `GreaterThan` functions can be used for comparing version numbers. This method is only guaranteed, however, if the version is always expressed in the form `d.d.dd` as above.

##### See also:

LessThan , GreaterThan .

###

Vi -- Edit a file or function

Unix-specific add-on

##### Calling format:

    Vi(filename);
    Vi(functionname);

##### Parameters:

`filename` - name of a file to edit

`functionname` - name of a function to find for editing

##### Description:

`Vi` will try to edit a file, or if the argument passed is a function, it will try to edit the file the function is defined in. It will try to do so by invoking the editor `vi`.

It finds the function by scanning the `*.def` files that have been reported to the system. (`Vi` calls `FindFunction` for this.) If editing a function, the command will jump directly to the first occurrence of the name of the function in the file (usually the beginning of a definition of a function).

For `Vi()` to be really useful, you need to start Yacas from the `scripts/` directory in the development tree. In that case, `FindFunction()` will return the filename under that directory. Otherwise, `FindFunction()` will return a name in the systemwide installation directory (or directory specified in the `--rootdir` option).

##### Examples:

    In> Vi("yacasinit.ys")
    Out> True;
    In> Vi("Sum")
    Out> True;

##### See also:

FindFunction .

/*, */, // , Prog, [, ] , Check , Bodied, Infix, Postfix, Prefix , IsBodied, IsInfix, IsPostfix, IsPrefix , OpPrecedence, OpLeftPrecedence, OpRightPrecedence , RightAssociative , LeftPrecedence, RightPrecedence , RuleBase , Rule , HoldArg , Retract , UnFence , HoldArgNr , RuleBaseArgList , MacroSet, MacroClear, MacroLocal, MacroRuleBase, MacroRule , Back-quoting , SetExtraInfo, GetExtraInfo , GarbageCollect , CurrentFile, CurrentLine , FindFunction , Secure .

# Programming

This chapter describes functions useful for writing Yacas scripts.

###

/*, */, // -- comments

Internal function

##### Calling format:

    /* comment */
    // comment

##### Description:

Introduce a comment block in a source file, similar to C++ comments. `//` makes everything until the end of the line a comment, while `/*` and `*/` may delimit a multi-line comment.

##### Examples:

    a+b; // get result
    a + /* add them */ b;

###

Prog, [, ] -- block of statements

Internal function

##### Calling format:

    Prog(statement1, statement2, ...)
    [ statement1; statement2; ... ]

##### Parameters:

statement1, statement2 -- expressions

##### Description:

The `Prog()` and the `[ ... ]` constuct have the same effect: they evaluate all arguments in order and return the result of the last evaluated expression.

`Prog(a,b);` is the same as typing `[a;b;];` and is very useful for writing out function bodies. The `[...]` construct is a syntactically nicer version of the `Prog()` call; it is converted into `Prog(...)` during the parsing stage.

###

Check -- report errors

Internal function

##### Calling format:

    Check(predicate,"error text")

##### Parameters:

`predicate` -- expression returning `True` or `False`

##### Description:

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 text`. Use this to assure that some condition is met during evaluation of expressions (guarding against internal errors).

###

Bodied, Infix, Postfix, Prefix -- define function syntax

Internal function

##### Calling format:

    Bodied("op", precedence)
    Infix("op")
    Infix("op", precedence)
    Postfix("op")
    Postfix("op", precedence)
    Prefix("op")
    Prefix("op", precedence)

##### Parameters:

`"op"` -- string, the name of a function

`precedence` -- nonnegative integer (evaluated)

##### Description:

Declares a function for the parser to understand as a bodied, infix, postfix, or prefix operator. Function name can be any string but meaningful usage would require it to be either made up entirely of letters or entirely of non-letter characters (such as "+", ":" etc.). Precedence can be specified (will be 0 by default).

##### Examples:

    In> YY x := x+1;
    CommandLine(1) : Error parsing expression

    In> Prefix("YY", 2)
    Out> True;
    In> YY x := x+1;
    Out> True;
    In> YY YY 2*3
    Out> 12;
    In> Infix("##", 5)
    Out> True;
    In> a ## b ## c
    Out> a##b##c;

##### See also:

IsBodied , OpPrecedence .

###

IsBodied, IsInfix, IsPostfix, IsPrefix -- check for function syntax

Internal function

##### Calling format:

    IsBodied("op")
    IsInfix("op")
    IsPostfix("op")
    IsPrefix("op")

##### Parameters:

`"op"` -- string, the name of a function

##### Description:

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

##### Examples:

    In> IsInfix("+");
    Out> True;
    In> IsBodied("While");
    Out> True;
    In> IsBodied("Sin");
    Out> False;
    In> IsPostfix("!");
    Out> True;

##### See also:

Bodied , OpPrecedence .

###

OpPrecedence, OpLeftPrecedence, OpRightPrecedence -- get operator precedence

Internal function

##### Calling format:

    OpPrecedence("op")
    OpLeftPrecedence("op")
    OpRightPrecedence("op")

##### Parameters:

`"op"` -- string, the name of a function

##### Description:

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

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

##### Examples:

    In> OpPrecedence("+")
    Out> 6;
    In> OpLeftPrecedence("!")
    Out> 0;

###

RightAssociative -- declare associativity

Internal function

##### Calling format:

    RightAssociative("op")

##### Parameters:

`"op"` -- string, the name of a function

##### Description:

This makes the operator right-associative. For 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. (All infix operators are by default left-associative until they are declared to be right-associative.)

##### See also:

OpPrecedence .

###

LeftPrecedence, RightPrecedence -- set operator precedence

Internal function

##### Calling format:

    LeftPrecedence("op",precedence)
    RightPrecedence("op",precedence)

##### Parameters:

`"op"` -- string, the name of a function

`precedence` -- nonnegative integer

##### Description:

`"op"` 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 expressions like `a-(b-c)` correctly. Thus, `a+b+c` is the same as `a+(b+c)`, but `a-(b-c)` is not the same as `a-b-c`.

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

##### See also:

OpPrecedence , OpLeftPrecedence , OpRightPrecedence , RightAssociative .

###

RuleBase -- define function name

Internal function

##### Calling format:

    RuleBase("operator",{params})

##### Description:

Define a new rules table entry for a function "operator", with `params` as the parameter list.

###

Rule -- define rule

##### Calling format:

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

##### Description:

Define a rule for the function "operator" with "arity", "precedence", "predicate" and "body". The "precedence" goes from low to high: rules with low precedence will be applied first. The arity for a rules database equals the number of arguments. Different rules 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 -- mark argument as not evaluated

Internal function

##### Calling format:

    HoldArg("operator",parameter)

##### Parameters:

`"operator"` -- string, name of a function

`parameter` -- atom, symbolic name of parameter

##### Description:

Specify that parameter 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.

The `parameter` must be an atom from the list of symbolic arguments used when calling `RuleBase`.

##### See also:

RuleBase , HoldArgNr , RuleBaseArgList .

###

Retract -- erase rules for a function

Internal function

##### Calling format:

    Retract("function",arity)

##### Parameters:

`"function"` -- string, name of function

`arity` -- positive integer

##### Description:

Remove a rulebase for the function named `"function"` with the specific `arity`, if it exists at all. This will make Yacas forget all rules defined for a given function. Rules for functions with the same name but different arities are not affected.

Assignment `:=` of a function does this to the function being (re)defined.

##### See also:

RuleBaseArgList , RuleBase , := .

###

UnFence -- change local variable scope for a function

Internal function

##### Calling format:

    UnFence("operator",arity)

##### Parameters:

`"operator"` -- string, name of function

`arity` -- positive integers

##### Description:

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

The standard library functions `For` and `ForEach` use `UnFence()`.

###

HoldArgNr -- specify argument as not evaluated

Standard math library

##### Calling format:

    HoldArgNr("function", arity, argNum)

##### Parameters:

`"function"` -- string, function name

`arity`, `argNum` -- positive integers

##### Description:

Declares the argument numbered `argNum` of the function named `"function"` with specified `arity` to be unevaluated ("held"). Useful if you don't know symbolic names of parameters, for instance, when the function was not declared using an explicit `RuleBase` call. Otherwise you could use `HoldArg()`.

##### See also:

HoldArg , RuleBase .

###

RuleBaseArgList -- obtain list of arguments

Internal function

##### Calling format:

    RuleBaseArgList("operator", arity)

##### Parameters:

`"operator"` -- string, name of function

`arity` -- integer

##### Description:

Returns a list of atoms, symbolic parameters specified in the `RuleBase()` call for the function named `"operator"` with the specific `arity`.

##### See also:

RuleBase , HoldArgNr , HoldArg .

###

MacroSet, MacroClear, MacroLocal, MacroRuleBase, MacroRule -- define rules in functions

##### Description:

These functions have the same effect as their non-macro counterparts, except that their arguments are evaluated before the required action is performed. This is useful in macro-like procedures or in functions that need to define new rules based on parameters.

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

##### See also:

Set , Clear , Local , RuleBase , Rule , Back-quoting .

###

Back-quoting -- LISP back-quoting, macro expansion

Internal function

##### Calling format:

    `(expression)

##### Parameters:

`expression` -- expression containing "`@var`" to substitute the value of variable "`var`"

##### Description:

Back-quoting is a macro substitution mechanism. A backquoted `expression` is evaluated in two stages: first, variables prefixed by `@` are evaluated inside an expression, and second, the new expression is evaluated.

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

The expression should contain some variables (assigned atoms) with the special prefix operator `@`. Variables prefixed by `@` will be evaluated even if they are inside function arguments that are normally not evaluated (e.g. functions declared with `HoldArg()`). If the `@var` pair is in place of a function name, e.g. "`@f(x)`", then at the first stage of evaluation the function name itself is replaced, not the return value of the function (see example); so at the second stage of evaluation, a new function may be called.

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

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

##### Examples:

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

    In> Decl(f1,f2) := \
    In>   `(@f1(x_IsNumber) <-- N(@f2(x)));
    Out> True;
    In> Decl(nSin,Sin)
    Out> True;
    In> Sin(1)
    Out> Sin(1);
    In> nSin(1)
    Out> 0.8414709848;

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

    In> SetF(var,func,value) := \
    In>     `(Set(@var,@func(@value)));
    Out> True;
    In> SetF(a,Sin,x)
    Out> True;
    In> a
    Out> Sin(x);

##### See also:

MacroSet , MacroLocal , MacroRuleBase , Hold , HoldArg .

###

SetExtraInfo, GetExtraInfo -- annotate objects with additional information

Internal function

##### Calling format:

    SetExtraInfo(expr,tag)
    GetExtraInfo(expr)

##### Parameters:

`expr` -- any expression

`tag` -- tag information (any other expression)

##### Description:

Sometimes it is useful to be able to add extra tag information to "annotate" objects or to label them as having certain "properties". The functions `SetExtraInfo` and `GetExtraInfo` enable this.

The function `SetExtraInfo` returns the tagged expression, leaving the original expression alone. This means there is a common pitfall: be sure to assign the returned value to a variable, or the tagged expression is lost when the temporary object is destroyed.

The original expression is left unmodified, and the tagged expression returned, in order to keep the atomic objects small. To tag an object, a new type of object is created from the old object, with one added property (the tag). The tag can be any expression whatsoever.

The function `GetExtraInfo(x)` retrieves this tag expression from an object `x`. If an object has no tag, it looks the same as if it had a tag with value `False`.

No part of the Yacas core uses tags in a way that is visible to the outside world, so for specific purposes a programmer can devise a format to use for tag information. Association lists (hashes) are a natural fit for this, although it is not required and a tag can be any object (except the atom `False` because it is indistinguishable from having no tag information). Using association lists is highly advised since it is most likely to be the format used by other parts of the library, and one needs to avoid clashes with other library code. Typically, an object will either have no tag or a tag which is an associative list (perhaps empty). A script that uses tagged objects will check whether an object has a tag and if so, will add or modify certain entries of the association list, preserving any other tag information.

Note that `FlatCopy()` currently does not copy the tag information (see examples).

##### Examples:

    In> a:=2*b
    Out> 2*b;
    In> a:=SetExtraInfo(a,{{"type","integer"}})
    Out> 2*b;
    In> a
    Out> 2*b;
    In> GetExtraInfo(a)
    Out> {{"type","integer"}};
    In> GetExtraInfo(a)["type"]
    Out> "integer";
    In> c:=a
    Out> 2*b;
    In> GetExtraInfo(c)
    Out> {{"type","integer"}};
    In> c
    Out> 2*b;
    In> d:=FlatCopy(a);
    Out> 2*b;
    In> GetExtraInfo(d)
    Out> False;

##### See also:

Assoc , := .

###

GarbageCollect -- do garbage collection on unused memory

Internal function

##### Calling format:

    GarbageCollect()

##### Description:

`GarbageCollect()` garbage-collects unused memory. The Yacas system uses a reference counting system for most objects, so this call is usually not necessary.

Reference counting refers to bookkeeping where in each object a counter is held, keeping track of the number of parts in the system using that object. When this count drops to zero, the object is automatically removed. Reference counting is not the fastest way of doing garbage collection, but it can be implemented in a very clean way with very little code.

Among the most important objects that are not reference counted are the strings. `GarbageCollect()` collects these and disposes of them when they are not used any more.

`GarbageCollect()` is useful when doing a lot of text processing, to clean up the text buffers. It is not highly needed, but it keeps memory use low.

###

CurrentFile, CurrentLine -- show current file and line of input

Internal function

##### Calling format:

    CurrentFile()
    CurrentLine()

##### Description:

The functions `CurrentFile()` and `CurrentLine()` return a string with the file name of the current file and the current line of input respectively.

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

    tst() := Echo({CurrentFile(),CurrentLine()});

which can then be spread out over the input file at various places, to see how far the interpreter reaches before an error occurs.

##### See also:

Echo .

###

FindFunction -- find the file where a function is defined

Internal function

##### Calling format:

    FindFunction(function)

##### Parameters:

`function` -- string, the name of a function

##### Description:

This function is useful for quickly finding the file where a standard library function is defined. It is likely to only be useful for developers. The function `FindFunction()` scans the `.def` files that were loaded at start-up. This means that functions that were not defined in `.def` files, but were loaded directly, will not be found with `FindFunction()`.

##### Examples:

    In> FindFunction("Sum")
    Out> "sums.rep/code.ys";
    In> FindFunction("Integrate")
    Out> "integrate.rep/code.ys";

##### See also:

Vi .

###

Secure -- guard the host OS

Internal function

##### Calling format:

    Secure(body)

##### Description:

`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, e.g. a script sent over the Internet to be evaluated on a remote computer.

##### See also:

SystemCall .

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

# Built-in (core) functions

Yacas comes with a small core of built-in functions and a large library of user-defined functions. Some of these core functions are documented in this chapter.

It is important for a developer to know which functions are built-in and cannot be redefined or `Retract`-ed. Also, core functions may be somewhat faster to execute than functions defined in the script library. All core functions are listed in the file `yacasapi.cpp` in the `src/` subdirectory of the Yacas source tree. The declarations typically look like this:

    SetCommand(LispSubtract, "MathSubtract");

Here `LispSubtract` is the Yacas internal name for the function and `MathSubtract` is the name visible to the Yacas language. Built-in bodied functions and infix operators are declared in the same file.

##

Full listing of core functions

The following Yacas functions are currently declared in `yacasapi.cpp` as core functions:

    =
    And
    ApplyPure
    ArrayCreate
    ArrayGet
    ArraySet
    ArraySize
    Atom
    Berlekamp
    BitAnd
    BitOr
    BitXor
    Bodied
    CTokenizer
    Check
    Clear
    Concat
    ConcatStrings
    CurrentFile
    CurrentLine
    DefLoad
    DefaultDirectory
    DefaultTokenizer
    Delete
    DestructiveDelete
    DestructiveInsert
    DestructiveReplace
    DestructiveReverse
    DllEnumerate
    DllLoad
    DllUnload
    Equals
    Eval
    FastArcCos
    FastArcSin
    FastArcTan
    FastAssoc
    FastCos
    FastExp
    FastLog
    FastPower
    FastSin
    FastTan
    FindFile
    FindFunction
    FlatCopy
    FromBase
    FromFile
    FromString
    FullForm
    GarbageCollect
    GenericTypeName
    GetExtraInfo
    GetPrecision
    GreaterThan
    Head
    Hold
    HoldArg
    If
    Infix
    Insert
    IsAtom
    IsBodied
    IsBound
    IsFunction
    IsGeneric
    IsInfix
    IsInteger
    IsList
    IsNumber
    IsPostfix
    IsPrefix
    IsString
    LazyGlobal
    LeftPrecedence
    Length
    LessThan
    LispRead
    List
    Listify
    Load
    Local
    LocalSymbols
    MacroClear
    MacroLocal
    MacroRule
    MacroRuleBase
    MacroRulePattern
    MacroSet
    MathAbs
    MathAdd
    MathAnd
    MathArcCos
    MathArcSin
    MathArcTan
    MathCeil
    MathCos
    MathDiv
    MathDivide
    MathExp
    MathFac
    MathFloor
    MathGcd
    MathLog
    MathMod
    MathMultiply
    MathNot
    MathNth
    MathOr
    MathPi
    MathPower
    MathSin
    MathSqrt
    MathSubtract
    MathTan
    MaxEvalDepth
    Not
    OpLeftPrecedence
    OpPrecedence
    OpRightPrecedence
    Or
    PatchLoad
    PatchString
    PatternCreate
    PatternMatches
    Postfix
    Precision
    Prefix
    PrettyPrinter
    Prog
    Read
    ReadToken
    Replace
    Retract
    RightAssociative
    RightPrecedence
    Rule
    RuleBase
    RuleBaseArgList
    RuleBaseDefined
    RulePattern
    Secure
    Set
    SetExtraInfo
    SetStringMid
    ShiftLeft
    ShiftRight
    String
    StringMid
    Subst
    SystemCall
    Tail
    ToBase
    ToFile
    ToString
    TraceExp
    TraceRule
    TraceStack
    Type
    UnFence
    UnList
    Use
    While
    Write
    WriteString
    XmlExplodeTag
    XmlTokenizer
    `

In addition, the following functions are declared with special syntax and precedence:

`@` --- prefix (prec. `0`).

`BackQuote` --- bodied (prec. `KMaxPrecedence`).

`FromFile` --- bodied (prec. `KMaxPrecedence`).

`FromString` --- bodied (prec. `KMaxPrecedence`).

`LocalSymbols` --- bodied (prec. `KMaxPrecedence`).

`MacroRule` --- bodied (prec. `KMaxPrecedence`).

`MacroRulePattern` --- bodied (prec. `KMaxPrecedence`).

`Rule` --- bodied (prec. `KMaxPrecedence`).

`RulePattern` --- bodied (prec. `KMaxPrecedence`).

`Subst` --- bodied (prec. `KMaxPrecedence`).

`ToFile` --- bodied (prec. `KMaxPrecedence`).

`ToString` --- bodied (prec. `KMaxPrecedence`).

`TraceRule` --- bodied (prec. `KMaxPrecedence`).

`While` --- bodied (prec. `KMaxPrecedence`).

`_` --- prefix (prec. `0`).

`_` --- infix (prec. `0`).

``` --- prefix (prec. `0`).

###

MathNot -- built-in logical "not"

Internal function

##### Calling format:

    MathNot(expression)

##### Description:

Returns "False" if "expression" evaluates to "True", and vice versa.

###

MathAnd -- built-in logical "and"

##### Calling format:

    MathAnd(...)

##### Description:

Lazy logical `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 of the arguments is `False`, `And` 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 -- built-in logical "or"

Internal function

##### Calling format:

    MathOr(...)

`MathOr` is the basic logical "or" function. Similarly to `And`, it is lazy-evaluated. `And(...)` and `Or(...)` do also exist, defined in the script library. You can redefine them as infix operators yourself, so you have the choice of precedence. In the standard scripts they are in fact declared as infix operators, so you can write `expr1 And expr`.

###

BitAnd, BitOr, BitXor -- bitwise arithmetic

Internal function

##### Calling format:

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

##### Description:

These functions return bitwise "and", "or" and "xor" of two numbers.

###

Equals -- check equality

Internal function

##### Calling format:

    Equals(a,b)

##### Description:

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.

###

GreaterThan, LessThan -- comparison predicates

Internal function

##### Calling format:

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

##### Parameters:

`a`, `b` -- numbers or strings

##### Description:

Comparing numbers or strings (lexicographically).

##### Example:

    In> LessThan(1,1)
    Out> False;
    In> LessThan("a","b")
    Out> True;

###

Math... -- arbitrary-precision math functions

Internal function

##### Calling format:

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)

##### Description:

Calculation of sin, cos, tan and other mathematical functions. The argument must 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... -- double-precision math functions

Internal function

##### Calling format:

FastExp(x), FastLog(x) (natural logarithm), FastPower(x,y), FastSin(x), FastCos(x), FastTan(x), FastArcSin(x), FastArcCos(x), FastArcTan(x)

##### Description:

Versions of these functions using the internal C++ version. These should then at least be faster than the arbitrary precision versions.

###

ShiftLeft, ShiftRight -- built-in bit shifts

Internal function

##### Calling format:

    ShiftLeft(expr,bits)
    ShiftRight(expr,bits)

##### Description:

Shift bits to the left or to the right.

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

# The Yacas plugin structure

Yacas supports dynamically loading libraries at runtime. This chapter describes functions for working with plugins.

The plugin feature allows Yacas 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 module `cstubgen` (currently still under 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 module `cstubgen` 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 file `makefile.plugin` is configured to automatically convert these to the required C++ files. See also an essay on plugins for a worked-out example.

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, DllUnload, DllEnumerate -- manipulate plugins

Internal function

##### Calling format:

    DllLoad(file)
    DllUnload(file)
    DllEnumerate()

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

`DllUnload` unloads a dynamic link library previously loaded with `DllLoad`. Note the dll file name has to be exactly the same, or the system will not be able to determine which dll to unload. It will scan all the dll files, and delete the first one found to exactly match, and return silently if it didn't find the dll. `DllUnload` always returns `True`.

`DllEnumerate()` returns a list with all loaded dynamic link libraries.

##### Example:

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

###

StubApiCStart -- start of C++ plugin API

Standard math library

##### Calling format:

    StubApiCStart()

##### 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 -- declare integer constant in plugin

Standard math library

##### Calling format:

    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 -- declare include file in plugin

Standard math library

##### Calling format:

    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("\")

and for user include file:

    StubApiCInclude("\"GL/gl.h\"")

##### See also:

StubApiCStart , StubApiCShortIntegerConstant , StubApiCFunction , StubApiCFile , StubApiCSetEnv .

###

StubApiCFunction -- declare C++ function in plugin

Standard math library

##### Calling format:

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

##### Parameters:

`returntype` -- return type of new 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 new 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 an OpenGL function `glVertex3d` that accepts three doubles and returns void:

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

##### See also:

StubApiCStart , StubApiCShortIntegerConstant , StubApiCInclude , StubApiCFile , StubApiCSetEnv .

###

StubApiCRemark -- documentation string in plugin

Standard math library

##### Calling format:

    StubApiCRemark(string)

##### Parameters:

`string` -- comment 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 -- access Yacas environment in plugin

Standard math library

##### Calling format:

    StubApiCSetEnv(func)

##### Parameters:

`func` -- name of the 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 -- set file name for plugin API

Standard math library

##### Calling format:

    StubApiCFile(basename)

##### Parameters:

`basename` -- name 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 -- declare C struct in plugin

Standard math library

##### Calling format:

    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:

StubApiCFunction .

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 -- check for generic object

Internal function

##### Calling format:

    IsGeneric(object)

##### Description:

Returns `True` if an object is of a generic object type.

###

GenericTypeName -- get type name

Internal function

##### Calling format:

    GenericTypeName(object)

##### Description:

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

EG

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

###

ArrayCreate -- create array

Internal function

##### Calling format:

    ArrayCreate(size,init)

##### Description:

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

###

ArraySize -- get array size

Internal function

##### Calling format:

    ArraySize(array)

##### Description:

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

###

ArrayGet -- fetch array element

Internal function

##### Calling format:

    ArrayGet(array,index)

##### Description:

Returns 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 -- set array element

Internal function

##### Calling format:

    ArraySet(array,index,element)

##### Description:

Sets the element at position index in the array passed to the value passed in as argument to element. Arrays are treated as base-one, so `index` set to 1 would set first element.

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

###

ArrayCreateFromList -- convert list to array

Internal function

##### Calling format:

    ArrayCreateFromList(list)

##### Description:

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

###

ListFromArray -- convert array to list

Internal function

##### Calling format:

    ListFromArray(array)

##### Description:

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

Verify, TestYacas, LogicVerify , KnownFailure , RoundTo , VerifyArithmetic, VerifyDiv .

# The Yacas test suite

This chapter describes commands used for verifying correct performance of Yacas.

Yacas comes with a test suite which can be found in the directory `tests/`. Typing

    make test

on the command line after Yacas was built will run the test. This test can be run even before `make install`, as it only uses files in the local directory of the Yacas source tree. The default extension for test scripts is `.yts` (Yacas test script).

The verification commands described in this chapter only display the expressions that do not evaluate correctly. Errors do not terminate the execution of the Yacas script that uses these testing commands, since they are meant to be used in test scripts.

###

Verify, TestYacas, LogicVerify -- Verifying equivalence of two expressions

Standard math library

##### Calling format:

    Verify(question,answer)
    TestYacas(question,answer)
    LogicVerify(question,answer)

##### Parameters:

`question` -- expression to check for

`answer` -- expected result after evaluation

##### Description:

The commands `Verify`, `TestYacas`, `LogicVerify` can be used to verify that an expression is equivalent to a correct answer after evaluation. All three commands return `True` or `False`.

For most calculations, the demand that two expressions are equal syntactically is too stringent. The Yacas system might change at various places in the future, but 1+x would still be equivalent, from a mathematical point of view, to x+1.

The general problem of deciding that two expressions a and b are equivalent, which is the same as saying that a-b=0 , is generally hard to decide on. The following commands solve this problem by having domain-specific comparisons.

The comparison commands do the following comparison types:

- `Verify` -- verify for literal equality. This is the fastest and simplest comparison, and can be used for testing that an expression simplifies to for instance 2.
- `TestYacas` -- compare two expressions after simplification for multivariate polynomials. If the two arguments are equivalent multivariate polynomials, this test succeeds. `TestYacas` uses `Simplify()`.
- `LogicVerify` -- Perform a test by using `CanProve` to verify that from `question` the expression `answer` follows. This test command is used for testing the logic theorem prover in Yacas.

##### Examples:

    In> Verify(1+2,3)
    Out> True;
    In> Verify(x*(1+x),x^2+x)
    ******************
    x*(x+1) evaluates to x*(x+1) which differs
      from x^2+x
    ******************
    Out> False;
    In> TestYacas(x*(1+x),x^2+x)
    Out> True;
    In> Verify(a And c Or b And Not c,a Or b)
    ******************
     a And c Or b And Not c evaluates to  a And c
      Or b And Not c which differs from  a Or b
    ******************
    Out> False;
    In> LogicVerify(a And c Or b And Not c,a Or b)
    Out> True;
    In> LogicVerify(a And c Or b And Not c,b Or a)
    Out> True;

##### See also:

Simplify , CanProve , KnownFailure .

###

KnownFailure -- Mark a test as a known failure

Standard math library

##### Calling format:

    KnownFailure(test)

##### Parameters:

`test` -- expression that should return False on failure

##### Description:

The command `KnownFailure` marks a test as known to fail by displaying a message to that effect on screen.

This might be used by developers when they have no time to fix the defect, but do not wish to alarm users who download Yacas and type `make test`.

##### Examples:

    In> KnownFailure(Verify(1,2))
    Known failure:
    ******************
     1 evaluates to  1 which differs from  2
    ******************
    Out> False;
    In> KnownFailure(Verify(1,1))
    Known failure:
    Failure resolved!
    Out> True;

##### See also:

Verify , TestYacas , LogicVerify .

###

RoundTo -- Round a real-valued result to a set number of digits

Standard math library

##### Calling format:

    RoundTo(number,precision)

##### Parameters:

`number` -- number to round off

`precision` -- precision to use for round-off

##### Description:

The function `RoundTo` rounds a floating point number to a specified precision, allowing for testing for correctness using the `Verify` command.

##### Examples:

    In> N(RoundTo(Exp(1),30),30)
    Out> 2.71828182110230114951959786552;
    In> N(RoundTo(Exp(1),20),20)
    Out> 2.71828182796964237096;

##### See also:

Verify , VerifyArithmetic , VerifyDiv .

###

VerifyArithmetic, VerifyDiv -- Special purpose arithmetic verifiers

Standard math library

##### Calling format:

    VerifyArithmetic(x,n,m)
    RandVerifyArithmetic(n)
    VerifyDiv(u,v)

##### Parameters:

`x`, `n`, `m`, `u`, `v` -- integer arguments

##### Description:

The commands `VerifyArithmetic` and `VerifyDiv` test a mathematic equality which should hold, testing that the result returned by the system is mathematically correct according to a mathematically provable theorem.

`VerifyArithmetic` verifies for an arbitrary set of numbers x, n and m that

(x^n-1)*(x^m-1)=x^(n+m)-x^n-x^m+1

The left and right side represent two ways to arrive at the same result, and so an arithmetic module actually doing the calculation does the calculation in two different ways. The results should be exactly equal.

`RandVerifyArithmetic(n)` calls `VerifyArithmetic()` with random values, `n` times.

`VerifyDiv(u,v)` checks that

u=v*Div(u,v)+Mod(u,v)

##### Examples:

    In> VerifyArithmetic(100,50,60)
    Out> True;
    In> RandVerifyArithmetic(4)
    Out> True;
    In> VerifyDiv(x^2+2*x+3,x+1)
    Out> True;
    In> VerifyDiv(3,2)
    Out> True;

##### See also:

Verify .