Programming in GP: other specific functions

Strprintf(fmt,{x}*)

Returns a string built from the remaining arguments according to the format fmt. The format consists of ordinary characters (not %), printed unchanged, and conversions specifications. See printf.


addhelp(sym,str)

Changes the help message for the symbol sym. The string str is expanded on the spot and stored as the online help for sym. It is recommended to document global variables and user functions in this way, although gp will not protest if you don't.

You can attach a help text to an alias, but it will never be shown: aliases are expanded by the ? help operator and we get the help of the symbol the alias points to. Nothing prevents you from modifying the help of built-in PARI functions. But if you do, we would like to hear why you needed it!

Without addhelp, the standard help for user functions consists of its name and definition.

  gp> f(x) = x^2;
  gp> ?f
  f =
    (x)->x^2
  
Once addhelp is applied to f, the function code is no longer included. It can still be consulted by typing the function name:

  gp> addhelp(f, "Square")
  gp> ?f
  Square
  
  gp> f
  %2 = (x)->x^2

The library syntax is void addhelp(const char *sym, const char *str).


alarm({s = 0},{code})

If code is omitted, trigger an e_ALARM exception after s seconds, cancelling any previously set alarm; stop a pending alarm if s = 0 or is omitted.

Otherwise, if s is positive, the function evaluates code, aborting after s seconds. The return value is the value of code if it ran to completion before the alarm timeout, and a t_ERROR object otherwise.

    ? p = nextprime(10^25); q = nextprime(10^26); N = p*q;
    ? E = alarm(1, factor(N));
    ? type(E)
    %3 = "t_ERROR"
    ? print(E)
    %4 = error("alarm interrupt after 964 ms.")
    ? alarm(10, factor(N));   \\ enough time
    %5 =
    [ 10000000000000000000000013 1]
  
    [100000000000000000000000067 1]
Here is a more involved example: the function timefact(N,sec) below tries to factor N and gives up after sec seconds, returning a partial factorisation.

  \\ Time-bounded partial factorization
  default(factor_add_primes,1);
  timefact(N,sec)=
  {
    F = alarm(sec, factor(N));
    if (type(F) == "t_ERROR", factor(N, 2^24), F);
  }
We either return the factorization directly, or replace the t_ERROR result by a simple bounded factorization factor(N, 2^24). Note the factor_add_primes trick: any prime larger than 2^{24} discovered while attempting the initial factorization is stored and remembered. When the alarm rings, the subsequent bounded factorization finds it right away.

Caveat. It is not possible to set a new alarm within another alarm code: the new timer erases the parent one.


alias(newsym,sym)

Defines the symbol newsym as an alias for the the symbol sym:

  ? alias("det", "matdet");
  ? det([1,2;3,4])
  %1 = -2

You are not restricted to ordinary functions, as in the above example: to alias (from/to) member functions, prefix them with `_.'; to alias operators, use their internal name, obtained by writing _ in lieu of the operators argument: for instance, _! and !_ are the internal names of the factorial and the logical negation, respectively.

  ? alias("mod", "_.mod");
  ? alias("add", "_+_");
  ? alias("_.sin", "sin");
  ? mod(Mod(x,x^4+1))
  %2 = x^4 + 1
  ? add(4,6)
  %3 = 10
  ? Pi.sin
  %4 = 0.E-37

Alias expansion is performed directly by the internal GP compiler. Note that since alias is performed at compilation-time, it does not require any run-time processing, however it only affects GP code compiled after the alias command is evaluated. A slower but more flexible alternative is to use variables. Compare

  ? fun = sin;
  ? g(a,b) = intnum(t=a,b,fun(t));
  ? g(0, Pi)
  %3 = 2.0000000000000000000000000000000000000
  ? fun = cos;
  ? g(0, Pi)
  %5 = 1.8830410776607851098 E-39

with

  ? alias(fun, sin);
  ? g(a,b) = intnum(t=a,b,fun(t));
  ? g(0,Pi)
  %2 = 2.0000000000000000000000000000000000000
  ? alias(fun, cos);  \\ Oops. Does not affect *previous* definition!
  ? g(0,Pi)
  %3 = 2.0000000000000000000000000000000000000
  ? g(a,b) = intnum(t=a,b,fun(t)); \\ Redefine, taking new alias into account
  ? g(0,Pi)
  %5 = 1.8830410776607851098 E-39

A sample alias file misc/gpalias is provided with the standard distribution.

The library syntax is void alias0(const char *newsym, const char *sym).


allocatemem({s = 0})

This special operation changes the stack size after initialization. x must be a non-negative integer. If x > 0, a new stack of at least x bytes is allocated. We may allocate more than x bytes if x is way too small, or for alignment reasons: the current formula is \max(16*ceil{x/16}, 500032) bytes.

If x = 0, the size of the new stack is twice the size of the old one. The old stack is discarded.

Warning. This function should be typed at the gp prompt in interactive usage, or left by itself at the start of batch files. It cannot be used meaningfully in loop-like constructs, or as part of a larger expression sequence, e.g

     allocatemem(); x = 1;   \\  This will not set x!

In fact, all loops are immediately exited, user functions terminated, and the rest of the sequence following allocatemem() is silently discarded, as well as all pending sequences of instructions. We just go on reading the next instruction sequence from the file we're in (or from the user). In particular, we have the following possibly unexpected behavior: in

     read("file.gp"); x = 1
were file.gp contains an allocatemem statement, the x = 1 is never executed, since all pending instructions in the current sequence are discarded.

The technical reason is that this routine moves the stack, so temporary objects created during the current expression evaluation are not correct anymore. (In particular byte-compiled expressions, which are allocated on the stack.) To avoid accessing obsolete pointers to the old stack, this routine ends by a longjmp.

Remark. If the operating system cannot allocate the desired x bytes, a loop halves the allocation size until it succeeds:

  ? allocatemem(5*10^10)
   ***   Warning: not enough memory, new stack 50000000000.
   ***   Warning: not enough memory, new stack 25000000000.
   ***   Warning: not enough memory, new stack 12500000000.
   ***   Warning: new stack size = 6250000000 (5960.464 Mbytes).


apply(f, A)

Apply the t_CLOSURE f to the entries of A. If A is a scalar, return f(A). If A is a polynomial or power series, apply f on all coefficients. If A is a vector or list, return the elements f(x) where x runs through A. If A is a matrix, return the matrix whose entries are the f(A[i,j]).

  ? apply(x->x^2, [1,2,3,4])
  %1 = [1, 4, 9, 16]
  ? apply(x->x^2, [1,2;3,4])
  %2 =
  [1 4]
  
  [9 16]
  ? apply(x->x^2, 4*x^2 + 3*x+ 2)
  %3 = 16*x^2 + 9*x + 4
Note that many functions already act componentwise on vectors or matrices, but they almost never act on lists; in this case, apply is a good solution:

  ? L = List([Mod(1,3), Mod(2,4)]);
  ? lift(L)
    ***   at top-level: lift(L)
    ***                 ^-------
    *** lift: incorrect type in lift.
  ? apply(lift, L);
  %2 = List([1, 2])

Remark. For v a t_VEC, t_COL, t_LIST or t_MAT, the alternative set-notations

  [g(x) | x <- v, f(x)]
  [x | x <- v, f(x)]
  [g(x) | x <- v]

are available as shortcuts for

  apply(g, select(f, Vec(v)))
  select(f, Vec(v))
  apply(g, Vec(v))
respectively:

  ? L = List([Mod(1,3), Mod(2,4)]);
  ? [ lift(x) | x<-L ]
  %2 = [1, 2]

The library syntax is genapply(void *E, GEN (*fun)(void*,GEN), GEN a).


default({key},{val})

Returns the default corresponding to keyword key. If val is present, sets the default to val first (which is subject to string expansion first). Typing default() (or \d) yields the complete default list as well as their current values. See Section [Label: se:defaults] for an introduction to GP defaults, Section [Label: se:gp_defaults] for a list of available defaults, and Section [Label: se:meta] for some shortcut alternatives. Note that the shortcuts are meant for interactive use and usually display more information than default.

The library syntax is GEN default0(const char *key = NULL, const char *val = NULL).


errname(E)

Returns the type of the error message E as a string.

The library syntax is GEN errname(GEN E).


error({str}*)

Outputs its argument list (each of them interpreted as a string), then interrupts the running gp program, returning to the input prompt. For instance

  error("n = ", n, " is not squarefree!")


extern(str)

The string str is the name of an external command (i.e. one you would type from your UNIX shell prompt). This command is immediately run and its output fed into gp, just as if read from a file.


externstr(str)

The string str is the name of an external command (i.e. one you would type from your UNIX shell prompt). This command is immediately run and its output is returned as a vector of GP strings, one component per output line.


getabstime()

Returns the time (in milliseconds) elapsed since gp startup. This provides a reentrant version of gettime:

  my (t = getabstime());
  ...
  print("Time: ", getabstime() - t);

The library syntax is long getabstime().


getenv(s)

Return the value of the environment variable s if it is defined, otherwise return 0.

The library syntax is GEN gp_getenv(const char *s).


getheap()

Returns a two-component row vector giving the number of objects on the heap and the amount of memory they occupy in long words. Useful mainly for debugging purposes.

The library syntax is GEN getheap().


getrand()

Returns the current value of the seed used by the pseudo-random number generator random. Useful mainly for debugging purposes, to reproduce a specific chain of computations. The returned value is technical (reproduces an internal state array), and can only be used as an argument to setrand.

The library syntax is GEN getrand().


getstack()

Returns the current value of top-avma, i.e. the number of bytes used up to now on the stack. Useful mainly for debugging purposes.

The library syntax is long getstack().


gettime()

Returns the time (in milliseconds) elapsed since either the last call to gettime, or to the beginning of the containing GP instruction (if inside gp), whichever came last.

For a reentrant version, see getabstime.

The library syntax is long gettime().


global(list of variables)

Obsolete. Scheduled for deletion.


inline(x,...,z)

(Experimental) declare x,..., z as inline variables. Such variables behave like lexically scoped variable (see my()) but with unlimited scope. It is however possible to exit the scope by using uninline(). When used in a GP script, it is recommended to call uninline() before the script's end to avoid inline variables leaking outside the script.


input()

Reads a string, interpreted as a GP expression, from the input file, usually standard input (i.e. the keyboard). If a sequence of expressions is given, the result is the result of the last expression of the sequence. When using this instruction, it is useful to prompt for the string by using the print1 function. Note that in the present version 2.19 of pari.el, when using gp under GNU Emacs (see Section [Label: se:emacs]) one must prompt for the string, with a string which ends with the same prompt as any of the previous ones (a "? " will do for instance).


install(name,code,{gpname},{lib})

Loads from dynamic library lib the function name. Assigns to it the name gpname in this gp session, with prototype code (see below). If gpname is omitted, uses name. If lib is omitted, all symbols known to gp are available: this includes the whole of libpari.so and possibly others (such as libc.so).

Most importantly, install gives you access to all non-static functions defined in the PARI library. For instance, the function \kbd{GEN addii(GEN x, GEN y)} adds two PARI integers, and is not directly accessible under gp (it is eventually called by the + operator of course):

  ? install("addii", "GG")
  ? addii(1, 2)
  %1 = 3

It also allows to add external functions to the gp interpreter. For instance, it makes the function system obsolete:

  ? install(system, vs, sys,/*omitted*/)
  ? sys("ls gp*")
  gp.c            gp.h            gp_rl.c
This works because system is part of libc.so, which is linked to gp. It is also possible to compile a shared library yourself and provide it to gp in this way: use gp2c, or do it manually (see the modules_build variable in pari.cfg for hints).

Re-installing a function will print a warning and update the prototype code if needed. However, it will not reload a symbol from the library, even if the latter has been recompiled.

Prototype. We only give a simplified description here, covering most functions, but there are many more possibilities. The full documentation is available in libpari.dvi, see

    ??prototype

* First character i, l, v : return type int / long / void. (Default: GEN)

* One letter for each mandatory argument, in the same order as they appear in the argument list: G (GEN), & (GEN*), L (long), s (char *), n (variable).

* p to supply realprecision (usually long prec in the argument list), P to supply seriesprecision (usually \kbd{long precdl}).

We also have special constructs for optional arguments and default values:

* DG (optional GEN, NULL if omitted),

* D& (optional GEN*, NULL if omitted),

* Dn (optional variable, -1 if omitted),

For instance the prototype corresponding to

    long issquareall(GEN x, GEN *n = NULL)
is lGD&.

Caution. This function may not work on all systems, especially when gp has been compiled statically. In that case, the first use of an installed function will provoke a Segmentation Fault (this should never happen with a dynamically linked executable). If you intend to use this function, please check first on some harmless example such as the one above that it works properly on your machine.

The library syntax is void gpinstall(const char *name, const char *code, const char *gpname, const char *lib).


kill(sym)

Restores the symbol sym to its "undefined" status, and deletes any help messages associated to sym using addhelp. Variable names remain known to the interpreter and keep their former priority: you cannot make a variable "less important" by killing it!

  ? z = y = 1; y
  %1 = 1
  ? kill(y)
  ? y            \\ restored to ``undefined'' status
  %2 = y
  ? variable()
  %3 = [x, y, z] \\ but the variable name y is still known, with y > z !

For the same reason, killing a user function (which is an ordinary variable holding a t_CLOSURE) does not remove its name from the list of variable names.

If the symbol is associated to a variable --- user functions being an important special case ---, one may use the quote operator a = 'a to reset variables to their starting values. However, this will not delete a help message associated to a, and is also slightly slower than kill(a).

  ? x = 1; addhelp(x, "foo"); x
  %1 = 1
  ? x = 'x; x   \\ same as 'kill', except we don't delete help.
  %2 = x
  ? ?x
  foo

On the other hand, kill is the only way to remove aliases and installed functions.

  ? alias(fun, sin);
  ? kill(fun);
  
  ? install(addii, GG);
  ? kill(addii);

The library syntax is void kill0(const char *sym).


print({str}*)

Outputs its (string) arguments in raw format, ending with a newline.


print1({str}*)

Outputs its (string) arguments in raw format, without ending with a newline. Note that you can still embed newlines within your strings, using the \n notation !


printf(fmt,{x}*)

This function is based on the C library command of the same name. It prints its arguments according to the format fmt, which specifies how subsequent arguments are converted for output. The format is a character string composed of zero or more directives:

* ordinary characters (not %), printed unchanged,

* conversions specifications (% followed by some characters) which fetch one argument from the list and prints it according to the specification.

More precisely, a conversion specification consists in a %, one or more optional flags (among #, 0, -, +, ` '), an optional decimal digit string specifying a minimal field width, an optional precision in the form of a period (`.') followed by a decimal digit string, and the conversion specifier (among d,i, o, u, x,X, p, e,E, f, g,G, s).

The flag characters. The character % is followed by zero or more of the following flags:

* #: The value is converted to an "alternate form". For o conversion (octal), a 0 is prefixed to the string. For x and X conversions (hexa), respectively 0x and 0X are prepended. For other conversions, the flag is ignored.

* 0: The value should be zero padded. For d, i, o, u, x, X e, E, f, F, g, and G conversions, the value is padded on the left with zeros rather than blanks. (If the 0 and - flags both appear, the 0 flag is ignored.)

* -: The value is left adjusted on the field boundary. (The default is right justification.) The value is padded on the right with blanks, rather than on the left with blanks or zeros. A - overrides a 0 if both are given.

* ` ' (a space): A blank is left before a positive number produced by a signed conversion.

* +: A sign (+ or -) is placed before a number produced by a signed conversion. A + overrides a space if both are used.

The field width. An optional decimal digit string (whose first digit is non-zero) specifying a minimum field width. If the value has fewer characters than the field width, it is padded with spaces on the left (or right, if the left-adjustment flag has been given). In no case does a small field width cause truncation of a field; if the value is wider than the field width, the field is expanded to contain the conversion result. Instead of a decimal digit string, one may write * to specify that the field width is given in the next argument.

The precision. An optional precision in the form of a period (`.') followed by a decimal digit string. This gives the number of digits to appear after the radix character for e, E, f, and F conversions, the maximum number of significant digits for g and G conversions, and the maximum number of characters to be printed from an s conversion. Instead of a decimal digit string, one may write * to specify that the field width is given in the next argument.

The length modifier. This is ignored under gp, but necessary for libpari programming. Description given here for completeness:

* l: argument is a long integer.

* P: argument is a GEN.

The conversion specifier. A character that specifies the type of conversion to be applied.

* d, i: A signed integer.

* o, u, x, X: An unsigned integer, converted to unsigned octal (o), decimal (u) or hexadecimal (x or X) notation. The letters abcdef are used for x conversions; the letters ABCDEF are used for X conversions.

* e, E: The (real) argument is converted in the style [ -]d.ddd e[ -]dd, where there is one digit before the decimal point, and the number of digits after it is equal to the precision; if the precision is missing, use the current realprecision for the total number of printed digits. If the precision is explicitly 0, no decimal-point character appears. An E conversion uses the letter E rather than e to introduce the exponent.

* f, F: The (real) argument is converted in the style [ -]ddd.ddd, where the number of digits after the decimal point is equal to the precision; if the precision is missing, use the current realprecision for the total number of printed digits. If the precision is explicitly 0, no decimal-point character appears. If a decimal point appears, at least one digit appears before it.

* g, G: The (real) argument is converted in style e or f (or E or F for G conversions) [ -]ddd.ddd, where the total number of digits printed is equal to the precision; if the precision is missing, use the current realprecision. If the precision is explicitly 0, it is treated as 1. Style e is used when the decimal exponent is < -4, to print 0., or when the integer part cannot be decided given the known significant digits, and the f format otherwise.

* c: The integer argument is converted to an unsigned char, and the resulting character is written.

* s: Convert to a character string. If a precision is given, no more than the specified number of characters are written.

* p: Print the address of the argument in hexadecimal (as if by %#x).

* %: A % is written. No argument is converted. The complete conversion specification is %%.

Examples:

  ? printf("floor: %d, field width 3: %3d, with sign: %+3d\n", Pi, 1, 2);
  floor: 3, field width 3:   1, with sign:  +2
  
  ? printf("%.5g %.5g %.5g\n",123,123/456,123456789);
  123.00 0.26974 1.2346 e8
  
  ? printf("%-2.5s:%2.5s:%2.5s\n", "P", "PARI", "PARIGP");
  P :PARI:PARIG
  
  \\ min field width and precision given by arguments
  ? x = 23; y=-1/x; printf("x=%+06.2f y=%+0*.*f\n", x, 6, 2, y);
  x=+23.00 y=-00.04
  
  \\ minimum fields width 5, pad left with zeroes
  ? for (i = 2, 5, printf("%05d\n", 10^i))
  00100
  01000
  10000
  100000  \\  don't truncate fields whose length is larger than the minimum width
  ? printf("%.2f  |%06.2f|", Pi,Pi)
  3.14  |  3.14|
All numerical conversions apply recursively to the entries of vectors and matrices:

  ? printf("%4d", [1,2,3]);
  [   1,   2,   3]
  ? printf("%5.2f", mathilbert(3));
  [ 1.00  0.50  0.33]
  
  [ 0.50  0.33  0.25]
  
  [ 0.33  0.25  0.20]

Technical note. Our implementation of printf deviates from the C89 and C99 standards in a few places:

* whenever a precision is missing, the current realprecision is used to determine the number of printed digits (C89: use 6 decimals after the radix character).

* in conversion style e, we do not impose that the exponent has at least two digits; we never write a + sign in the exponent; 0 is printed in a special way, always as 0.Eexp.

* in conversion style f, we switch to style e if the exponent is greater or equal to the precision.

* in conversion g and G, we do not remove trailing zeros from the fractional part of the result; nor a trailing decimal point; 0 is printed in a special way, always as 0.Eexp.


printsep(sep,{str}*)

Outputs its (string) arguments in raw format, ending with a newline. Successive entries are separated by sep:

  ? printsep(":", 1,2,3,4)
  1:2:3:4


printsep1(sep,{str}*)

Outputs its (string) arguments in raw format, without ending with a newline. Successive entries are separated by sep:

  ? printsep1(":", 1,2,3,4);print("|")
  1:2:3:4


printtex({str}*)

Outputs its (string) arguments in TeX format. This output can then be used in a TeX manuscript. The printing is done on the standard output. If you want to print it to a file you should use writetex (see there).

Another possibility is to enable the log default (see Section [Label: se:defaults]). You could for instance do:

  default(logfile, "new.tex");
  default(log, 1);
  printtex(result);


quit({status = 0})

Exits gp and return to the system with exit status status, a small integer. A non-zero exit status normally indicates abnormal termination. (Note: the system actually sees only status mod 256, see your man pages for exit(3) or wait(2)).


read({filename})

Reads in the file filename (subject to string expansion). If filename is omitted, re-reads the last file that was fed into gp. The return value is the result of the last expression evaluated.

If a GP binary file is read using this command (see Section [Label: se:writebin]), the file is loaded and the last object in the file is returned.

In case the file you read in contains an allocatemem statement (to be generally avoided), you should leave read instructions by themselves, and not part of larger instruction sequences.


readstr({filename})

Reads in the file filename and return a vector of GP strings, each component containing one line from the file. If filename is omitted, re-reads the last file that was fed into gp.


readvec({filename})

Reads in the file filename (subject to string expansion). If filename is omitted, re-reads the last file that was fed into gp. The return value is a vector whose components are the evaluation of all sequences of instructions contained in the file. For instance, if file contains

  1
  2
  3

then we will get:

  ? \r a
  %1 = 1
  %2 = 2
  %3 = 3
  ? read(a)
  %4 = 3
  ? readvec(a)
  %5 = [1, 2, 3]

In general a sequence is just a single line, but as usual braces and \ may be used to enter multiline sequences.

The library syntax is GEN gp_readvec_file(const char *filename). The underlying library function GEN gp_readvec_stream(FILE *f) is usually more flexible.


select(f, A, {flag = 0})

We first describe the default behaviour, when flag is 0 or omitted. Given a vector or list A and a t_CLOSURE f, select returns the elements x of A such that f(x) is non-zero. In other words, f is seen as a selection function returning a boolean value.

  ? select(x->isprime(x), vector(50,i,i^2+1))
  %1 = [2, 5, 17, 37, 101, 197, 257, 401, 577, 677, 1297, 1601]
  ? select(x->(x<100), %)
  %2 = [2, 5, 17, 37]
returns the primes of the form i^2+1 for some i <= 50, then the elements less than 100 in the preceding result. The select function also applies to a matrix A, seen as a vector of columns, i.e. it selects columns instead of entries, and returns the matrix whose columns are the selected ones.

Remark. For v a t_VEC, t_COL, t_LIST or t_MAT, the alternative set-notations

  [g(x) | x <- v, f(x)]
  [x | x <- v, f(x)]
  [g(x) | x <- v]

are available as shortcuts for

  apply(g, select(f, Vec(v)))
  select(f, Vec(v))
  apply(g, Vec(v))
respectively:

  ? [ x | x <- vector(50,i,i^2+1), isprime(x) ]
  %1 = [2, 5, 17, 37, 101, 197, 257, 401, 577, 677, 1297, 1601]

If flag = 1, this function returns instead the indices of the selected elements, and not the elements themselves (indirect selection):

  ? V = vector(50,i,i^2+1);
  ? select(x->isprime(x), V, 1)
  %2 = Vecsmall([1, 2, 4, 6, 10, 14, 16, 20, 24, 26, 36, 40])
  ? vecextract(V, %)
  %3 = [2, 5, 17, 37, 101, 197, 257, 401, 577, 677, 1297, 1601]

The following function lists the elements in (Z/NZ)^*:

  ? invertibles(N) = select(x->gcd(x,N) == 1, [1..N])

Finally

  ? select(x->x, M)
selects the non-0 entries in M. If the latter is a t_MAT, we extract the matrix of non-0 columns. Note that removing entries instead of selecting them just involves replacing the selection function f with its negation:

  ? select(x->!isprime(x), vector(50,i,i^2+1))

The library syntax is genselect(void *E, long (*fun)(void*,GEN), GEN a). Also available is GEN genindexselect(void *E, long (*fun)(void*, GEN), GEN a), corresponding to flag = 1.


setrand(n)

Reseeds the random number generator using the seed n. No value is returned. The seed is either a technical array output by getrand, or a small positive integer, used to generate deterministically a suitable state array. For instance, running a randomized computation starting by setrand(1) twice will generate the exact same output.

The library syntax is void setrand(GEN n).


system(str)

str is a string representing a system command. This command is executed, its output written to the standard output (this won't get into your logfile), and control returns to the PARI system. This simply calls the C system command.


trap({e}, {rec}, seq)

THIS FUNCTION IS OBSOLETE: use iferr, which has a nicer and much more powerful interface. For compatibility's sake we now describe the obsolete function trap.

This function tries to evaluate seq, trapping runtime error e, that is effectively preventing it from aborting computations in the usual way; the recovery sequence rec is executed if the error occurs and the evaluation of rec becomes the result of the command. If e is omitted, all exceptions are trapped. See Section [Label: se:errorrec] for an introduction to error recovery under gp.

  ? \\  trap division by 0
  ? inv(x) = trap (e_INV, INFINITY, 1/x)
  ? inv(2)
  %1 = 1/2
  ? inv(0)
  %2 = INFINITY

Note that seq is effectively evaluated up to the point that produced the error, and the recovery sequence is evaluated starting from that same context, it does not "undo" whatever happened in the other branch (restore the evaluation context):

  ? x = 1; trap (, /* recover: */ x, /* try: */ x = 0; 1/x)
  %1 = 0

Note. The interface is currently not adequate for trapping individual exceptions. In the current version 2.7.0, the following keywords are recognized, but the name list will be expanded and changed in the future (all library mode errors can be trapped: it's a matter of defining the keywords to gp):

e_ALARM: alarm time-out

e_ARCH: not available on this architecture or operating system

e_STACK: the PARI stack overflows

e_INV: impossible inverse

e_IMPL: not yet implemented

e_OVERFLOW: all forms of arithmetic overflow, including length or exponent overflow (when a larger value is supplied than the implementation can handle).

e_SYNTAX: syntax error

e_MISC: miscellaneous error

e_TYPE: wrong type

e_USER: user error (from the error function)

The library syntax is GEN trap0(const char *e = NULL, GEN rec = NULL, GEN seq = NULL).


type(x)

This is useful only under gp. Returns the internal type name of the PARI object x as a string. Check out existing type names with the metacommand \t. For example type(1) will return "t_INT".

The library syntax is GEN type0(GEN x). The macro typ is usually simpler to use since it returns a long that can easily be matched with the symbols t_*. The name type was avoided since it is a reserved identifier for some compilers.


uninline()

(Experimental) Exit the scope of all current inline variables.


version()

Returns the current version number as a t_VEC with three integer components (major version number, minor version number and patchlevel); if your sources were obtained through our version control system, this will be followed by further more precise arguments, including e.g. a git commit hash.

This function is present in all versions of PARI following releases 2.3.4 (stable) and 2.4.3 (testing).

Unless you are working with multiple development versions, you probably only care about the 3 first numeric components. In any case, the lex function offers a clever way to check against a particular version number, since it will compare each successive vector entry, numerically or as strings, and will not mind if the vectors it compares have different lengths:

     if (lex(version(), [2,3,5]) >= 0,
       \\ code to be executed if we are running 2.3.5 or more recent.
     ,
       \\ compatibility code
     );
On a number of different machines, version() could return either of

   %1 = [2, 3, 4]    \\ released version, stable branch
   %1 = [2, 4, 3]    \\ released version, testing branch
   %1 = [2, 6, 1, 15174, ""505ab9b"] \\ development

In particular, if you are only working with released versions, the first line of the gp introductory message can be emulated by

     [M,m,p] = version();
     printf("GP/PARI CALCULATOR Version %s.%s.%s", M,m,p);
If you are working with many development versions of PARI/GP, the 4th and/or 5th components can be profitably included in the name of your logfiles, for instance.

Technical note. For development versions obtained via git, the 4th and 5th components are liable to change eventually, but we document their current meaning for completeness. The 4th component counts the number of reachable commits in the branch (analogous to svn's revision number), and the 5th is the git commit hash. In particular, lex comparison still orders correctly development versions with respect to each others or to released versions (provided we stay within a given branch, e.g. master)!

The library syntax is GEN pari_version().


warning({str}*)

Outputs the message "user warning" and the argument list (each of them interpreted as a string). If colors are enabled, this warning will be in a different color, making it easy to distinguish.

  warning(n, " is very large, this might take a while.")


whatnow(key)

If keyword key is the name of a function that was present in GP version 1.39.15 or lower, outputs the new function name and syntax, if it changed at all (387 out of 560 did).


write(filename,{str}*)

Writes (appends) to filename the remaining arguments, and appends a newline (same output as print).


write1(filename,{str}*)

Writes (appends) to filename the remaining arguments without a trailing newline (same output as print1).


writebin(filename,{x})

Writes (appends) to filename the object x in binary format. This format is not human readable, but contains the exact internal structure of x, and is much faster to save/load than a string expression, as would be produced by write. The binary file format includes a magic number, so that such a file can be recognized and correctly input by the regular read or \r function. If saved objects refer to (polynomial) variables that are not defined in the new session, they will be displayed in a funny way (see Section [Label: se:kill]). Installed functions and history objects can not be saved via this function.

If x is omitted, saves all user variables from the session, together with their names. Reading such a "named object" back in a gp session will set the corresponding user variable to the saved value. E.g after

  x = 1; writebin("log")

reading log into a clean session will set x to 1. The relative variables priorities (see Section [Label: se:priority]) of new variables set in this way remain the same (preset variables retain their former priority, but are set to the new value). In particular, reading such a session log into a clean session will restore all variables exactly as they were in the original one.

Just as a regular input file, a binary file can be compressed using gzip, provided the file name has the standard .gz extension.

In the present implementation, the binary files are architecture dependent and compatibility with future versions of gp is not guaranteed. Hence binary files should not be used for long term storage (also, they are larger and harder to compress than text files).

The library syntax is void gpwritebin(const char *filename, GEN x = NULL).


writetex(filename,{str}*)

As write, in TeX format.