Testing latest pari + WASM + node.js... and it works?! Wow.
License: GPL3
ubuntu2004
% Copyright (c) 2000 The PARI Group1%2% This file is part of the PARI/GP documentation3%4% Permission is granted to copy, distribute and/or modify this document5% under the terms of the GNU General Public License6\chapter{The gp Calculator}78\section{Introduction}910Originally, \tet{gp} was designed as a debugging device for the PARI system11library. Over the years, it has become a powerful user-friendly stand-alone12calculator. The mathematical functions available in PARI and \kbd{gp} are13described in the next chapter. In the present one, we describe the specific14use of the \kbd{gp} programmable calculator.1516\emacs If you have GNU Emacs and use the PariEmacs package, you can work in a17special Emacs shell, described in \secref{se:emacs}. Specific features of18this Emacs shell are indicated by an EMACS sign in the left margin.1920We briefly mention at this point GNU21TeXmacs (\url{http://www.texmacs.org/}), a free wysiwyg editing22platform that allows to embed an entire gp session in a document, and23provides a nice alternative to PariEmacs.2425\subsec{Startup}2627To start the calculator, the general command line syntax is:2829\kbd{gp [-D \var{key}=\var{val}] [\var{files}]}3031\noindent32where items within brackets are optional. The [\var{files}] argument is a33list of files written in the GP scripting language, which will be loaded on34startup. There can be any number of arguments of the form35\kbd{-D \var{key}=\var{val}}, setting some internal parameters of \kbd{gp},36or \var{defaults}: each sets the default \var{key} to the value \var{val}. See37\secref{se:defaults} below for a list and explanation of all defaults. These38defaults can be changed by adding parameters to the input line as above, or39interactively during a \kbd{gp} session, or in a preferences file also known40as \tet{gprc}.4142If a \idx{preferences file} (to be discussed in \secref{se:gprc}) is43found, \kbd{gp} then reads it and executes the commands it contains. This44provides an easy way to customize \kbd{gp}. The \var{files} argument is45processed right after the \kbd{gprc}.4647A copyright banner then appears which includes the version number, and a lot48of useful technical information. After the copyright, the computer writes the49top-level help information, some initial defaults, and then waits after50printing its prompt, which is '\kbd{?~}' by default . Whether extended51on-line help and line editing are available or not is indicated in this52\kbd{gp} banner, between the version number and the copyright message.53Consider investigating the matter with the person who installed \kbd{gp} if54they are not. Do this as well if there is no mention of the GMP kernel.5556\subsec{Getting help}5758To get help, type a \kbd{?} and hit return. A menu appears, describing the59main categories of available functions and how to get more detailed60help. If you now type \kbd{?$n$} with $n = 1, 2, \dots$, you get the list of61commands corresponding to category $n$ and simultaneously to Section $3.n$ of62this manual. If you type \kbd{?}\var{functionname} where \var{functionname}63is the name of a PARI function, you will get a short explanation of this64function.6566If extended help (see \secref{se:exthelp}) is available on your system,67you can double or triple the \kbd{?} sign to get much more: respectively the68complete description of the function (e.g.~\kbd{??sqrt}), or a list of69\kbd{gp} functions relevant to your query (e.g.~ \kbd{???"elliptic curve"}70or \kbd{???"quadratic field"}).7172If \kbd{gp} was properly installed (see Appendix~A), a line editor is73available to correct the command line, get automatic completions, and so on.74See \secref{se:readline} or \kbd{??readline} for a short summary of the line75editor's commands.7677If you type \kbd{?\bs} you will get a short description of the metacommands78(keyboard shortcuts).7980Finally, typing \kbd{?.} will return the list of available (pre-defined)81member functions. These are functions attached to specific kind of objects,82used to retrieve easily some information from complicated structures (you can83define your own but they won't be shown here). We will soon describe these84commands in more detail.8586More generally, commands starting with the symbols \b\ or \kbd{?}, are not87computing commands, but are metacommands which allow you to exchange88information with \kbd{gp}. The available metacommands can be divided into89default setting commands (explained below) and simple commands (or keyboard90shortcuts, to be dealt with in \secref{se:meta}).9192\subsec{Input}9394Just type in an instruction, e.g. \kbd{1 + 1}, or \kbd{Pi}. No action is95undertaken until you hit the \kbd{<Return>} key. Then computation starts, and96a result is eventually printed. To suppress printing of the result, end the97expression with a \kbd{;} sign. Note that many systems use \kbd{;} to98indicate end of input. Not so in \kbd{gp}: a final semicolon means the99result should not be printed. (Which is certainly useful if it occupies100several screens.)101102\subsec{Interrupt, Quit}103104Typing \kbd{quit} at the prompt ends the session and exits \kbd{gp}. At any105point you can type \kbd{Ctrl-C} (that is press simultaneously the106\kbd{Control} and \kbd{C} keys): the current computation is interrupted and107control given back to you at the \kbd{gp} prompt, together with a message108like109\bprog110*** at top-level: gcd(a,b)111*** ^--------112*** gcd: user interrupt after 236 ms.113@eprog\noindent114telling you how much time elapsed since the last command was typed in and115in which GP function the computation was aborted. It does not mean that that116much time was spent in the function, only that the evaluator was busy117processing that specific function when you stopped it.118119\section{The general gp input line}120121The \kbd{gp} calculator uses a purely interpreted language GP. The structure122of this language is reminiscent of LISP with a functional notation,123\kbd{f(x,y)} rather than \kbd{(f x y)}: all programming constructs,124such as \kbd{if}, \kbd{while,} etc\dots are functions\footnote{*}{Not exactly,125since not all their arguments need be evaluated. For instance it would be126stupid to evaluate both branches of an \kbd{if} statement: since only one127will apply, only this one is evaluated.}, and the main loop does not really128execute, but rather evaluates (sequences of) expressions. Of course, it is by129no means a true LISP, and has been strongly influenced by C and Perl since130then.131132\subsec{Introduction} User interaction with a \kbd{gp} session proceeds as133follows. First, one types a sequence of characters at the \kbd{gp} prompt;134see \secref{se:readline} for a description of the line editor. When you hit135the \kbd{<Return>} key, \kbd{gp} gets your input, evaluates it, then prints136the result and assigns it to an ``history'' array.137138More precisely, the input is case-sensitive and, outside of character139strings, blanks are completely ignored. Inputs are either metacommands or140sequences of expressions. Metacommands are shortcuts designed to alter gp's141internal state, such as the working precision or general verbosity level; we142shall describe them in \secref{se:meta}, and ignore them for the time being.143144The evaluation of a sequence of instructions proceeds in two phases: your145input is first digested (byte-compiled) to a bytecode suitable for fast146evaluation, in particular loop bodies are compiled only once but a priori147evaluated many times; then the bytecode is evaluated.148149An \idx{expression}\sidx{expression sequence} is formed by combining150constants, variables, operator symbols, functions and control statements.151It is evaluated using the conventions about operator priorities and left to152right associativity. An expression always has a value, which can be any PARI153object:154\bprog155? 1 + 1156%1 = 2 \\@com an ordinary integer157? x158%2 = x \\@com a polynomial of degree 1 in the unknown \kbd{x}159? print("Hello")160Hello \\@com \kbd{void} return value, 'Hello' printed as side effect161? f(x) = x^2162%4 = (x)->x^2 \\@com a user function163@eprog164\noindent In the third example, \kbd{Hello} is printed as a side effect, but165is not the return value. The \kbd{print} command is a \emph{procedure},166which conceptually returns nothing. But in fact procedures return a special167\kbd{void} object, meant to be ignored (but which evaluates168to $0$ in a numeric context, and stored as $0$ in the history or results).169The final example assigns to the variable \kbd{f} the function $x\mapsto170x^2$, the alternative form \kbd{f = x->x\pow2} achieving the same effect; the171return value of a function definition is, unsurprisingly, a function object172(of type \typ{CLOSURE}).173174Several expressions are combined on a single line by separating them with175semicolons ('\kbd{;}'). Such an expression sequence will be called a176\var{seq}. A \var{seq} also has a value, which is the value of the last177expression in the sequence. Under \kbd{gp}, the value of the \var{seq}, and178only this last value, becomes an history entry. The values of the other179expressions in the \var{seq} are discarded after the execution of the180\var{seq} is complete, except of course if they were assigned into variables.181In addition, the value of the \var{seq} is printed if the line does not end182with a semicolon \kbd{;}.183184\subsec{The gp history of results}185186This is not to be confused with the history of your \emph{commands},187maintained by \kbd{readline}. The \kbd{gp} history contains the \emph{results}188they produced, in sequence.189190The successive elements of the history array are called \kbd{\%1}, \kbd{\%2},191\dots As a shortcut, the latest computed expression can also be192called \kbd{\%}, the previous one \kbd{\%`},193the one before that \kbd{\%``} and so on.194195When you suppress the printing of the result with a semicolon, it is still196stored in the history, but its history number will not appear either. It is a197better idea to assign it to a variable for later use than to mentally198recompute what its number is. Of course, on the next line, you may just use199\kbd{\%}.200201The time used to compute that history entry is also stored as part of the entry202and can be recovered using the \kbd{\%\#} operator: \kbd{\%\#1}, \kbd{\%\#2},203\kbd{\%\#`}; \kbd{\%\#} by itself returns the time needed to compute the last204result (the one returned by \kbd{\%}). The output is a vector with two205components \kbd{[cpu, real]} where \kbd{cpu} is the CPU time and \kbd{real} is206the wall clock time.207208\misctitle{Remark}209The history ``array'' is in fact better thought of as a queue: its size is210limited to 5000 entries by default, after which \kbd{gp} starts forgetting211the initial entries. So \kbd{\%1} becomes unavailable as \kbd{gp} prints212\kbd{\%5001}. You can modify the history size using \tet{histsize}.213214\subsec{Special editing characters}\sidx{editing characters} A GP program215can of course have more than one line. Since your commands are executed as216soon as you have finished typing them, there must be a way to tell \kbd{gp}217to wait for the next line or lines of input before doing anything. There are218three ways of doing this.219220The first one is to use the \idx{backslash character} \kbd{\bs} at the end of221the line that you are typing, just before hitting \kbd{<Return>}. This tells222\kbd{gp} that what you will write on the next line is the physical223continuation of what you have just written. In other words, it makes \kbd{gp}224forget your newline character. You can type a \kbd{\bs} anywhere. It is225interpreted as above only if (apart from ignored whitespace characters) it is226immediately followed by a newline. For example, you can type227\bprog228? 3 + \2294230@eprog231\noindent instead of typing \kbd{3 + 4}.232233The second one is a variation on the first, and is mostly useful when234defining a user function (see \secref{se:user_defined}): since an equal sign235can never end a valid expression, \kbd{gp} disregards a newline immediately236following an \kbd{=}.237\bprog238? a =239123240%1 = 123241@eprog242243The third one is in general much more useful, and uses braces \kbd{\obr} and244\kbd{\cbr}.\sidx{brace characters} An opening brace \kbd{\obr} signals that245you are typing a multi-line command, and newlines are ignored until you type246a closing brace \kbd{\cbr}. There are two important, but easily obeyed,247restrictions: first, braces do not nest; second, inside an open brace-close248brace pair, all input lines are concatenated, suppressing any newlines. Thus,249all newlines should occur after a semicolon (\kbd{;}), a comma (\kbd{,}) or250an operator (for clarity's sake, never split an identifier over two lines in251this way). For instance, the following program252\bprog253{254a = b255b = c256}257@eprog258259\noindent would silently produce garbage, since this is interpreted as260\kbd{a=bb=c} which assigns the value of \kbd{c} to both \kbd{bb} and261\kbd{a}. It should have been written262\bprog263{264a = b;265b = c;266}267@eprog268269\section{The PARI types}270271\noindent272We see here how to input values of the different data types known to PARI.273Recall that blanks are ignored in any expression which is not a string (see274below).275276\misctitle{A note on efficiency}277The following types are provided for convenience, not for speed:278\typ{INTMOD}, \typ{FRAC}, \typ{PADIC}, \typ{QUAD}, \typ{POLMOD},279\typ{RFRAC}. Indeed, they always perform a reduction of some kind after280each basic operation, even though it is usually more efficient to perform281a single reduction at the end of some complex computation. For instance,282in a convolution product $\sum_{i+j = n} x_i y_j$ in $\Z/N\Z$ --- common283when multiplying polynomials! ---, it is quite wasteful to perform $n$284reductions modulo $N$. In short, basic individual operations on these types285are fast, but recursive objects with such components could be handled more286efficiently: programming with libpari will save large constant factors here,287compared to GP.288289\subsec{Integers (\typ{INT})}%290\sidx{integer}\kbdsidx{t_INT}291After an (optional) leading \kbd{+} or \kbd{-}, type in the292decimal digits of your integer. No decimal point!293\bprog294? 1234567295%1 = 1234567296? -3297%2 = -3298? 1. \\@com oops, not an integer299%3 = 1.000000000000000000000000000300@eprog301302Integers can be input in hexadecimal notation by prefixing them with303\kbd{0x}; hexadecimal digits ($a, \dots, f$) can be input either in lowercase304or in uppercase:305\bprog306? 0xF307%4 = 15308? 0x1abcd309%5 = 109517310@eprog311312Integers can also be input in binary by prefixing them with313\kbd{0b}:314\bprog315? 0b010101316%6 = 21317@eprog318319\subsec{Real numbers (\typ{REAL})}%320\sidx{real number}\kbdsidx{t_REAL}321322Real numbers are represented (approximately) in a floating point system,323internally in base 2, but converted to base 10 for input / output purposes.324A \typ{REAL} object has a given \emph{bit accuracy} (or \emph{bit precision})325$\ell \geq 0$; it comprises326327\item a sign $s$: $+1$, $-1$ or $0$;328329\item a mantissa $m$: a multiprecision integer, $0\leq m < 2^\ell$;330331\item an exponent $e$: a small integer in $[-2^B,2^B[$, where $B = 31$ on a33232-bit machine and 63 otherwise.333334This data may represent any real number $x$ such that335$$|x - s m 2^e| < 2^{e-\ell}.$$336We consider that a \typ{REAL} with sign $s = 0$ has accuracy $\ell = 0$, so337that its mantissa is useless, but it still has an exponent $e$ and acts like338a machine epsilon for all accuracies $< e$.339340After an (optional) leading \kbd{+} or \kbd{-}, type a number with a decimal341point. Leading zeroes may be omitted, up to the decimal point, but trailing342zeroes are important: your \typ{REAL} is assigned an internal precision,343which is the supremum of the input precision, one more than the number of344decimal digits input, and the default \tet{realprecision}. For example, if345the default precision is 38 digits, typing \kbd{2.} yields a precision of 38346digits, but \kbd{2.0\dots0} with 45 zeros gives a number with internal347decimal precision at least 45, although less may be printed.348349You can also use scientific notation with the letter \kbd{E} or350\kbd{e}. As usual, \kbd{e$n$} is interpreted as $\times 10^n$ for all351integers $n$. Since the result is converted to a \typ{REAL}, you may often352omit the decimal point in this case: \kbd{6.02 E 23} or \kbd{1e-5} are fine,353but \kbd{e10} is not.354355By definition, \kbd{0.E $n$} returns a real $0$ of exponent $n$, whereas356\kbd{0.} returns a real 0 ``of default precision'' (of exponent357$-\tet{realprecision}$), see \secref{se:whatzero}, behaving like the machine358epsilon for the current default accuracy: any float of smaller absolute value359is indistinguishable from $0$.360361\misctitle{Note on output formats} A zero real number is printed in \kbd{e}362format as $0.Exx$ where $xx$ is the (usually negative) \emph{decimal}363exponent of the number (cf.~\secref{se:whatzero}). This allows the user to364check the accuracy of that particular zero.365366When the integer part of a real number $x$ is not known exactly because the367exponent of $x$ is greater than the internal precision, the real number is368printed in \kbd{e} format.369370\misctitle{Technical note} The internal \emph{precision} is actually371expressed in bits and can be viewed and manipulated globally in interactive372use via \kbd{realprecision} (decimal digits, as explained above; shortcut373\kbd{\bs p}) or \kbd{realbitprecision} (bits; shortcut \kbd{\bs ps}), the374latter allowing finer granularity. See \secref{se:trans} for details. In375programs we advise to leave this global variable alone and adapt precision376locally for a given sequence of computations using \tet{localbitprec}.377378Note that most decimal floating point numbers cannot be converted exactly379in binary, the (binary) number actually stored is a rounded version of the380(decimal) number input. Analogously, a decimal output is rounded381from the internal binary representation.382383\subsec{Intmods (\typ{INTMOD})}%384\sidx{intmod}\kbdsidx{t_INTMOD}385To create the image of the integer $a$ in $\Z/b\Z$ (for some nonzero386integer $b$), type \kbd{Mod(a,b)}; \emph{not} \kbd{a\%b}.387Internally, all operations are done on integer representatives belonging to388$[0,b-1]$.389390Note that this type is available for convenience, not for speed: each391elementary operation involves a reduction modulo $b$.392393If $x$ is a \typ{INTMOD} \kbd{Mod(a,b)}, the following member function is394defined:395396\kbd{x.mod}: return the modulus \kbd{b}.397398\subsec{Rational numbers (\typ{FRAC})}%399\sidx{rational number}\kbdsidx{t_FRAC}400All fractions are automatically reduced to lowest401terms, so it is impossible to work with reducible fractions. To enter $n/m$402just type it as written. As explained in \secref{se:gdiv}, floating point403division is \emph{not} performed, only reduction to lowest404terms.\label{se:FRAC}405406Note that rational computation are almost never the fastest method to proceed:407in the PARI implementation, each elementary operation involves computing a gcd.408It is generally a little more efficient to cancel denominators and work with409integers only:410\bprog411? P = Pol( vector(10^3,i, 1/i) ); \\@com big polynomial with small rational coeffs412? P^2413time = 1,392 ms.414? c = content(P); c^2 * (P/c)^2; \\@com same computation in integers415time = 1,116 ms.416@eprog\noindent417And much more efficient (but harder to setup) to use homomorphic imaging418schemes and modular computations. As the simple example below indicates, if you419only need modular information, it is very worthwhile to work with420\typ{INTMOD}s directly, rather than deal with \typ{FRAC}s all the way through:421\bprog422? p = nextprime(10^7);423? sum(i=1, 10^5, 1/i) % p424time = 13,288 ms.425%1 = 2759492426? sum(i=1, 10^5, Mod(1/i, p))427time = 60 ms.428%2 = Mod(2759492, 10000019)429@eprog\noindent430431\subsec{Finite field elements (\typ{FFELT})}%432\sidx{finite field element}\kbdsidx{t_FFELT}433Let $T\in\F_p[X]$ be a monic irreducible polynomial defining your434finite field over $\F_p$, for instance obtained using \tet{ffinit}. Then the435\tet{ffgen} function creates a generator of the finite field as an436$\F_p$-algebra, namely the class of $X$ in $\F_p[X]/(T)$, from which you can437build all other elements. For instance, to create the field $\F_{2^8}$, we438write439\bprog440? T = ffinit(2, 8);441? y = ffgen(T, 'y);442? y^0 \\ the unit element in the field443%3 = 1444? y^8445%4 = y^6 + y^5 + y^4 + y^3 + y + 1446@eprog\noindent447The second (optional) parameter to \tet{ffgen} is only used to display448the result; it is customary to use the name of the variable we assign the449generator to. If \kbd{g} is a \typ{FFELT}, the following member functions are450defined:451452\kbd{g.pol}: the polynomial (with reduced integer coefficients)453expressing \kbd{g} in term of the field generator.454455\kbd{g.p}: the characteristic of the finite field.456457\kbd{g.f}: the dimension of the definition field over its prime field; the458cardinality of the definition field is thus $p^f$.459460\kbd{g.mod}: the minimal polynomial (with reduced integer461coefficients) of the field generator.462463\subsec{Complex numbers (\typ{COMPLEX})}%464\sidx{complex number}\kbdsidx{t_COMPLEX}465To enter $x+iy$, type \kbd{x + I*y}. (That's \kbd{I}, \emph{not} \kbd{i}!)466The letter \tet{I} stands for $\sqrt{-1}$. The ``real'' and ``imaginary''467parts $x$ and $y$ can be of type \typ{INT}, \typ{REAL}, \typ{INTMOD},468\typ{FRAC}, or \typ{PADIC}.469470\subsec{$p$-adic numbers (\typ{PADIC}):}%471\sidx{p-adic number}\label{se:padic}\kbdsidx{t_PADIC}472Typing \kbd{O($p$\pow $k$)}, where $p$ is a prime and $k$ is an integer,473yields a $p$-adic $0$ of accuracy~$k$, representing any $p$-adic number whose474valuation is $\geq k$. To input a general nonzero $p$-adic number, write475a suitably precise rational or integer approximation and add \kbd{O($p$\pow476$k$)} to it. For example, you can type in the $7$-adic number477\bprog4782*7^(-1) + 3 + 4*7 + 2*7^2 + O(7^3)479@eprog\noindent exactly as shown, or equivalently as \kbd{905/7 + O(7\pow3)}.480481Note that it is not checked whether $p$ is indeed prime but results are482undefined if this is not the case: you can try to work on $10$-adics if483you want, but disasters will happen as soon as you do something nontrivial.484For instance:485\bprog486? t = 2 * (1/10 + O(10^5));487? lift(t)488%2 = 2/10 \\ not reduced (invalid t_FRAC)489? factor(x^2-t)490*** at top-level: factor(x^2-%1)491*** ^--------------492*** factor: impossible inverse in Fl_inv: Mod(2, 10000).493@eprog\noindent Note that \kbd{O(25)} is not the same as \kbd{O(5\pow 2)};494you want the latter!495496If $a$ is a \typ{PADIC}, the following member functions are defined:497498\kbd{a.mod}: returns the modulus $p^k$.499500\kbd{a.p}: returns $p$.501502Note that this type is available for convenience, not for speed:503internally, \typ{PADIC}s are stored as $p$-adic units modulo some $p^k$.504Each elementary operation involves updating $p^k$ (multiplying or505dividing by powers of $p$) and a reduction mod $p^k$. In particular,506additions are slow.507\bprog508? n = 1+O(2^20); for (i=1,10^6, n++)509time = 841 ms.510? n = Mod(1,2^20); for (i=1,10^6, n++)511time = 441 ms.512? n = 1; for (i=1,10^6, n++)513time = 328 ms.514@eprog\noindent The penalty attached to maintaining $p^k$ decreases515steeply as $p$ increases (and updates become rare). But \typ{INTMOD}s516remain at least 25\% more efficient. (On the other hand, they do not allow517denominators!)518% n = 1+O(1009^2); for (i=1,10^6, n++)519% n = Mod(1,1009^2); for (i=1,10^6, n++)520521\subsec{Quadratic numbers (\typ{QUAD})}%522\sidx{quadratic number}\kbdsidx{t_QUAD}523This type is used to work in the quadratic order of \emph{discriminant}524\kbd{d}, where \kbd{d} is a nonsquare integer congruent to $0$ or $1$525(modulo $4$). The command526\bprog527w = quadgen(d,'w)528@eprog\noindent529assigns to \kbd{w} the ``canonical'' generator for the integer basis530of the order of discriminant $d$, i.e.~$w=\sqrt{d}/2$ if $d\equiv 0 \mod 4$,531and $w=(1+\sqrt{d})/2$ if $d\equiv 1 \mod 4$ and set its name to \kbd{w}.532The name \kbd{'w} is used for printing and we advise to store it in a variable533of the same name.534Beware, two \typ{QUAD}s with different discriminants can be printed in the same535way and not be equal; however, \kbd{gp} will refuse to add or multiply them for536example, so use different names for different discriminants.537538Since the order is $\Z + \kbd{w}\Z$, any other element can be input539as \kbd{z = $x$+$y$*w} for some integers $x$ and $y$. In fact, you may work in540its fraction field $\Q(\sqrt{d})$ and use \typ{FRAC} values for $x$ and $y$.541542The member function \kbd{z.disc} retrieves the discriminant $d$; $x$ and $y$543are obtained via \kbd{real(z)} and \kbd{imag(z)} respectively.544545\subsec{Polmods (\typ{POLMOD})}%546\sidx{polmod}\kbdsidx{t_POLMOD}547Exactly as for intmods, to enter $x \mod y$ (where $x$ and $y$ are548polynomials), type \kbd{Mod(x,y)}, not \kbd{x\%y}. Note that when $y$ is an549irreducible polynomial in one variable, polmods whose modulus is $y$ are simply550algebraic numbers in the finite extension defined by the polynomial $y$.551This allows us to work easily in \idx{number field}s, finite extensions of552the $p$-adic field $\Q_p$, or \idx{finite field}s.553554Note that this type is available for convenience, not for speed: each555elementary operation involves a reduction modulo $y$.556If $p$ is a \typ{POLMOD}, the following member functions are defined:557558\kbd{p.pol}: return a representative of the polynomial class of minimal degree.559560\kbd{p.mod}: return the modulus.561562\label{se:rempolmod}563\misctitle{Important remark}\sidx{variable (priority)}564Mathematically, the variables\sidx{variable} occurring in a polmod are not565free variables. But internally, a congruence class in $R[t]/(y)$ is566represented by its representative of lowest degree, which is a \typ{POL} in567$R[t]$, and computations occur with polynomials in the variable $t$. PARI568will not recognize that \kbd{Mod(y, y\pow2 + 1)} is ``the same'' as569\kbd{Mod(x, x\pow2 + 1)}, since \kbd{x} and \kbd{y} are different variables.570571To avoid inconsistencies, polmods must use the same variable in internal572operations (i.e.~between polmods) and variables of lower priority for573external operations, typically between a polynomial and a polmod. See574\secref{se:priority} for a definition of ``priority'' and a discussion of575(PARI's idea of) multivariate polynomial arithmetic.576For instance:577\bprog578? Mod(x, x^2+ 1) + Mod(x, x^2 + 1)579%1 = Mod(2*x, x^2 + 1) \\@com $2i$ (or $-2i$), with $i^2=-1$580? x + Mod(y, y^2 + 1)581%2 = x + Mod(y, y^2 + 1) \\@com in $\Q(i)[x]$582? y + Mod(x, x^2 + 1)583%3 = Mod(x + y, x^2 + 1) \\@com in $\Q(y)[i]$584@eprog\noindent585The first two are straightforward, but the last one may not be what you586want: \kbd{y} is treated here as a numerical parameter, not as a polynomial587variable.588589If the main variables are the same, it is allowed to mix \typ{POL} and590\typ{POLMOD}s. The result is the expected \typ{POLMOD}. For instance591\bprog592? x + Mod(x, x^2 + 1)593%1 = Mod(2*x, x^2 + 1)594@eprog595596\subsec{Polynomials (\typ{POL})}%597\sidx{polynomial}\label{se:pol}\kbdsidx{t_POL}598Type the polynomial in a natural way, not forgetting to put a ``$*$'' between599a coefficient and a formal variable;600\bprog601? 1 + 2*x + 3*x^2602%1 = 3*x^2 + 2*x + 1603@eprog\noindent604This assumes that \kbd{x} is still a ''free variable''.605\bprog606? x = 1; 1 + 2*x + 3*x^2607%2 = 6608@eprog\noindent609generates an integer, not a polynomial! It is good practice to never assign610values to polynomial variables to avoid the above problem, but a foolproof611construction is available using \kbd{'x} instead of~\kbd{x}: \kbd{'x}612is a constant evaluating to the free variable with name \kbd{x},613independently of the current value of~\kbd{x}.614\bprog615? x = 1; 1 + 2*'x + 3*'x^2616%3 = 1 + 2*x + 3*x^2617? x = 'x; 1 + 2*x + 3*x^2618%4 = 1 + 2*x + 3*x^2619@eprog\noindent620You may also use the functions \kbd{Pol} or \kbd{Polrev}:621\bprog622? Pol([1,2,3]) \\@com \kbd{Pol} creates a polynomial in \kbd{x} by default623%1 = x^2 + 2*x + 3624? Polrev([1,2,3])625%2 = 3*x^2 + 2*x + 1626? Pol([1,2,3], 'y) \\@com we use \kbd{'y}, safer than \kbd{y}627%3 = y^2 + 2*y + 3628@eprog\noindent The latter two are much more efficient constructors than an629explicit summation (the latter is quadratic in the degree, the former linear):630\bprog631? for (i=1, 10^4, Polrev( vector(100, i,i) ) )632time = 124ms633634? for (i=1, 10^4, sum(i = 1, 100, (i+1) * 'x^i) )635time = 3,985ms636@eprog637638Polynomials are always printed as \emph{univariate} polynomials over a639commutative base ring, with monomials sorted by decreasing degree:640\bprog641? (x+y+1)^2642%1 = x^2 + (2*y + 2)*x + (y^2 + 2*y + 1)643@eprog\noindent644(Univariate polynomial in \kbd{x} whose coefficients are polynomials in645\kbd{y}.) See \secref{se:varsymb} for valid variable names, and a discussion646of multivariate polynomial rings. Polynomials over noncommutative rings647are not supported.648649\subsec{Power series (\typ{SER})}%650\sidx{power series}\kbdsidx{t_SER}\label{se:series}651Typing \kbd{O(X\pow $k$)}, where $k$ is an integer, yields an $X$-adic $0$ of652accuracy~$k$, representing any power series in \kbd{X} whose valuation is653$\geq k$. Of course, \kbd{X} can be replaced by any other variable name! To654input a general nonzero power series, type in a polynomial or rational655function (in \kbd{X}, say), and add \kbd{O(X\pow $k$)} to it. The discussion656in the \typ{POL} section about variables remains valid; a constructor657\tet{Ser} replaces \tet{Pol} and \tet{Polrev}. Power series over658noncommutative rings are not supported.659660\misctitle{Caveat} Power series with inexact coefficients sometimes have a661nonintuitive behavior: if $k$ significant terms are requested, an inexact662zero is counted as significant, even if it is the coefficient of lowest663degree. This means that useful higher order terms may be disregarded.664665If a series with a zero leading coefficient must be inverted, then as a666desperation measure that coefficient is discarded, and a warning is issued:667\bprog668? C = 0. + y + O(y^2);669? 1/C670*** _/_: Warning: normalizing a series with 0 leading term.671%2 = y^-1 + O(1)672@eprog\noindent673The last output could be construed as a bug since it is a priori impossible674to deduce such a result from the input ($0.$ represents any sufficiently675small real number). But it was thought more useful to try and go on with an676approximate computation than to raise an early exception.677678If the series precision is insufficient, errors may occur (mostly division679by $0$), which could have been avoided by a better global understanding of680the computation:681\bprog682? A = 1/(y + 0.); B = 1. + O(y);683? B * denominator(A)684%2 = 0.E-28 + O(y)685? A/B686*** _/_: Warning: normalizing a series with 0 leading term.687%3 = 1.000000000000000000000000000*y^-1 + O(1)688? A*B689*** _*_: Warning: normalizing a series with 0 leading term.690%4 = 1.000000000000000000000000000*y^-1 + O(1)691@eprog692693\subsec{Rational functions (\typ{RFRAC})}%694\sidx{rational function}\kbdsidx{t_RFRAC}695As for fractions, all rational functions are automatically reduced to lowest696terms. All that was said about fractions in \secref{se:FRAC} remains valid697here.698699\subsec{Binary quadratic forms (\typ{QFB})}%700\sidx{binary quadratic form}\kbdsidx{t_QFB}701These are input using the function \kbd{Qfb}. For example, both \kbd{Qfb(1,2,3)}702and \kbd{Qfb([1,2,3])} create the binary form $q = x^2+2xy+3y^2$. It is703imaginary since its discriminant $2^2 - 4\times 3 = -8$ is negative. Although704imaginary forms could be positive or negative definite, only positive705definite forms are implemented.706707The discriminant can be retrieved via \kbd{q.disc}. The individual708components are obtained via either of709\bprog710[a,b,c] = Vec(q);711712a = component(q,1);713b = component(q,2);714c = component(q,3);715@eprog716717See also the function718\kbd{qfbprimeform} which creates a prime form of given discriminant.719720\subsec{Row and column vectors (\typ{VEC} and \typ{COL})}%721\sidx{row vector}\sidx{column vector}\kbdsidx{t_VEC}\kbdsidx{t_COL}722To enter a row vector, type the components separated by commas ``\kbd{,}'',723and enclosed between brackets ``\kbd{[}$\,$'' and ``$\,$\kbd{]}'',724e.g.~\kbd{[1,2,3]}. To enter a column vector, type the vector horizontally,725and add a tilde ``\til'' to transpose. \kbd{[ ]} yields the empty (row)726vector. The function \tet{Vec} can be used to transform any object into a727vector (see Chapter~3). The construction $[i..j]$, where $i \leq j$ are two728integers returns the vector $[i, i+1,\dots, j-1, j]$729\bprog730? [1,2,3]731%1 = [1, 2, 3]732? [-2..3]733%2 = [-2, -1, 0, 1, 2, 3]734@eprog735736Let the variable $v$ contain a (row or column) vector:737738\item \kbd{v[m]} refers to its $m$-th entry; you can assign any value to739\kbd{v[m]}, i.e.~write something like $v[m]=\var{expr}$.740741\item \kbd{v[i..j]}, where $i \leq j$, returns the vector slice containing742elements $v[i],\dots, v[j]$; you can \emph{not} assign a result to743\kbd{v[i..j]}.744745\item \kbd{v[\pow i]} returns the vector whose $i$-th entry has been removed;746you can \emph{not} assign a result to \kbd{v[\pow i]}.747748\noindent In the last two constructions \kbd{v[i..j]} and \kbd{v[\pow i]},749$i$ and $j$ are allowed to be negative integers, in which case, we start750counting from the end of the vector: e.g., $-1$ is the index of the last751element.752\bprog753? v = [1,2,3,4];754? v[2..4]755%2 = [2, 3, 4]756? v[^3]757%3 = [1, 2, 4]758? v[^-1]759%3 = [1, 2, 3]760? v[-3..-1]761%4 = [2, 3, 4]762@eprog763764\misctitle{Remark} \tet{vector} is the standard constructor for row vectors765whose $i$-th entry is given by a simple function of $i$; \tet{vectorv}766is similar for column vectors:767\bprog768? vector(10, i, i^2+1)769%1 = [2, 5, 10, 17, 26, 37, 50, 65, 82, 101]770@eprog771The functions \tet{Vec} and \tet{Col} convert objects to row and column772vectors respectively (as well as \tet{Vecrev} and \tet{Colrev}, which revert773the indexing):774\bprog775? T = poltchebi(5) \\ 5-th Chebyshev polynomial776%1 = 16*x^5 - 20*x^3 + 5*x777? Vec(T)778%2 = [16, 0, -20, 0, 5, 0] \\ coefficients of T779? Vecrev(T)780%3 = [0, 5, 0, -20, 0, 16] \\ ... in reverse order781@eprog782783\misctitle{Remark} For $v$ a \typ{VEC}, \typ{COL}, \typ{VECSMALL},784\typ{LIST} or \typ{MAT}, the alternative set-notations785\bprog786[g(x) | x <- v, f(x)]787[x | x <- v, f(x)]788[g(x) | x <- v]789@eprog\noindent790are available as shortcuts for791\bprog792apply(g, select(f, Vec(v)))793select(f, Vec(v))794apply(g, Vec(v))795@eprog\noindent respectively, and may serve as \typ{VEC} constructors:796\bprog797? [ p | p <- primes(10), isprime(p+2) ]798%2 = [3, 5, 11, 17, 29]799@eprog\noindent returns the primes $p$ (among the first 10 primes) such800that $(p, p+2)$ is a twin pair;801\bprog802? [ p^2 | p <- primes(10), p % 4 == 1 ]803%1 = [25, 169, 289, 841]804@eprog\noindent returns the squares of the primes congruent to $1$ modulo $4$,805where $p$ runs among the first 10 primes.806807\subsec{Matrices (\typ{MAT})}%808\sidx{matrix}\kbdsidx{t_MAT}809To enter a matrix, type the components row by row, the components being810separated by commas ``\kbd{,}'', the rows by semicolons ``\kbd{;}'', and811everything enclosed in brackets ``\kbd{[}$\,$'' and ``$\,$\kbd{]}'', e.g.812\kbd{[x,y; z,t; u,v]}. \kbd{[;]} yields an empty ($0 \times 0$) matrix. The813function \tet{Mat} transforms any object into a matrix, and \tet{matrix}814creates matrices whose $(i,j)$-th entry is described by a function $f(i,j)$:815\bprog816? Mat(1)817%1 =818[1]819? matrix(2,2, i,j, 2*i+j)820%2 =821[3 4]822823[5 6]824@eprog\noindent Matrix multiplication assumes that the base ring containing825the matrix entries is commutative.826827\noindent Let the variable $M$ contain a matrix, and let $i,j,k,l$ denote828four829integers:830831\item \kbd{M[i,j]} refers to its $(i,j)$-th entry; you can assign any result832to \kbd{M[i,j]}.833834\item \kbd{M[i,]} refers to its $i$-th row; you can assign a \typ{VEC}835of the right dimension to \kbd{M[i,]}.836837\item \kbd{M[,j]} refers to its $j$-th column; you can assign a \typ{COL}838of the right dimension to \kbd{M[,j]}.839840\noindent \emph{But} \kbd{M[i]} is meaningless and triggers an error. The841``range'' $i..j$ and ``caret'' \kbd{\pow}$c$ notations are available as for842vectors; you can not \emph{assign} to any of these:843844\item \kbd{M[i..j, k..l]}, $i\leq j$, $k\leq l$, returns the submatrix built845from the rows $i$ to $j$ and columns $k$ to $l$ of $M$.846847\item \kbd{M[i..j,]} returns the submatrix built from the rows $i$ to848$j$ of $M$.849850\item \kbd{M[,i..j]} returns the submatrix built from the columns $i$ to851$j$ of $M$.852853\item \kbd{M[i..j, \pow k]}, $i\leq j$, returns the submatrix built854from the rows $i$ to $j$ and column $k$ removed.855856\item \kbd{M[\pow k,]} returns the submatrix with row $k$ removed.857858\item \kbd{M[,\pow k]} returns the submatrix with column $k$ removed.859860\noindent Finally,861862\item \kbd{M[i..j, k]} returns the \typ{COL} built from the $k$-th column863(entries $i$ to $j$).864865\item \kbd{M[\pow i, k]} returns the \typ{COL} built from the $k$-th column866(entry $i$ removed).867868\item \kbd{M[k, i..j]} returns the \typ{VEC} built from the $k$-th row869(entries $i$ to $j$).870871\item \kbd{M[k, \pow i]} returns the \typ{VEC} built from the $k$-th row872(entry $i$ removed).873874\bprog875? M = [1,2,3;4,5,6;7,8,9];876? M[1..2, 2..3]877%2 =878[2 3]879880[5 6]881? M[1..2,]882%3 =883[1 2 3]884885[4 5 6]886? M[,2..3]887%4 =888[2 3]889890[5 6]891892[8 9]893@eprog894895All this is recursive, so if \kbd{M} is a matrix of matrices of \dots, an896expression such as \kbd{M[1,1][,3][4] = 1} is perfectly valid (and actually897identical to \kbd{M[1,1][4,3] = 1}), assuming that all matrices along the way898have compatible dimensions.899900\misctitle{Technical note (design flaw)} Matrices are internally represented901as a vector of columns. All matrices with $0$ columns are thus represented902by the same object (internally, an empty vector), and there is no way to903distinguish between them. Thus it is not possible to create or represent904matrices with zero columns and an actual nonzero number of rows.905The empty matrix \kbd{[;]} is handled as though it had an arbitrary number of906rows, exactly as many as needed for the current computation to make sense:907\bprog908? [1,2,3; 4,5,6] * [;]909%1 = [;]910@eprog\noindent911The empty matrix on the first line is understood as a $3\times 0$ matrix, and912the result as a $2\times 0$ matrix. On the other hand, it is possible to913create matrices with a given positive number of columns, each of which has914zero rows, e.g.~using \kbd{Mat} as above or using the \kbd{matrix} function.915916Note that although the internal representation is essentially the same, a row917vector of column vectors is \emph{not} a matrix; for example, multiplication918will not work in the same way. It is easy to go from one representation to919the other using \tet{Vec} / \tet{Mat}, though:920\bprog921? [1,2,3;4,5,6]922%1 =923[1 2 3]924925[4 5 6]926927? Vec(%)928%2 = [[1, 4]~, [2, 5]~, [3, 6]~]929? Mat(%)930%3 =931[1 2 3]932933[4 5 6]934@eprog935936\subsec{Lists (\typ{LIST})}%937\sidx{list}\kbdsidx{t_LIST}938Lists can be input directly, as in \kbd{List([1,2,3,4])}; but in most cases,939one creates an empty list, then appends elements using \kbd{listput}:940\bprog941? L = List(); listput(~L,1); listput(~L,2);942? L943%2 = List([1, 2])944@eprog\noindent945Note the \kbd{\til L}: this means that the function is called with a946\emph{reference} to \kbd{L} and changes \kbd{L} in place. Elements can be947accessed directly as with the vector types described above.948949\subsec{Strings (\typ{STR})}%950\sidx{string}\sidx{character string}\kbdsidx{t_STR}951To enter a string, enclose it between double quotes \kbd{"}, as in:952\kbd{"this is a string"}. The function \kbd{Str} can be used to transform any953object into a string.954955\subsec{Small vectors (\typ{VECSMALL})}%956\kbdsidx{t_VECSMALL}957This type codes in an efficient way vectors containing only small integers,958such as permutations. Most \kbd{gp} functions will refuse to operate on these959objects, notable exceptions being \kbd{vecsort} and conversion functions960such as \kbd{VEC}, but you can retrieve entries and assign to them as961for ordinary vectors. You can also convert back and forth between962\typ{VECSMALL} and \typ{VEC} objects using \tet{Vec} and \tet{Vecsmall}.963\bprog964? v = Vecsmall([2, 4, 6])965%1 = Vecsmall([1, 2, 3])966? v[1]967%2 = 2968? v[1] = 3; v969%3 = Vecsmall([3, 2, 3])970? v[2..3]971%4 = Vecsmall([2, 3])972? v[^2]973%5 = Vecsmall([3, 3])974? Vec(v)975%6 = [3, 2, 3]976@eprog\noindent977Allowed entries for a \typ{VECMALL} are signed integer $x$ such that $|x| <9782^{31}$ on a 32-bit architecture, resp.~$|x| < 2^{63}$ on a 64-bit979architecture Assigning a larger integer to a \typ{VECSMALL} entry triggers an980exception:981\bprog982? v[1] = 2^63983*** at top-level: v[1]=2^63984*** ^----------985*** incorrect type in t_VECSMALL assignment (t_INT).986@eprog987988\subsec{Functions (\typ{CLOSURE})}%989\kbdsidx{t_CLOSURE}990We will explain this at length in \secref{se:user_defined}. For the time991being, suffice it to say that functions can be assigned to variables, as any992other object, and the following equivalent basic forms are available to993create new ones994\bprog995f = (x,y) -> x^2 + y^2996997f(x,y) = x^2 + y^2998@eprog9991000\subsec{Error contexts (\typ{ERROR})}%1001\kbdsidx{t_ERROR}1002An object of this type is created whenever an error occurs: it contains some1003information about the error and the error context. Usually, an appropriate1004error is printed immediately, the computation is aborted, and GP enters the1005``break loop'':1006\bprog1007? 1/0; 1 + 11008*** at top-level: 1/0;1+11009*** ^------1010*** _/_: division by a noninvertible object1011*** Break loop: type 'break' to go back to the GP prompt10121013@eprog\noindent Here the computation is aborted as soon as we try to evaluate1014$1/0$, and $1 + 1$ is never executed. Exceptions can be trapped1015using \tet{iferr}, however: we can evaluate some expression and either recover1016an ordinary result (no error occurred), or an exception (an error did occur).1017\bprog1018? i = Mod(6,12); iferr(1/i, E, print(E)); 1 + 11019error("impossible inverse modulo: Mod(6, 12).")1020%1 = 21021@eprog\noindent One can ignore the exception, print it as above, or extract1022non trivial information from the error context:1023\bprog1024? i = Mod(6,12); iferr(1/i, E, print(component(E,1)));1025Mod(6, 12)1026@eprog\noindent We can also rethrow the exception: \kbd{error(E)}.10271028\subsec{Infinity (\typ{INFINITY})}%1029\kbdsidx{t_INFINITY}10301031There are only two objects of this type \kbd{+oo} and \kbd{-oo}, representing1032$\pm\infty$. This type only contain only two elements \kbd{oo} and \kbd{-oo},1033They are used in functions sur as \kbd{intnum} or \kbd{polrootsreal}, to1034encode infinite real intervals. These objects can only be negated and1035compared to real numbers (\typ{INT}, \typ{REAL}, \typ{FRAC}), but not1036included in any computation, i.e.~\kbd{1+oo} is an error, not kbd{oo} again.10371038\section{GP operators}\label{se:operators}10391040\noindent Loosely speaking, an \idx{operator} is a function, usually1041attached to basic arithmetic operations, whose name contains only1042nonalphanumeric characters. For instance \kbd{+} or \kbd{-}, but also1043\kbd{=} or \kbd{+=}, or even \kbd{[ ]} (the selection operator). As all1044functions, operators take arguments, and return a value; \emph{assignment}1045operators also have side effects: besides returning a value, they change the1046value of some variable.10471048Each operator has a fixed and unchangeable priority, which means that, in1049a given expression, the operations with the highest priority is performed1050first. Unless mentioned otherwise, operators at the same priority level are1051left-associative (performed from left to right), unless they are assignments,1052in which case they are right-associative. Anything enclosed between1053parenthesis is considered a complete subexpression, and is resolved1054recursively, independently of the surrounding context. For instance,1055\bprog1056a + b + c --> (a + b) + c \\@com left-associative1057a = b = c --> a = (b = c) \\@com right-associative1058@eprog\noindent1059Assuming that \var{op}$_1$, \var{op}$_2$, \var{op}$_3$ are1060binary operators with increasing priorities (think of \kbd{+},1061\kbd{*}, \kbd{\pow}),1062$$ x~\var{op}_1~y~\var{op}_2~z~\var{op}_2~x~\var{op}_3~y $$ is1063equivalent to $$ x~\var{op}_1~((y~\var{op}_2~z)~\var{op}_2~1064(x~\var{op}_3~y)).$$10651066GP contains many different operators, either unary (having only1067one argument) or binary, plus a few special selection operators. Unary1068operators are defined as either \emph{prefix} or \emph{postfix}, meaning1069that they respectively precede (\var{op}~$x$) and follow ($x$~\var{op}) their1070single argument. Some symbols are syntactically correct in both positions,1071like \kbd{!}, but then represent different operators: the \kbd{!} symbol1072represents the negation and factorial operators when in prefix and postfix1073position respectively. Binary operators all use the (infix) syntax1074$x$~\var{op}~$y$.10751076Most operators are standard (\kbd{+}, \kbd{\%}, \kbd{=}), some are1077borrowed from the C language (\kbd{++}, \kbd{<<}), and a few are1078specific to GP (\kbd{\bs}, \kbd{\#}). Beware that some GP operators differ1079slightly from their C counterparts. For instance, GP's postfix \kbd{++}1080returns the \emph{new} value, like the prefix \kbd{++} of~C, and the binary1081shifts \kbd{<<}, \kbd{>>} have a priority which is different from (higher1082than) that of their C counterparts. When in doubt, just surround everything1083by parentheses; besides, your code will be more legible.10841085\noindent Here is the list of available operators, ordered by decreasing1086\idx{priority}, binary and left-associative unless mentioned otherwise. An1087expression is an \tev{lvalue} if something can be assigned to it. (The name1088comes from left-value, to the left of a \kbd{=} operator; e.g.1089\kbd{x}, or \kbd{v[1]} are lvalues, but \kbd{x + 1} is not.)10901091\def\point#1{\noindent\item #1\hfill\break\indent\strut}1092\point{Priority 14}1093%1094\kbd{:} as in \kbd{x:small}, is used to indicate to the GP2C compiler that the1095variable on the left-hand side always contains objects of the type specified1096on the right hand-side (here, a small integer) in order to produce more1097efficient or more readable C code. This is ignored by GP.10981099%1100\point{Priority 13}1101\kbd{( )} is the function call operator. If $f$ is a closure and \var{args}1102is a comma-separated list of arguments (possibly empty),1103$f\kbd{(\var{args})}$ evaluates $f$ on those arguments.11041105\point{Priority 12}1106%1107\kbd{++} and \kbd{--} (unary, postfix): if $x$ is an \tet{lvalue},1108\kbd{$x$++} assigns the value $x+1$ to $x$, then returns the new value of1109$x$. This corresponds to the C statement \kbd{++$x$}: there is no prefix1110\kbd{++} operator in GP. \kbd{$x$--} does the same with $x-1$. These1111operators are not associative, i.e. \kbd{x++++} is invalid, since1112\kbd{x++} is not an lvalue.11131114\point{Priority 11}1115%1116\kbd{.}\var{member} (unary, postfix): \kbd{$x$.\var{member}} extracts1117\var{member} from structure $x$ (see~\secref{se:member}).11181119\kbd{[ ]} is the selection operator. \kbd{$x$[$i$]} returns the $i$-th1120component of vector $x$; \kbd{$x$[$i$,$j$]}, \kbd{$x$[,$j$]} and1121\kbd{$x$[$i$,]} respectively return the entry of coordinates $(i,j)$, the1122$j$-th column, and the $i$-th row of matrix $x$. If the assignment operator1123(\kbd{=}) immediately follows a sequence of selections, it assigns its right1124hand side to the selected component. E.g \kbd{x[1][1] = 0} is valid; but1125beware that \kbd{(x[1])[1] = 0} is not (because the parentheses force the1126complete evaluation of \kbd{x[1]}, and the result is not modifiable).11271128\point{Priority 10}1129%1130\kbd{'} (unary, postfix): derivative with respect to the main variable.1131If $f$ is a function (\typ{CLOSURE}), $f'$ is allowed and defines a new1132function, which will perform \idx{numerical derivation} when evaluated1133at a scalar $x$; this is defined as $(f(x+\varepsilon) - f(x-\varepsilon)) /11342\varepsilon$ for a suitably small epsilon depending on current precision.1135\bprog1136? (x^2 + y*x + y^2)' \\@com derive with respect to main variable \kbd{x}1137%1 = 2*x + y1138? SIN = cos'1139%2 = cos'1140? SIN(Pi/6) \\@com numerical derivation1141%3 = -0.50000000000000000000000000001142? cos'(Pi/6) \\@com works directly: no need for intermediate \kbd{SIN}1143%4 = -0.50000000000000000000000000001144@eprog11451146\strut\kbd{\til} (unary, postfix): vector/matrix transpose.11471148\kbd{!} (unary, postfix): factorial. $x\kbd{!}=x(x-1)\cdots 1$.11491150\kbd{!} (unary, prefix): logical \var{not}. \kbd{!$x$} returns $1$ if $x$ is1151equal to $0$ (specifically, if \kbd{gequal0($x$)==1}), and $0$ otherwise.11521153\point{Priority 9}1154%1155\kbd{\#} (unary, prefix): cardinality; \kbd{\#$x$} returns \kbd{length($x$)}.11561157\point{Priority 8}1158%1159\kbd{\pow}: powering. This operator is right associative:1160\kbd{2 \pow 3\pow 4} is understood as \kbd{2 \pow (3\pow 4)}.11611162\point{Priority 7}1163%1164\kbd{+}, \kbd{-} (unary, prefix): \kbd{-} toggles the sign of its argument,1165\kbd{+} has no effect whatsoever.11661167\point{Priority 6}1168%1169\kbd{*}: multiplication.11701171\kbd{/}: exact division (\kbd{3/2} yields $3/2$, not $1.5$).11721173\kbd{\bs}, \kbd{\%}: Euclidean quotient and remainder, i.e.~if $x =1174qy + r$, then $\kbd{x \b{ } y} = q$, $\kbd{x\%y} = r$. If $x$ and $y$1175are scalars, then $q$ is an integer and $r$ satisfies $0\le r < |y|$; if $x$1176and $y$ are polynomials, then $q$ and $r$ are polynomials such that $\deg r<1177\deg y$ and the leading terms of $r$ and $x$ have the same sign.11781179\kbd{\bs/}: rounded Euclidean quotient for integers (rounded towards1180$+\infty$ when the exact quotient would be a half-integer).11811182\kbd{<<}, \kbd{>>}: left and right binary shift. By definition,1183\kbd{x<<n}$~=~x * 2^n$ if $n>0$, and $\kbd{truncate}(x 2^{-n})$ otherwise.1184Right shift is defined by \kbd{x>>n}$~=~$\kbd{x<<(-n)}.11851186\point{Priority 5}1187%1188\kbd{+}, \kbd{-}: addition/subtraction.11891190\point{Priority 4}1191%1192\kbd{<}, \kbd{>}, \kbd{<=}, \kbd{>=}: the usual comparison operators,1193returning 1 for \kbd{true} and 0 for \kbd{false}. For instance,1194\kbd{x<=1} returns $1$ if $x\le 1$ and $0$ otherwise.11951196\kbd{<>}, \kbd{!=}: test for (exact) inequality.11971198\kbd{==}: test for (exact) equality.11991200\kbd{===}: test whether two objects are identical component-wise. This is1201stricter than \kbd{==}: for instance, the integer 0, a 0 polynomial or a1202vector with 0 entries, are all tested equal by \kbd{==}, but they are not1203identical.12041205\point{Priority 3}1206%1207\kbd{\&\&}: logical \var{and}.12081209\kbd{||}: logical (inclusive) \var{or}. Any sequence of logical1210\var{or} and \var{and} operations is evaluated from left to right,1211and aborted as soon as the final truth value is known. Thus, for instance,1212\bprog1213x == 0 || test(1/x)1214@eprog\noindent1215will never produce an error since \kbd{test(1/x)} is not even evaluated1216when the first test is true (hence the final truth value is true). Similarly1217\bprog1218type(p) == "t_INT" && isprime(p)1219@eprog\noindent1220does not evaluate \kbd{isprime(p)} if \kbd{p} is not an integer.12211222\point{Priority 2}1223%1224\kbd{=} (assignment, \var{lvalue} \kbd{=} \var{expr}). The result of1225\kbd{x~=~$y$} is the value of the expression~$y$, which is also assigned to1226the variable~\kbd{x}. This assignment operator is right-associative. This is1227\emph{not} the equality test operator; a statement like \kbd{x~=~1} is always1228true (i.e.~nonzero), and sets \kbd{x} to~1; the equality test would be1229\kbd{x == 1}. The right hand side of the assignment operator is evaluated1230before the left hand side.12311232It is crucial that the left hand-side be an \var{lvalue} there, it avoids1233ambiguities in expressions like \kbd{1 + x = 1}. The latter evaluates as1234\kbd{1 + (x = 1)}, not as \kbd{(1 + x) = 1}, even though the priority of1235\kbd{=} is lower than the priority of \kbd{+}: \kbd{1 + x} is not an lvalue.12361237If the expression cannot be parsed in a way where the left hand side is an1238lvalue, raise an error.1239\bprog1240? x + 1 = 11241*** syntax error, unexpected '=', expecting $end or ';': x+1=11242*** ^--1243@eprog\noindent1244Assignment to all variables is a deep copy: after $x = y$, modifying a1245component of $y$ will \emph{not} change $x$. To globals it is a full copy to1246the heap. Space used by local objects in local variables is released when1247they go out of scope or when the value changes in local scope. Assigning a1248value to a vector or matrix entry allocates room for that entry only (on the1249heap).12501251\leavevmode1252\kbd{\var{op}=}, where \var{op} is any binary operator1253among \kbd{+}, \kbd{-}, \kbd{*}, \kbd{\%}, \kbd{/}, \kbd{\bs}, \kbd{\bs/},1254\kbd{<<}, or1255\kbd{>>} (composed assignment \var{lvalue} \var{op}\kbd{=} \var{expr}).1256The expression \kbd{x~\var{op}=~$y$} assigns $(\kbd{x}~\var{op}~y)$1257to~\kbd{x}, and returns the new value of~\kbd{x}. The result is \emph{not}1258an \tev{lvalue}; thus1259\bprog1260(x += 2) = 31261@eprog\noindent1262is invalid. These assignment operators are right-associative:1263\bprog1264? x = 'x; x += x *= 21265%1 = 3*x1266@eprog12671268\point{Priority 1}1269\kbd{->} (function definition): \kbd{(\var{vars})->\var{expr}} returns a1270function object, of type \typ{CLOSURE}.12711272\misctitle{Remark} Use the \var{op}\kbd{=} operators as often as possible1273since they make complex assignments more legible. Compare1274\bprog1275v[i+j-1] = v[i+j-1] + 1 --> v[i+j-1]++12761277M[i,i+j] = M[i,i+j] * 2 --> M[i,i+j] *= 21278@eprog12791280\misctitle{Remark about efficiency} the operators \kbd{++}1281and \kbd{--} are usually a little more efficient than their expended1282counterpart:1283\bprog1284? N = 10^7;1285? i = 0; for(k = 1, N, i=i+1)1286time = 949 ms.1287? i = 0; for(k = 1, N, i++)1288time = 933 ms.1289@eprog\noindent On the other hand, this is not the case for the1290\var{op}\kbd{=} operators which may even be a little less efficient:1291\bprog1292? i = 0; for(k = 1, N, i=i+10)1293time = 949 ms.1294? i = 0; for(k = 1, N, i+=10)1295time = 1,064 ms.1296@eprog12971298\section{Variables and symbolic expressions}\sidx{variable}\label{se:varsymb}1299In this section we use \emph{variable} in the standard mathematical1300sense, symbols representing algebraically independent elements used to build1301rings of polynomials and power series, and explain the all-important concept1302of \emph{variable priority}. In the next \secref{se:scope}, we shall no1303longer consider only free variables, but adopt the viewpoint of computer1304programming and assign values to these symbols: (bound) variables are names1305attached to values in a given scope.13061307\subsec{Variable names}\label{se:varname} A valid name starts with a letter,1308followed by any number of keyword characters: \kbd{\_} or alphanumeric1309characters ([\kbd{A-Za-z0-9}]). As a rule, the built-in function names are1310reserved and cannot be used; see the list with \b{c}, including the constants1311\kbd{Pi}, \kbd{Euler}, \kbd{Catalan}, $\kbd{I}=\sqrt{-1}$ and $\kbd{oo} =1312\infty$. Beware in particular of \kbd{gamma}, \kbd{omega}, \kbd{theta},1313\kbd{sum} or \kbd{O}, none of which are free to use. (We shall see1314in~\secref{se:scope} how this rule can be circumvented. It \emph{is} possible1315to name a \var{lexical} variable \kbd{gamma}.)13161317GP names are case sensitive. For instance, the symbol \kbd{i} is perfectly1318safe to use, and will not be mistaken for $\kbd{I} = \sqrt{-1}$; analogously,1319\kbd{o} is not synonymous to \kbd{O}.13201321In GP you can use up to 16383 variable names (up to 65535 on 64-bit1322machines). If you ever need thousands of variables and this becomes a serious1323limitation, you should probably be using vectors instead: e.g. instead of1324variables \kbd{X1}, \kbd{X2}, \kbd{X3}, \dots, you might equally well store1325their values in \kbd{X[1]}, \kbd{X[2]}, \kbd{X[3]}, \dots13261327\subsec{Variables and polynomials}\sidx{free variable}1328The quote operator \kbd{'t} registers a new \emph{free variable} with the1329interpreter, which will be written as \kbd{t}, and evaluates to a monomial1330of degree $1$ in the said variable.13311332\misctitle{Caveat}1333For reasons of backward compatibility, there is no such thing as an1334``unbound'' (uninitialized) variable in GP. If you use a valid variable name1335in an expression, \kbd{t} say, for the first time \emph{before} assigning a1336value into it, it is interpreted as \kbd{'t} rather than raising an1337exception. One should not rely on this feature in serious programs, which1338would otherwise break if some unexpected assignment (e.g. \kbd{t = 1})1339occurs: use \kbd{'t} directly or \kbd{t = 't} first, then \kbd{t}.1340A statement like \kbd{t = 't} in effect restores \kbd{t} as a free variable.1341%1342\bprog1343? t = 't; t^2 + 11344%1 = t^2 + 11345? t = 2; t^2 + 11346%2 = 51347? %11348%3 = t^2 + 11349? eval(%1)1350%4 = 51351@eprog\noindent1352In the above, we initialize \kbd{t} to a monomial, then bind it to $2$.1353Assigning a value to a polynomial variable does not affect previous1354expressions involving it; to take into account the new variable's value, one1355must force a new evaluation, using the function \kbd{eval} (see1356\secref{se:eval}).13571358\misctitle{Caveat2}1359The use of an explicit quote operator avoids the following kind of problems:1360\bprog1361? t = 't; p = t^2 + 1; subst(p, t, 2)1362%1 = 51363? t = 2;1364? subst(p, t, 3) \\@com \kbd{t} is no longer free: it evaluates to 21365*** at top-level: subst(p,t,3)1366*** ^----1367*** variable name expected.1368? subst(p, 't, 3) \\ OK1369%3 = 101370@eprog13711372\subsec{Variable priorities, multivariate objects}\sidx{variable (priority)}\label{se:priority}1373A multivariate polynomial in PARI is just a polynomial (in one variable),1374whose coefficients are themselves polynomials, arbitrary but for the fact1375that they do not involve the main variable. (PARI currently has no sparse1376representation for polynomials, listing only nonzero monomials.) All1377computations are then done formally on the coefficients as if the1378polynomial was univariate.13791380This is not symmetrical. So if I enter \kbd{'x + 'y} in a clean session,1381what happens? This is understood as1382$$ x^1 + (y^1 + 0*y^0)*x^0 \in (\Z[y])[x] $$1383but how do we know that $x$ is ``more important'' than $y$ ? Why not $y^1 +1384x*y^0$, which is the same mathematical entity after all?13851386The answer is that variables are ordered implicitly by the interpreter:1387when a new identifier (e.g~$x$, or $y$ as above) is input, the corresponding1388variable is registered as having a strictly lower priority than any variable in1389use at this point\footnote{*}{This is not strictly true:1390the variables $x$ and $y$ are predefined, and satisfy $x > y$.1391Variables of higher priority than $x$ can be created1392using \tet{varhigher}.}%1393. To see the ordering used by \kbd{gp} at any given time, type1394\kbd{variable()}.\kbdsidx{variable}13951396Given such an ordering, multivariate polynomials are stored so that the1397variable with the highest priority is the main variable. And so on,1398recursively, until all variables are exhausted. A different storage pattern1399(which could only be obtained via \kbd{libpari} programming and low-level1400constructors) would produce an invalid object, and eventually a disaster.14011402In any case, if you are working with expressions involving several variables1403and want to have them ordered in a specific manner in the internal1404representation just described, the simplest is just to write down the1405variables one after the other under \kbd{gp} before starting any real1406computations. You may also define variables from your \tet{gprc} to have a1407consistent ordering of common variable names in all your \kbd{gp} sessions,1408e.g read in a file \kbd{variables.gp} containing1409\bprog1410'x; 'y; 'z; 't; 'a;1411@eprog\noindent There is no way to change the priority of existing variables,1412but you may always create new ones with well-defined priorities using1413\kbd{varhigher} or \kbd{varlower}.14141415\misctitle{Important note} PARI allows Euclidean division of multivariate1416polynomials, but assumes that the computation takes place in the fraction1417field of the coefficient ring (if it is not an integral domain, the result1418will a priori not make sense). This can become tricky. For instance1419assume $x$ has highest priority, then $y$:1420\bprog1421? x % y1422%1 = 01423? y % x1424%2 = y \\@com these two take place in $\Q(y)[x]$1425? x * Mod(1,y)1426%3 = Mod(1, y)*x \\@com in $(\Q(y)/y\Q(y))[x] \sim \Q[x]$1427? Mod(x,y)1428%4 = 01429@eprog1430\noindent In the last example, the division by $y$ takes place in1431$\Q(y)[x]$,1432hence the \kbd{Mod} object is a coset in $(\Q(y)[x]) / (y\Q(y)[x])$, which1433is the null ring since $y$ is invertible! So be very wary of variable1434ordering when your computations involve implicit divisions and many1435variables. This also affects functions like \tet{numerator}/\tet{denominator}1436or \tet{content}:1437\bprog1438? denominator(x / y)1439%1 = 11440? denominator(y / x)1441%2 = x1442? content(x / y)1443%3 = 1/y1444? content(y / x)1445%4 = y1446? content(2 / x)1447%5 = 21448@eprog1449\noindent Can you see why? Hint: $x/y = (1/y) * x$ is in $\Q(y)[x]$ and1450denominator is taken with respect to $\Q(y)(x)$; $y/x = (y*x^0) / x$ is in1451$\Q(y)(x)$ so $y$ is invertible in the coefficient ring. On the other hand,1452$2/x$ involves a single variable and the coefficient ring is simply $\Z$.14531454These problems arise because the variable ordering defines an \emph{implicit}1455variable with respect to which division takes place. This is1456the price to pay to allow \kbd{\%} and \kbd{/} operators on polynomials1457instead of requiring a more cumbersome \kbd{divrem($x$, $y$, \var{var})}1458(which also exists). Unfortunately, in some functions like \tet{content} and1459\tet{denominator}, there is no way to set explicitly a main variable like in1460\tet{divrem} and remove the dependence on implicit orderings. This will1461hopefully be corrected in future versions.14621463\subsec{Multivariate power series}1464Just like multivariate polynomials, power series are fundamentally1465single-variable objects. It is awkward to handle many variables at once,1466since PARI's implementation cannot handle multivariate error terms like1467$O(x^i y^j)$. (It can handle the polynomial $O(y^j) \times x^i$ which is1468a very different thing, see below.)14691470The basic assumption in our model is that if variable $x$ has higher1471priority than $y$, then $y$ does not depend on $x$: setting $y$ to a1472function of $x$ after some computations with bivariate power series does1473not make sense a priori. This is because implicit constants in1474expressions like $O(x^i)$ depend on $y$ (whereas in $O(y^j)$ they can not1475depend on $x$). For instance1476\bprog1477? O(x) * y1478%1 = O(x)1479? O(y) * x1480%2 = O(y)*x1481@eprog\noindent1482Here is a more involved example:1483\bprog1484? A = 1/x^2 + 1 + O(x); B = 1/x + 1 + O(x^3);1485? subst(z*A, z, B)1486%2 = x^-3 + x^-2 + x^-1 + 1 + O(x)1487? B * A1488%3 = x^-3 + x^-2 + x^-1 + O(1)1489? z * A1490%4 = z*x^-2 + z + O(x)1491@eprog\noindent1492The discrepancy between \kbd{\%2} and \kbd{\%3} is surprising. Why does1493\kbd{\%2} contain a spurious constant term, which cannot be1494deduced from the input? Well, we ignored the rule that forbids to1495substitute an expression involving high-priority variables1496to a low-priority variable. The result \kbd{\%4} is correct according to1497our rules since the implicit constant in $O(x)$ may depend on $z$. It is1498obviously wrong if $z$ is allowed to have negative valuation in $x$. Of1499course, the correct error term should be $O(xz)$, but this is not1500possible in PARI.15011502\section{Variables and Scope}\sidx{variable scope}\label{se:scope}1503This section is rather technical, and strives to explain potentially1504confusing concepts. Skip to the last subsection for practical advice, if the1505next discussion does not make sense to you. After learning about user1506functions, study the example in \secref{se:bewarescope} then come back.15071508\misctitle{Definitions} % rather not make it a section to allow for ??my15091510A \emph{scope} is an enclosing context where names and values are attached.1511A user's function body, the body of a loop, an individual command line, all1512define scopes; the whole program defines the \emph{global} scope. The1513argument of \tet{eval} is evaluated in the enclosing scope.15141515Variables are bound to values within a given scope. This is traditionally1516implemented in two different ways:15171518\item\sidx{lexical scoping} lexical (or static) scoping: the binding makes1519sense within a given block of program text. The value is private to the block1520and may not be accessed from outside. Where to find the value is determined1521at compile time.15221523\item\sidx{dynamic scoping} dynamic scoping: introducing a local variable,1524say \kbd{x}, pushes a new value on a stack attached to the name \kbd{x}1525(possibly empty at this point), which is popped out when the control flow1526leaves the scope. Evaluating \kbd{x} in any context, possibly outside of the1527given block, always yields the top value on this dynamic stack.15281529GP implements both lexical and dynamic scoping, using the keywords%1530\footnote{*}{The names are borrowed from the \tet{Perl} scripting language.}1531\tet{my} (lexical) and \tet{local} (dynamic):1532\bprog1533x = 0;1534f() = x1535g() = my(x = 1); f()1536h() = local(x = 1); f()1537@eprog\noindent1538The function \kbd{g} returns 0 since the global \kbd{x} binding1539is unaffected by the introduction of a private variable of the same name in1540\kbd{g}. On the other hand, \kbd{h} returns 1; when it calls \kbd{f()}, the1541binding stack for the \kbd{x} identifier contains two items: the global1542binding to 0, and the binding to 1 introduced in \kbd{h}, which is still1543present on the stack since the control flow has not left \kbd{h} yet.15441545The rule mentionned in the previous section about built-in function names1546being reserved does \emph{not} apply to lexically scoped variables. Those may1547temporarily shadow an existing function name:1548\bprog1549my(gamma = 0) ; ...1550@eprog1551Without the \kbd{my}, this would be invalid since \kbd{gamma} is the $\Gamma$1552function.15531554\subsec{Scoping rules}15551556Named parameters in a function definition, as well as all loop1557indices\footnote{**}{1558More generally, in all iterative constructs which use a variable name1559(\kbd{for}, \kbd{prod}, \kbd{sum}, \kbd{vector}, \kbd{matrix},1560\kbd{plot}, etc.) the given variable is lexically scoped to the construct's1561body.},1562have lexical scope within the function body and the loop body respectively.1563\bprog1564p = 0;1565forprime (p = 2, 11, print(p)); p \\ prints 0 at the end15661567x = 0;1568f(x) = x++;1569f(1) \\ returns 2, and leave global x unaffected (= 0)1570@eprog\noindent1571If you exit the loop prematurely, e.g.~using the \kbd{break} statement, you1572must save the loop index in another variable since its value prior the loop1573will be restored upon exit. For instance1574\bprog1575for(i = 1, n,1576if (ok(i), break);1577);1578if (i > n, return(failure));1579@eprog\noindent1580is incorrect, since the value of $i$ tested by the $(i > n)$ is quite1581unrelated to the loop index. One ugly workaround is1582\bprog1583for(i = 1, n,1584if (ok(i), isave = i; break);1585);1586if (isave > n, return(failure));1587@eprog\noindent1588But it is usually more natural to wrap the loop in a user function1589and use \kbd{return} instead of \kbd{break}:1590\bprog1591try() =1592{1593for(i = 1, n,1594if (ok(i), return (i));1595);15960 \\ failure1597}1598@eprog15991600A list of variables can be lexically or dynamically scoped (to the block1601between the declaration and the end of the innermost enclosing scope) using a1602\kbd{my} or \kbd{local} declaration:1603\bprog1604for (i = 1, 10,1605my(x, y, z, i2 = i^2); \\ temps needed within the loop body1606...1607)1608@eprog\noindent1609Note how the declaration can include (optional) initial values, \kbd{i2 =1610i\pow 2} in the above. Variables for which no explicit default value is given1611in the declaration are initialized to $0$. It would be more natural to1612initialize them to free variables, but this would break backward1613compatibility. To obtain this behavior, you may explicitly use the quoting1614operator:1615\bprog1616my(x = 'x, y = 'y, z = 'z);1617@eprog\noindent1618A more complicated example:1619\bprog1620for (i = 1, 3,1621print("main loop");1622my(x = i); \\ local to the outermost loop1623for (j = 1, 3,1624my (y = x^2); \\ local to the innermost loop1625print (y + y^2);1626x++;1627)1628)1629@eprog\noindent1630When we leave the loops, the values of \kbd{x}, \kbd{y}, \kbd{i}, \kbd{j}1631are the same as before they were started.16321633Note that \tet{eval} is evaluated in the given scope, and can access values1634of lexical variables:1635\bprog1636? x = 1;1637? my(x = 0); eval("x")1638%2 = 0 \\@com we see the local \kbd{x} scoped to this command line, not the global one1639@eprog16401641Variables dynamically scoped using \kbd{local} should more appropriately be1642called \emph{temporary values} since they are in fact local to the function1643declaring them \emph{and} any subroutine called from within. In practice, you1644almost certainly want true private variables, hence should use almost1645exclusively \kbd{my}.16461647We strongly recommended to explicitly scope (lexically) all variables to the1648smallest possible block. Should you forget this, in expressions involving such1649``rogue'' variables, the value used will be the one which happens to be on1650top of the value stack at the time of the call; which depends on the whole1651calling context in a nontrivial way. This is in general \emph{not} what you1652want.16531654\section{User defined functions}\sidx{user defined functions}1655\label{se:user_defined}16561657User-defined functions are ordinary GP objects, bound to variables just like1658any other object. Those variables are subject to scoping rules as any other:1659while you can define all your functions in global scope, it is usually1660possible and cleaner to lexically scope your private helper functions to the1661block of text where they will be needed.16621663Whenever gp meets a construction of the form \kbd{expr(\var{argument list})}1664and the expression \kbd{expr} evaluates to a function (an object of type1665\typ{CLOSURE}), the function is called with the proper arguments. For1666instance, constructions like \kbd{funcs[i](x)} are perfectly valid,1667assuming \kbd{funcs} is an array of functions.16681669As regards argument passing conventions, GP functions support both16701671\item \idx{call by value}: the function operates on a copy of a variable,1672changes made to the argument in the function do not affect the original1673variable;16741675\item and \idx{call by reference}: the function receives a reference to the1676variable and original data is affected.16771678\subsec{Defining a function}\label{se:userfundef}16791680A user function is defined as follows:16811682\kbd{(\var{list of formal variables}) -> \var{seq}}.16831684\noindent The list of formal variables is a comma-separated list of1685\emph{distinct} variable names and allowed to be empty. It there is a single1686formal variable, the parentheses are optional. This list corresponds to the1687list of parameters you will supply to your function when calling it. By1688default, GP functions use call by value to pass arguments; a variable1689name may be prefixed by a tilde \kbd{\til} to use instead a call by1690reference.16911692In most cases you want to assign a function to a variable immediately, as in1693\bprog1694R = (x,y) -> sqrt( x^2+y^2 );1695sq = x -> x^2; \\@com or equivalently \kbd{(x) -> x\pow2}1696@eprog\noindent1697but it is quite possible to define short-lived anonymous functions.1698The trailing semicolon is not part of the definition, but as usual prevents1699\kbd{gp} from printing the result of the evaluation, i.e. the function1700object. The construction17011702\kbd{f(\var{list of formal variables}) = \var{seq}}17031704\noindent is available as an alias for17051706\kbd{f = (\var{list of formal variables}) -> \var{seq}}17071708\noindent Using that syntax, it is not possible to define anonymous functions1709(obviously), and the above two examples become:1710\bprog1711R(x,y) = sqrt( x^2+y^2 );1712sq(x) = x^2;1713@eprog\noindent1714The semicolon serves the same purpose as above: preventing the printing1715of the resulting function object; compare1716\bprog1717? sq(x) = x^2; \\@com no output1718? sq(x) = x^2 \\@com print the result: a function object1719%2 = (x)->x^21720@eprog\noindent Of course, the sequence \var{seq} can be arbitrarily1721complicated, in which case it will look better written on consecutive lines,1722with properly scoped variables:1723\bprog1724{1725f(x0, x1, @dots) =1726my(t0, t1, @dots); \\@com variables lexically scoped to the function body1727@dots1728}1729@eprog \noindent Note that the following variant would also work:1730\bprog1731f(x0, x1, @dots) =1732{1733my(t0, t1, @dots); \\@com variables lexically scoped to the function body1734@dots1735}1736@eprog \noindent1737(the first newline is disregarded due to the preceding \kbd{=} sign, and the1738others because of the enclosing braces). The \tet{my} statements can actually1739occur anywhere within the function body, scoping the variables to more1740restricted blocks than the whole function body.17411742Formal parameters are lexically scoped to the function body. It is not1743allowed to use the same variable name for different parameters of your1744function:1745\bprog1746? f(x,x) = 11747*** variable declared twice: f(x,x)=11748*** ^----1749@eprog17501751By default, arguments are passed by value, not as variables: modifying a1752function's argument in the function body is allowed, but does not modify its1753value in the calling scope. In fact, a \emph{copy} of the actual parameter is1754assigned to the formal parameter when the function is called. (This is not1755litterally true: a form of copy-on-write is implemented so an object is not1756duplicated unless modified in the function.) If an argument is prefixed by a1757tilde \kbd{\til} in the function declaration \emph{and} the call, it is1758passed by reference. (If either the declaration or the call is missing1759a tilde, we revert to a call by value.)17601761\bprog1762? x = [1];1763? f(v) = v[1]++;1764? F(~v) = v[1]++;17651766? f(x)1767%4 = 21768? x \\ unchanged1769%5 = [1]1770? F(~x)1771%6 = 21772? x \\ incremented1773%7 = [2]1774? F(x) \\ forgot the ~: call by value1775%8 = 31776? x \\ => contents of x did not change1777%9 = [2]1778? f(~x) \\ adding a ~ in call, missing in declaration1779%10 = 31780? x \\ => call by value1781%11 = [2]1782@eprog1783\misctitle{Caveat} In GP, a call by reference means that the function1784accesses the value and may change the original variable content, but only if1785it is a container type (a vector, list or matrice), as shown above with the1786vector $x$. It will not alter its value in other cases !1787\bprog1788? v = 1 \\ not a container1789? F(~v) = v++1790? F(~v)1791%3 = 21792? v \\ components of v could be altered, not v itself1793%4 = 11794@eprog17951796\misctitle{Functions taking an unlimited number of arguments}17971798A function taking an unlimited number of arguments is called \emph{variadic}.1799To create such a function, use the syntax18001801\kbd{(\var{list of formal variables}, \var{var}[..]) -> \var{seq}}18021803\noindent The parameter \var{var} is replaced by a vector containing all the1804remaining arguments. The name may not be prefixed by a tilde to (absurdly)1805indicate a call by reference.18061807\bprog1808? f(c[..]) = sum(i=1,#c,c[i]);1809? f(1,2,3)1810%1 = 61811? sep(s,v[..]) = for(i=1,#v-1,print1(v[i],s)); if (#v, print(v[#v]));1812? sep(":", 1, 2, 3)18131:2:31814@eprog18151816\misctitle{Finishing touch}1817You can add a specific help message for your function using \kbd{addhelp},1818but the online help system already handles it. By default \kbd{?\var{name}}1819will print the definition of the function \var{name}: the list of arguments,1820as well as their default values, the text of \var{seq} as you input it.1821Just as \b{c} prints the list of all built-in commands, \b{u} outputs the1822list of all user-defined functions.18231824\misctitle{Backward compatibility (lexical scope)} Lexically scoped1825variables were introduced in version~2.4.2. Before that, the formal1826parameters were dynamically scoped. If your script depends on this behavior,1827you may use the following trick: replace the initial \kbd{f(x) =} \ by1828\bprog1829f(x_orig) = local(x = x_orig)1830@eprog1831\misctitle{Backward compatibility (disjoint namespaces)} Before version18322.4.2, variables and functions lived in disjoint namespaces and it was not1833possible to have a variable and a function share the same name. Hence the1834need for a \kbd{kill} function allowing to reuse symbols. This is no longer1835the case.18361837There is now no distinction between variable and function names: we1838have PARI objects (functions of type \typ{CLOSURE}, or more mundane1839mathematical entities, like \typ{INT}, etc.) and variables bound to them.1840There is nothing wrong with the following sequence of assignments:1841\bprog1842? f = 1 \\@com assigns the integer 1 to \kbd{f}1843%1 = 1;1844? f() = 1 \\@com a function with a constant value1845%2 = ()->11846? f = x^2 \\@com \kbd{f} now holds a polynomial1847%3 = x^21848? f(x) = x^2 \\@com \dots and now a polynomial function1849%4 = (x)->x^21850? g(fun) = fun(Pi);\\@com a function taking a function as argument1851? g(cos)1852%6 = -1.00000000000000000000000000018531854@eprog\noindent1855Previously used names can be recycled as above: you are just redefining the1856variable. The previous definition is lost of course.18571858\misctitle{Important technical note} Built-in functions are a special case1859since they are read-only (you cannot overwrite their default meaning),1860and they use features not available to user functions, in particular pointer1861arguments. In the present version \vers{}, it is possible to assign a built-in1862function to a variable, or to use a built-in function name to create an1863anonymous function, but some special argument combinations may not be1864available:1865\bprog1866? issquare(9, &e)1867%1 = 11868? e1869%2 = 31870? g = issquare;1871? g(9)1872%4 = 11873? g(9, &e) \\@com pointers are not implemented for user functions1874*** unexpected &: g(9,&e)1875*** ^---1876@eprog18771878\subsec{Function call, Default arguments}18791880You may now call your function, as in \kbd{f(1,2)}, supplying values1881for the formal variables. The number of parameters actually supplied may be1882\emph{less} than the number of formal variables in the function definition.1883An uninitialized formal variable is given an implicit default value of (the1884integer)~0, i.e. after the definition1885\bprog1886f(x, y) = ...1887@eprog\noindent1888you may call \kbd{f(1, 2)}, supplying values for the two formal1889parameters, or for example1890\settabs\+\indent&xxxxxxxxx& equivalent to xxxx &\cr1891\+& \kbd{f(2)} & equivalent to &\kbd{f(2,0)},\cr1892\+& \kbd{f()} & & \kbd{f(0,0)},\cr1893\+& \kbd{f(,3)} & &\kbd{f(0,3)}. (``Empty argument'' trick)\cr1894\noindent This \emph{implicit} default value of $0$, is actually deprecated1895and setting1896\bprog1897default(strictargs, 1)1898@eprog\noindent allows to disable it (see \secref{se:def,strictargs}).\kbdsidx{strictargs}18991900The recommended practice is to \emph{explicitly} set a default value:1901in the function definition, you can append \kbd{=}\var{expr} to a formal1902parameter, to give that variable a default value. The expression1903gets evaluated the moment the function is called, and may involve the1904preceding function parameters: a default value for $x_i$ may involve $x_j$1905for $j < i$. For instance, after1906\bprog1907f(x = 1, y = 2, z = y+1) = ....1908@eprog\noindent1909typing in \kbd{f(3,4)} would give you \kbd{f(3,4,5)}. In the rare case when1910you want to set some far away argument, and leave the defaults in between as1911they stand, use the ``empty argument'' trick: \kbd{f(6,,1)} would yield1912\kbd{f(6,2,1)}. Of course, \kbd{f()} by itself yields \kbd{f(1,2,3)} as was1913to be expected.19141915In short, the argument list is filled with user supplied values, in1916order. A comma or closing parenthesis, where a value should have been,1917signals we must use a default value. When no input arguments are left, the1918defaults are used instead to fill in remaining formal parameters.1919A final example:1920\bprog1921f(x, y=2, z=3) = print(x, ":", y, ":", z);1922@eprog1923\noindent defines a function which prints its arguments (at most three of1924them), separated by colons.1925\bprog1926? f(6,7)19276:7:31928? f(,5)19290:5:31930? f()19310:2:31932@eprog\noindent If \kbd{strictargs} is set (recommended), $x$ is now a1933mandatory argument, and the above becomes:1934\bprog1935? default(strictargs,1)1936? f(6,7)19376:7:31938? f(,5)1939*** at top-level: f(,5)1940*** ^-----1941*** in function f: x,y=2,z=31942*** ^---------1943*** missing mandatory argument 'x' in user function.1944@eprog19451946\misctitle{Example} We conclude with an amusing example, intended to1947illustrate both user-defined functions and the power of the \kbd{sumalt}1948function. Although the \idx{Riemann zeta-function} is included (as1949\kbd{zeta}) among the standard functions, let us assume that we want to check1950other implementations. Since we are highly interested in the critical strip,1951we use the classical formula1952$$ (2^{1-s} - 1)\zeta(s) = \sum_{n\geq 1} (-1)^n n^{-s},1953\qquad\Re s > 0.$$1954The implementation is obvious:\sidx{zeta function}1955\bprog1956ZETA(s) = sumalt(n=1, (-1)^n*n^(-s)) / (2^(1-s) - 1)1957@eprog1958\noindent1959Note that \kbd{n} is automatically lexically scoped to the \kbd{sumalt}1960``loop'', so that it is unnecessary to add a \kbd{my(n)} declaration to the1961function body. Surprisingly, this gives very good accuracy in a larger region1962than expected:1963\bprog1964? check = z -> ZETA(z) / zeta(z);1965? check(2)1966%1 = 1.0000000000000000000000000001967? check(200)1968%2 = 1.0000000000000000000000000001969? check(0)1970%3 = 0.99999999999999999999999999941971? check(-5)1972%4 = 1.000000000000000075492665571973? check(-11)1974%5 = 0.99997526410478249026608477451975? check(1/2+14.134*I) \\@com very close to a nontrivial zero1976%6 = 1.000000000000000000003747432 + 7.62329066 E-21*I1977? check(-1+10*I)1978%7 = 1.000000000000000000000002511 + 2.989950968 E-24*I1979@eprog\noindent Now wait a minute; not only are we summing a series which is1980certainly no longer alternating (it has complex coefficients), but we are1981also way outside of the region of convergence, and still get decent results! No1982programming mistake this time: \kbd{sumalt} is a1983``magic'' function\footnote{*}{\kbd{sumalt} is heuristic, but its use can be1984rigorously justified for a given function, in particular our $\zeta(s)$1985formula. Indeed, Peter Borwein (\emph{An efficient algorithm for the Riemann1986zeta function}, CMS Conf.~Proc.~{\bf 27} (2000), pp.~29--34) proved that the1987formula used in \kbd{sumalt} with $n$ terms computes $(1-2^{1-s})\zeta(s)$1988with a relative error of the order of $(3+\sqrt{8})^{-n}|\Gamma(s)|^{-1}$.},1989providing very good convergence acceleration; in effect, we are computing1990the analytic continuation of our original function. To convince ourselves1991that \kbd{sumalt} is a nontrivial implementation, let us try a simpler1992example:1993\bprog1994? sum(n=1, 10^7, (-1)^n/n, 0.) / (-log(2)) \\@com approximates the well-known formula1995time = 7,417 ms.1996%1 = 0.99999992786525156228934054571997? sumalt(n=1, (-1)^n/n) / (-log(2)) \\@com accurate and fast1998time = 0 ms.1999%2 = 1.0000000000000000000000000002000@eprog\noindent No, we are not using a powerful simplification tool here,2001only numerical computations. Remember, PARI is not a computer algebra system!200220032004\subsec{Beware scopes}\label{se:bewarescope}2005Be extra careful with the scopes of variables. What is wrong with the2006following definition?2007\bprog2008FirstPrimeDiv(x) =2009{ my(p);2010forprime(p=2, x, if (x%p == 0, break));2011p2012}2013? FirstPrimeDiv(10)2014%1 = 02015@eprog\noindent \misctitle{Hint} The function body is equivalent to2016\bprog2017{ my(newp = 0);2018forprime(p=2, x, if (x%p == 0, break));2019newp2020}2021@eprog\noindent2022\misctitle{Detailed explanation} The index \kbd{p} in the \kbd{forprime}2023loop is lexically scoped to the loop and is not visible to the outside world.2024Hence, it will not survive the \kbd{break} statement. More precisely, at this2025point the loop index is restored to its preceding value. The initial2026\kbd{my(p)}, although well-meant, adds to the confusion: it indeed scopes2027\kbd{p} to the function body, with initial value $0$, but the \kbd{forprime}2028loop introduces \emph{another} variable, unfortunately also called \kbd{p},2029scoped to the loop body, which shadows the one we wanted. So we always return2030$0$, since the value of the \kbd{p} scoped to the function body never changes2031and is initially $0$.20322033To sum up, the routine returns the \kbd{p} declared local to2034it, not the one which was local to \kbd{forprime} and ran through consecutive2035prime numbers. Here is a corrected version:2036\bprog2037? FirstPrimeDiv(x) = forprime(p=2, x, if (x%p == 0, return(p)))2038@eprog20392040\subsec{Recursive functions} Recursive functions\sidx{recursion} can easily2041be written as long as one pays proper attention to variable scope. Here is an2042example, used to retrieve the coefficient array of a multivariate polynomial2043(a nontrivial task due to PARI's unsophisticated representation for those2044objects): \sidx{multivariate polynomial}2045\bprog2046coeffs(P, nbvar) =2047{2048if (type(P) != "t_POL",2049for (i=1, nbvar, P = [P]);2050return (P)2051);2052vector(poldegree(P)+1, i, coeffs(polcoef(P, i-1), nbvar-1))2053}2054@eprog20552056\noindent If $P$ is a polynomial in $k$ variables, show that after the2057assignment {\tt v = coeffs(P,k)}, the coefficient of $x_1^{n_1}\dots2058x_k^{n_k}$ in P is given by {\tt v[$n_1$+1][\dots][$n_k$+1]}.20592060When the operating system allows querying the maximum size of the process2061stack, we automatically limit the \idx{recursion depth}: \sidx{deep recursion}2062\bprog2063? dive(n) = dive(n+1)2064? dive(0);2065*** [...] at: dive(n+1)2066*** ^---------2067*** in function dive: dive(n+1)2068*** ^---------2069\\@com (last 2 lines repeated 19 times)2070*** deep recursion.2071@eprog\noindent2072All Unix variants support this mechanism and the recursion limit2073may be different from one machine to the next; other systems may crash on2074deep recursion. There is no way to increase the limit from within \kbd{gp}.2075On a Unix system, you may increase it before launching \kbd{gp} with2076\tet{ulimit} or \tet{limit}, depending on your shell, and raise the process2077available stack space (increase \tet{stacksize}).20782079\subsec{Function which take functions as parameters} This is done as follows:2080\bprog2081? calc(f, x) = f(x)2082? calc(sin, Pi)2083%2 = -5.04870979 E-292084? g(x) = x^2;2085? calc(g, 3)2086%4 = 92087@eprog2088\noindent If we do not need \kbd{g} elsewhere, we should use an anonymous2089function here, \kbd{calc(x->x\pow 2, 3)}. Here is a variation:2090\bprog2091? funs = [cos, sin, tan, x->x^3+1]; \\@com an array of functions2092? call(i, x) = funs[i](x)2093@eprog\noindent2094evaluates the appropriate function on argument \kbd{x},2095provided $1\leq i\leq 4$. Finally, a more useful example:2096\bprog2097APPLY(f, v) = vector(#v, i, f(v[i]))2098@eprog\noindent2099applies the function \kbd{f} to every element in the vector \kbd{v}.2100(The built-in function \kbd{apply} is more powerful since it also applies to2101lists and matrices.)21022103\subsec{Defining functions within a function}2104Defining a single function is easy:2105\bprog2106init(x) = (add = y -> x+y);2107@eprog\noindent Basically, we are defining a global variable \kbd{add}2108whose value is the function \kbd{y->x+y}. The parentheses were added for2109clarity and are not mandatory.2110\bprog2111? init(5);2112? add(2)2113%2 = 72114@eprog\noindent2115A more refined approach is to2116avoid global variables and \emph{return} the function:2117\bprog2118init(x) = y -> x+y2119add = init(5)2120@eprog\noindent Then \kbd{add(2)} still returns 7, as expected! Of course,2121if \kbd{add} is in global scope, there is no gain, but we can2122lexically scope it to the place where it is useful:2123\bprog2124my ( add = init(5) );2125@eprog21262127How about multiple functions then? We can use the last idea and return a2128vector of functions, but if we insist on global variables?2129The first idea2130\bprog2131init(x) = add(y) = x+y; mul(y) = x*y;2132@eprog2133\noindent does not work since in the construction \kbd{f() = }\var{seq}, the2134function body contains everything until the end of the expression. Hence2135executing \kbd{init} defines the wrong function \kbd{add} (itself defining2136a function \kbd{mul}). The way out is to2137use parentheses for grouping, so that enclosed subexpressions will be2138evaluated independently:2139\bprog2140? init(x) = ( add(y) = x+y ); ( mul(y) = x*y );2141? init(5);2142? add(2)2143%3 = 72144? mul(3)2145%4 = 152146@eprog\noindent This defines two global functions which have access to the2147lexical variables private to \kbd{init}! The following would work in exactly2148the same way:2149\bprog2150? init5() = my(x = 5); ( add(y) = x+y ); ( mul(y) = x*y );2151@eprog21522153\subsec{Closures as Objects} Contrary to what you might think after the2154preceding examples, GP's closures may not be used to simulate true2155``objects'', with private and public parts and methods to access and2156manipulate them. In fact, closures indeed incorporate an existing context2157(they may access lexical variables that existed at the time of their2158definition), but then may not change it. More precisely, they access a copy,2159which they are welcome to change, but a further function call still accesses2160the original context, as it existed at the time the function was defined:2161\bprog2162init() =2163{ my(count = 0);2164(inc()=count++);2165(dec()=count--);2166}2167? init();2168? inc()2169%1 = 12170? inc()2171%2 = 12172? dec()2173%3 = -12174? dec()2175%4 = -12176@eprog21772178\section{Member functions}\sidx{member functions} \label{se:member}21792180Member functions use the `dot' notation to retrieve information from2181complicated structures. The built-in structures are \tev{bid}, \tev{ell},2182\tev{galois}, \tev{ff}, \tev{nf}, \tev{bnf}, \tev{bnr} and \tev{prid}, which2183will be described at length in Chapter~3. The syntax \kbd{structure.member}2184is taken to mean: retrieve \kbd{member} from \kbd{structure},2185e.g.~\kbd{E.j} returns the $j$-invariant of the elliptic curve \kbd{E},2186or outputs an error message if \kbd{E} is not a proper \tev{ell} structure.2187To define your own member functions, use the syntax21882189\ \kbd{\var{var}.\var{member} = \var{seq}},21902191\noindent where the formal variable \var{var} is scoped to the function2192body \var{seq}. This is of course reminiscent of a user function with a2193single formal variable \var{var}. For instance, the current implementation of2194the \kbd{ell} type is a vector, the $j$-invariant being the thirteenth2195component. It could be implemented as21962197\bprog2198x.j =2199{2200if (type(x) != "t_VEC" || #x < 14, error("not an elliptic curve: " x));2201x[13]2202}2203@eprog\noindent As for user functions, you can redefine your member functions2204simply by typing new definitions. On the other hand, as a safety measure, you2205cannot redefine the built-in member functions, so attempting to redefine2206\kbd{x.j} as above would in fact produce an error; you would have to call it2207e.g.~\kbd{x.myj} in order for \kbd{gp} to accept it.22082209Member functions use call by reference to pass arguments, your function2210may modify in place the contents of a variable (of container type).22112212\misctitle{Rationale} In most cases, member functions are simple accessors2213of the form2214\bprog2215x.a = x[1];2216x.b = x[2];2217x.c = x[3];2218@eprog\noindent2219where \kbd{x} is a vector containing relevant data. There are at least2220three alternative approaches to the above member functions: 1) hardcode2221\kbd{x[1]}, etc. in the program text, 2) define constant global variables2222\kbd{AINDEX = 1}, \kbd{BINDEX = 2} and hardcode \kbd{x[AINDEX]}, 3)2223user functions \kbd{a(x) = x[1]} and so on.22242225Even if 2) improves on 1), these solutions are neither elegant nor flexible,2226and they scale badly. 3) is a genuine possibility, but the main advantage of2227member functions is that their namespace is independent from the variables2228(and functions) namespace, hence we can use very short identifiers without2229risk. The $j$-invariant is a good example: it would clearly not be a good2230idea to define \kbd{j(E) = E[13]}, because clashes with loop indices are2231likely.22322233Beware that there is no guarantee that a built-in member function \emph{is}2234a simple accessor and it could involve a computation. Thus you should2235not use them on a constant object in tight loops: store them in a variable2236before the loop.22372238\misctitle{Note} Typing \b{um} will output all user-defined member functions.22392240\misctitle{Member function names} A valid name starts with a letter followed2241by any number of keyword characters: \kbd{\_} or alphanumeric characters2242([\kbd{A-Za-z0-9}]). The built-in member function names are reserved and2243cannot be used (see the list with \kbd{?.}). Finally, names starting with2244\kbd{e} or \kbd{E} followed by a digit are forbidden, due to a clash with2245the floating point exponent notation: we understand \kbd{1.e2} as2246$100.000\dots$, not as extracting member \kbd{e2} of object \kbd{1}.22472248\section{Strings and Keywords}\sidx{string}\sidx{keyword}2249\label{se:strings}22502251\subsec{Strings} GP variables can hold values of type character string2252(internal type \typ{STR}). This section describes how they are actually used,2253as well as some convenient tricks (automatic concatenation and expansion,2254keywords) valid in string context.22552256As explained above, the general way to input a string is to enclose2257characters between quotes~\kbd{"}. This is the only input construct where2258whitespace characters are significant: the string will contain the exact2259number of spaces you typed in. Besides, you can ``escape'' characters by2260putting a \kbd{\bs} just before them; the translation is as follows2261\bprog2262\e: <Escape>2263\n: <Newline>2264\t: <Tab>2265@eprog2266For any other character $x$, \b{$x$} is expanded to $x$. In particular, the2267only way to put a \kbd{"} into a string is to escape it. Thus, for2268instance, \kbd{"\bs"a\bs""} would produce the string whose content is2269``a''. This is definitely \emph{not} the same thing as typing \kbd{"a"},2270whose content is merely the one-letter string a.22712272You can concatenate two strings using the \tet{concat} function. If either2273argument is a string, the other is automatically converted to a string if2274necessary (it will be evaluated first).22752276\bprog2277? concat("ex", 1+1)2278%1 = "ex2"2279? a = 2; b = "ex"; concat(b, a)2280%2 = "ex2"2281? concat(a, b)2282%3 = "2ex"2283@eprog22842285Some functions expect strings for some of their arguments: \tet{print} would2286be an obvious example, \tet{Str} is a less obvious but useful one (see the2287end of this section for a complete list). While typing in such an argument,2288you will be said to be in \tev{string context}. The rest of this section is2289devoted to special syntactical tricks which can be used with such arguments2290(and only here; you will get an error message if you try these outside of2291string context):22922293\item Writing two strings alongside one another will just concatenate2294them, producing a longer string. Thus it is equivalent to type in2295\kbd{"a " "b"} or \kbd{"a b"}. A little tricky point in the first expression:2296the first whitespace is enclosed between quotes, and so is part of a string;2297while the second (before the \kbd{"b"}) is completely optional and \kbd{gp}2298actually suppresses it, as it would with any number of whitespace characters2299at this point (i.e.~outside of any string).23002301\item If you insert any expression when a string is expected, it gets2302``expanded'': it is evaluated as a standard GP expression, and the final2303result (as would have been printed if you had typed it by itself) is then2304converted to a string, as if you had typed it directly. For instance \kbd{"a"23051+1 "b"} is equivalent to \kbd{"a2b"}: three strings get created, the middle2306one being the expansion of \kbd{1+1}, and these are then concatenated2307according to the rule described above. Another tricky point here: assume you2308did not assign a value to \kbd{aaa} in a GP expression before. Then typing2309\kbd{aaa} by itself in a string context will actually produce the correct2310output (i.e.~the string whose content is aaa), but in a fortuitous way. This2311\kbd{aaa} gets expanded to the monomial of degree one in the variable2312\kbd{aaa}, which is of course printed as \kbd{aaa}, and thus will expand to2313the three letters you were expecting.23142315\misctitle{Warning} Expression involving strings are not handled in a2316special way; even in string context, the largest possible expression is2317evaluated, hence \kbd{print("a"[1])} is incorrect since \kbd{"a"} is not an2318object whose first component can be extracted. On the other hand2319\kbd{print("a", [1])} is correct (two distinct argument, each converted to a2320string), and so is \kbd{print("a" 1)} (since \kbd{"a"1} is not a valid2321expression, only \kbd{"a"} gets expanded, then \kbd{1}, and the result is2322concatenated as explained above).23232324\subsec{Keywords} Since there are cases where expansion is not desirable, we2325now distinguish between ``Keywords'' and ``Strings''. String is what has been2326described so far. Keywords are special relatives of Strings which are2327automatically assumed to be quoted, whether you actually type in the quotes2328or not. Thus expansion is never performed on them. They get concatenated,2329though. The analyzer supplies automatically the quotes you have ``forgotten''2330and treats Keywords just as normal strings otherwise. For instance, if you2331type \kbd{"a"b+b} in Keyword context, you will get the string whose contents2332are ab+b. In String context, on the other hand, you would get a2\kbd{*}b.23332334All GP functions have prototypes (described in Chapter~3 below) which2335specify the types of arguments they expect: either generic PARI objects2336(GEN), or strings, or keywords, or unevaluated expression sequences. In the2337keyword case, only a very small set of words will actually be meaningful2338(the \kbd{default} function is a prominent example).23392340\misctitle{Reference} The arguments of the following functions are processed2341in string context:23422343\settabs\+\indent&\cr2344\+&\tet{Str}\cr2345\+&\tet{addhelp} (second argument)\cr2346\+&\tet{default} (second argument)\cr2347\+&\tet{error}\cr2348\+&\tet{extern}\cr2349\+&\tet{plotstring} (second argument)\cr2350\+&\tet{plotterm} (first argument)\cr2351\+&\tet{read} and \tet{readvec}\cr2352\+&\tet{system}\cr2353\+&all the \tet{print}\var{xxx} functions\cr2354\+&all the \tet{write}\var{xxx} functions\cr23552356\noindent The arguments of the following functions are processed as keywords:23572358\+&\tet{alias}\cr2359\+&\tet{default} (first argument)\cr2360\+&\tet{install} (all arguments but the last)\cr2361\+&\tet{trap} (first argument)\cr2362\+&\tet{whatnow}\cr23632364\subsec{Useful example} The function \kbd{Str} converts its arguments into2365strings and concatenate them. Coupled with \tet{eval}, it is very powerful.2366The following example creates generic matrices\sidx{generic2367matrix}\sidx{matrix}:2368\bprog2369? genmat(u,v,s="x") = matrix(u,v,i,j, eval( Str(s,i,j) ))2370? genmat(2,3) + genmat(2,3,"m")2371%1 =2372[x11 + m11 x12 + m12 x13 + m13]2373[x21 + m21 x22 + m22 x23 + m23]2374@eprog23752376\section{Errors and error recovery}23772378\subsec{Errors} Your input program is first compiled to a more efficient2379bytecode; then the latter is evaluated, calling appropriate functions from2380the PARI library. Accordingly, there are two kind of errors: syntax errors2381produced by the compiler, and runtime errors produced by the PARI library2382either by the evaluator itself, or in a mathematical function.2383Both kinds are fatal to your computation: \kbd{gp} will report the error2384and perform some cleanup (restore variables modified while evaluating the2385erroneous command, close open files, reclaim unused memory, etc.).23862387At this point, the default is to return to the usual prompt, but if the2388\kbd{recover} option (\secref{se:def,recover}) is off then \kbd{gp} exits2389immediately. This can be useful for batch-mode operation to make untrapped2390errors fatal.23912392When reporting a \emph{syntax error}, \kbd{gp} gives meaningful2393context by copying (part of) the expression it was trying to compile,2394indicating where the error occurred with a caret \kbd{\pow-}, as in2395\bprog2396? factor()2397*** too few arguments: factor()2398*** ^-2399? 1+2400*** syntax error, unexpected $end: 1+2401*** ^-2402@eprog\noindent2403possibly enlarged to a full arrow given enough trailing context2404\bprog2405? if (isprime(1+, do_something())2406*** syntax error, unexpected ',': if(isprime(1+,do_something()))2407*** ^----------------2408@eprog\noindent2409These error messages may be mysterious, because \kbd{gp} cannot guess what2410you were trying to do, and the error may occur once \kbd{gp} has been2411sidetracked. The first error is straightforward: \kbd{factor} has one2412mandatory argument, which is missing.24132414The other two are simple typos involving an ill-formed addition2415\kbd{1 + } missing its second operand. The error messages differ2416because the parsing context is slightly different: in the first2417case we reach the end of input (\kbd{\$end}) while still expecting a token,2418and in the second one, we received an unexpected token (the comma).24192420Here is a more complicated one:2421\bprog2422? factor(x2423*** syntax error, unexpected $end, expecting )-> or ',' or ')': factor(x2424*** ^-2425@eprog\noindent2426The error is a missing parenthesis, but from \kbd{gp}'s point of view,2427you might as well have intended to give further arguments to \kbd{factor}2428(this is possible and useful, see the description of the function). In fact2429\kbd{gp} expected either a closing parenthesis, or a second argument2430separated from the first by a comma. And this is essentially what the error2431message says: we reached the end of the input (\kbd{\$end}) while expecting2432a \kbd{')'} or a \kbd{','}.24332434Actually, a third possibility is mentioned in the error message \kbd{)->},2435which could never be valid in the above context, but a subexpression like2436\kbd{(x)->sin(x)}, defining an inline closure would be valid, and the parser is2437not clever enough to rule that out, so we get the same message as in2438\bprog2439? (x2440*** syntax error, unexpected $end, expecting )-> or ',' or ')': (x2441*** ^-2442@eprog\noindent2443where all three proposed continuations would be valid.24442445\emph{Runtime errors} from the evaluator are nicer because they answer a2446correctly worded query, otherwise the bytecode compiler would have protested2447first; here is a slightly pathological case:2448\bprog2449? if (siN(x) < eps, do_something())2450*** at top-level: if(siN(x)<eps,do_someth2451*** ^--------------------2452*** not a function in function call2453@eprog\noindent (no arrow!) The code is syntactically correct and compiled2454correctly, even though the \kbd{siN} function, a typo for \kbd{sin}, was not2455defined at this point. When trying to evaluate the bytecode, however, it2456turned out that \kbd{siN} is still undefined so we cannot evaluate the2457function call \kbd{siN(x)}.24582459\emph{Library runtime errors} are even nicer because they have more2460mathematical content, which is easier to grasp than a parser's logic:2461\bprog2462? 1/Mod(2,4)2463*** at top-level: 1/Mod(2,4)2464*** ^---------2465*** _/_: impossible inverse in Fp_inv: Mod(2, 4).2466@eprog\noindent telling us that a runtime error occurred while evaluating the2467binary \kbd{/} operator (the \kbd{\_} surrounding the operator are2468placeholders), more precisely the \kbd{Fp\_inv} library function was fed2469the argument \kbd{Mod(2,4)} and could not invert it. More context is provided2470if the error occurs deep in the call chain:2471\bprog2472? f(x) = 1/x;2473? g(N) = for(i = -N, N, f(i + O(5)));2474? g(10)2475*** at top-level: g(10)2476*** ^-----2477*** in function g: for(i=-N,N,f(i))2478*** ^-----2479*** in function f: 1/x2480*** ^--2481*** _/_: impossible inverse in ginv: O(5).2482@eprog\noindent In this example, the debugger reports (at least) 3 enclosed2483frames: last (innermost) is the body of user function $f$, the body of $g$,2484and the top-level (global scope). In fact, the \kbd{for} loop in $g$'s body2485defines an extra frame, since there exist variables scoped to the loop body.24862487\subsec{Error recovery}\sidx{error recovery}\label{se:errorrec}24882489It is annoying to wait for a program to finish and find out the hard2490way that there was a mistake in it (like the division by 0 above), sending2491you back to the prompt. First you may lose some valuable intermediate data.2492Also, correcting the error may not be obvious; you might have to change your2493program, adding a number of extra statements and tests to narrow down2494the problem.24952496A different situation, still related to error recovery, is when you2497actually foresee that some error may occur, are unable to prevent it, but2498quite capable of recovering from it, given the chance. Examples include lazy2499factorization, where you knowingly use a pseudo prime $N$ as if it were2500prime; you may then encounter an ``impossible'' situation, but this would2501usually exhibit a factor of $N$, enabling you to refine the factorization and2502go on. Or you might run an expensive computation at low precision to guess2503the size of the output, hence the right precision to use. You can then2504encounter errors like ``precision loss in truncation'', e.g when trying to2505convert \kbd{1E1000}, known to $28$ digits of accuracy, to an integer; or2506``division by 0'', e.g inverting \kbd{0E1000} when all accuracy has been2507lost, and no significant digit remains. It would be enough to restart part of2508the computation at a slightly higher precision.25092510We now describe \tev{error trapping}, a useful mechanism which alleviates2511much of the pain in the first situation (the break loop debugger), and2512provides satisfactory ways out of the second one (the \tet{iferr} exception2513handler).25142515\subsec{Break loop}\label{se:break_loop}25162517A \tev{break loop} is a special debugging mode that you enter whenever a2518user interrupt (\kbd{Control-C}) or runtime error occurs, freezing the2519\kbd{gp} state, and preventing cleanup until you get out of the loop. By2520runtime error, we mean an error from the evaluator, the library or a user error2521(from \tet{error}), \emph{not} syntax errors. When a break loop starts, a2522prompt is issued (\kbd{break>}). You can type in a \kbd{gp} command, which is2523evaluated when you hit the \kbd{<Return>} key, and the result is printed as2524during the main \kbd{gp} loop, except that no history of results is kept. Then2525the break loop prompt reappears and you can type further commands as long as2526you do not exit the loop. If you are using readline, the history of commands is2527kept, and line editing is available as usual. If you type in a command that2528results in an error, you are sent back to the break loop prompt: errors do2529\var{not} terminate the loop.25302531To get out of a break loop, you can use \tet{next}, \tet{break}, \tet{return},2532or type \kbd{C-d} (\kbd{EOF}), any of which will let \kbd{gp} perform its2533usual cleanup, and send you back to the \kbd{gp} prompt. Note that \kbd{C-d}2534is slightly dangerous, since typing it \emph{twice} will not only send you2535back to the \kbd{gp} prompt, but to your shell prompt! (Since \kbd{C-d} at2536the \kbd{gp} prompt exits the gp session.)25372538If the break loop was started by a user interrupt \kbd{Control-C}, and not by2539an error, inputting an empty line, i.e hitting the \kbd{<Return>} key at the2540\kbd{break>} prompt, resumes the temporarily interrupted computation. A single2541empty line has no effect in case of a fatal error, to avoid getting get out of2542the loop prematurely, thereby losing valuable debugging data. Any of2543\tet{next}, \tet{break}, \tet{return}, or \kbd{C-d} will abort the computation2544and send you back to the \kbd{gp} prompt as above.25452546Break loops are useful as a debugging tool. You may inspect the values of2547\kbd{gp} variables to understand why an error occurred, or change2548\kbd{gp}'s state in the middle of a computation (increase debugging level,2549start storing results in a log file, set variables to different values\dots):2550hit \kbd{C-c}, type in your modifications, then let the computation go on as2551explained above. A break loop looks like this:2552\bprog2553? v = 0; 1/v2554*** at top-level: v=0;1/v2555*** ^--2556*** _/_: impossible inverse in gdiv: 0.2557*** Break loop (type 'break' to go back to the GP prompt)2558break>2559@eprog2560\noindent So the standard error message is printed first. The2561\kbd{break>} at the bottom is a prompt, and hitting \kbd{v} then2562\kbd{<Return>}, we see:2563\bprog2564break> v256502566@eprog\noindent explaining the problem. We could have typed any \kbd{gp}2567command, not only the name of a variable, of course. Lexically-scoped2568variables are accessible to the evaluator during the break loop:2569\bprog2570? for(v = -2, 2, print(1/v))2571-1/22572-12573*** at top-level: for(v=-2,2,print(1/v))2574*** ^----2575*** _/_: impossible inverse in gdiv: 0.2576*** Break loop (type 'break' to go back to the GP prompt)2577break> v257802579@eprog\noindent2580Even though loop indices are automatically lexically scoped and no longer2581exist when the break loop is run, enough debugging information is retained in2582the bytecode to reconstruct the evaluation context. Of course, when the error2583occurs in a nested chain of user function calls, lexically scoped variables are2584available only in the corresponding frame:2585\bprog2586? f(x) = 1/x;2587? g(x) = for(i = 1, 10, f(x+i));2588? for(j = -5,5, g(j))2589*** at top-level: for(j=-5,5,g(j))2590*** ^-----2591*** in function g: for(i=1,10,f(x+i))2592*** ^-------2593*** in function f: 1/x2594*** ^--2595*** _/_: impossible inverse in gdiv: 0.2596*** Break loop: type 'break' to go back to GP prompt2597break> [i,j,x] \\ @com the $x$ in $f$'s body.2598[i, j, 0]2599break> dbg_up \\ @com go up one frame2600*** at top-level: for(j=-5,5,g(j))2601*** ^-----2602*** in function g: for(i=1,10,f(x+i))2603*** ^-------2604break> [i,j,x] \\ @com the $x$ in $g$'s body, $i$ in the for loop.2605[5, j, -5]2606@eprog2607The following GP commands are available during a break loop to help debugging:26082609\tet{dbg_up}$(n)$: go up $n$ frames, as seen above.26102611\tet{dbg_down}$(n)$: go down $n$ frames, cancelling previous \kbd{dbg\_up}'s.26122613\tet{dbg_x}$(t)$: examine $t$, as \kbd{\bs x} but more flexible.26142615\tet{dbg_err}$()$: returns the current error context \typ{ERROR}. The error2616components often provide useful additional information:2617\bprog2618? O(2) + O(3)2619*** at top-level: O(2)+O(3)2620*** ^-----2621*** _+_: inconsistent addition t_PADIC + t_PADIC.2622*** Break loop: type 'break' to go back to GP prompt2623break> E = dbg_err()2624error("inconsistent addition t_PADIC + t_PADIC.")2625break> Vec(E)2626["e_OP", "+", O(2), O(3)]2627@eprog26282629\misctitle{Note} The debugger is enabled by default, and fires up as soon as2630a runtime error occurs. If you do not like this behavior, you may disable it by2631setting the default \tet{breakloop} to 0 in for \kbd{gprc}. A runtime error2632will send you back to the prompt. Note that the break loop is automatically2633disabled when running \kbd{gp} in non interactive mode, i.e.~when the program's2634standard input is not attached to a terminal.26352636\misctitle{Technical Note} When you enter a break loop due to a PARI stack2637overflow, the PARI stack is reset so that you can run commands. Otherwise the2638stack would immediately overflow again! Still, as explained above, you do not2639lose the value of any \kbd{gp} variable in the process.26402641\subsec{Protecting code}2642The expression26432644\kbd{iferr(\var{statements}, ERR, \var{recovery})}26452646\noindent evaluates and returns the value of \var{statements}, unless an2647error occurs during the evaluation in which case the value of \var{recovery}2648is returned. As in an if/else clause, with the difference that2649\var{statements} has been partially evaluated, with possible side effects.2650We shall give a lot more details about the \kbd{ERR} argument shortly; it is2651the name of a variable, lexically scoped to the \var{recovery} expression2652sequence, whose value is set by the exception handler to help the recovery2653code decide what to do about the error.26542655For instance one can define a fault tolerant inversion function as follows:2656\bprog2657? inv(x) = iferr(1/x, ERR, "oo") \\ ERR is unused...2658? for (i=-1,1, print(inv(i)))2659-12660oo266112662@eprog\noindent Protected codes can be nested without adverse effect.2663Let's now see how \kbd{ERR} can be used; as written, \kbd{inv} is too2664tolerant:2665\bprog2666? inv("blah")2667%2 = "oo"2668@eprog Let's improve it by checking that we caught a ``division by 0''2669exception, and not an unrelated one like the type error \kbd{1 / "blah"}.2670\bprog2671? inv2(x) = {2672iferr(1/x,2673ERR, if (errname(ERR) != "e_INV", error(ERR)); "oo")2674}2675? inv2(0)2676%3 = "oo" \\ as before2677? inv2("blah")2678*** at top-level: inv2("blah")2679*** ^------------2680*** in function inv2: ...f(errname(ERR)!="e_INV",error(ERR));"oo")2681*** ^-----------------2682*** error: forbidden division t_INT / t_STR.2683@eprog\noindent In the \kbd{inv2("blah")} example, the error type was not2684expected, so we rethrow the exception: \kbd{error(ERR)} triggers the original2685error that we mistakenly trapped. Since the recovery code should always check2686whether the error is the one expected, this construction is very common and2687can be simplified to2688\bprog2689? inv3(x) = iferr(1/x,2690ERR, "oo",2691errname(ERR) == "e_INV")2692@eprog\noindent More generally26932694\kbd{iferr(\var{statements}, ERR, \var{recovery}, \var{predicate})}26952696\noindent only catches the exception if \var{predicate} (allowed to check2697various things about \kbd{ERR}, not only its name) is nonzero.26982699Rather than trapping everything, then rethrowing whatever we do not like, we2700advise to only trap errors of a specific kind, as above. Of course,2701sometimes, one just want to trap \emph{everything} because we do not know2702what to expect. The following function check whether \tet{install} works2703correctly in your \kbd{gp}:2704\bprog2705broken_install() =2706{ \\ can we install?2707iferr(install(addii,GG),2708ERR, return ("OS"));2709\\ can we use the installed function?2710iferr(if (addii(1,1) != 2, return("BROKEN")),2711ERR, return("USE"));2712return (0);2713}2714@eprog2715\noindent The function returns2716\kbd{OS} if the operating system does not support \kbd{install},2717\kbd{USE} if using an installed function triggers an error,2718\kbd{BROKEN} if the installed function did not behave as expected,2719and 0 if everything works.27202721The \kbd{ERR} formal parameter contains more useful data than just the error2722name, which we recovered using \kbd{errname(ERR)}. In fact, a \typ{ERROR}2723object usually has extra components, which can be accessed as2724\kbd{component(ERR,1)}, \kbd{component(ERR,2)}, and so on. Or globally by2725casting the error to a \typ{VEC}: \kbd{Vec(ERR)} returns the vector2726of all components at once. See \secref{se:iferr} for the list of all2727exception types, and the corresponding contents of \kbd{ERR}.27282729\section{Interfacing GP with other languages}2730\noindent2731The PARI library was meant to be interfaced with C programs. This specific2732use is dealt with extensively in the \emph{User's guide to the PARI library}.2733Of course, \kbd{gp} itself provides a convenient interpreter to execute2734rather intricate scripts (see \secref{se:programming}).27352736Scripts, when properly written, tend to be shorter and clearer than C2737programs, and are certainly easier to write, maintain or debug. You don't2738need to deal with memory management, garbage collection, pointers,2739declarations, and so on. Because of their intrinsic simplicity, they are more2740robust as well. They are unfortunately somewhat slower. Thus their use will2741remain complementary: it is suggested that you test and debug your algorithms2742using scripts, before actually coding them in C if speed is paramount.2743The GP2C compiler often eases this part.27442745The \kbd{install} command (see~\secref{se:install}) efficiently imports2746foreign functions for use under \kbd{gp}, which can of course be written2747using other libraries than PARI. Thus you may code only critical parts2748of your program in C, and still maintain most of the program as a GP script.27492750We are aware of three PARI-related Free Software packages to embed PARI in2751other languages. We \emph{neither endorse nor support} any of them, but you2752may want to give them a try if you are familiar with the languages they are2753based on. The first is the Python-based SAGE2754system (\url{http://sagemath.org/}). The second is the \tet{Math::Pari} Perl2755module (see any CPAN mirror), written by Ilya Zakharevich.2756Finally, Michael Stoll and Sam Steingold have integrated PARI into \tet{CLISP}2757(\url{http://clisp.cons.org/}), a Common Lisp implementation.27582759These provide interfaces to \kbd{gp} functions for use in2760\kbd{python}, \kbd{perl}, or \kbd{Lisp}\sidx{Perl}\sidx{Python}\sidx{Lisp}2761programs, respectively.27622763\section{Defaults}\sidx{defaults}2764\label{se:defaults}27652766\noindent There are many internal variables in \kbd{gp}, defining how the2767system will behave in certain situations, unless a specific override has been2768given. Most of them are a matter of basic customization (colors, prompt) and2769will be set once and for all in your \idx{preferences file} (see2770\secref{se:gprc}), but some of them are useful interactively (set timer on,2771increase precision, etc.).27722773The function used to manipulate these values is called \kbd{default}, which2774is described in \secref{se:default}. The basic syntax is27752776\kbd{default(\var{def}, \var{value})},27772778\noindent which sets the default \var{def} to \var{value}. In interactive2779use, most of these can be abbreviated using \kbd{gp} metacommands2780(mostly, starting with \b), which we shall describe in the next section.27812782Available defaults are described in the reference guide,2783\secref{se:gp_defaults}, the most important one being \tet{parisizemax}.2784Just be aware that typing \kbd{default} by itself will list all of them, as2785well as their current values (see \b{d}).27862787\misctitle{Note} The suffixes \kbd{k}, \kbd{M} or \kbd{G} can be appended to2788a \var{value} which is a numeric argument, with the effect of multiplying it2789by $10^3$, $10^6$ and $10^9$ respectively. Case is not taken into account2790there, so for instance \kbd{30k} and \kbd{30K} both stand for $30000$. This2791is mostly useful to modify or set the defaults \kbd{parisize} and2792\kbd{parisizemax} which typically involve a lot of trailing zeroes.27932794\misctitle{(somewhat technical) Note} As we saw in \secref{se:strings},2795the second argument to \kbd{default} is subject to string context2796expansion, which means you can use run-time values. In other words, something2797like2798\bprog2799a = 3;2800default(logfile, "file" a ".log")2801@eprog2802logs the output in \kbd{file3.log}.28032804Some special defaults, corresponding to file names and prompts, expand further2805the resulting value at the time they are set. Two kinds of expansions may be2806performed:28072808\item \teb{time expansion}: the string is sent through the library2809function \tet{strftime}. This means that \kbd{\%}\var{char} combinations have2810a special meaning, usually related to the time and date. For instance,2811\kbd{\%H} = hour (24-hour clock) and \kbd{\%M} = minute [00,59] (on a Unix2812system, you can try \kbd{man strftime} at your shell prompt to get a complete2813list). This is applied to \kbd{prompt} and \kbd{logfile}. For2814instance,28152816\kbd{default(prompt,"(\%H:\%M) ? ")}28172818\noindent2819will prepend the time of day, in the form \kbd{(\var{hh}:\var{mm})}2820to \kbd{gp}'s usual prompt.28212822\item \teb{environment expansion}: When the string contains a sequence of2823the form \kbd{\$\var{SOMEVAR}}, e.g.~\kbd{\$HOME}, the environment is2824searched and if \var{SOMEVAR} is defined, the sequence is replaced by the2825corresponding value. Also the \kbd{\til} symbol has the same meaning as in2826many shells~--- \kbd{\til} by itself stands for your home directory, and2827\kbd{\til{}user} is expanded to \kbd{user}'s home directory. This is applied2828to all file names\sidx{filename}. \label{se:envir}28292830\section{Simple metacommands}\label{se:meta}28312832\noindent2833Simple metacommands are meant as shortcuts and should not be used in GP2834scripts (see \secref{se:programming}). Beware that these, as all of \kbd{gp}2835input, are \emph{case sensitive}. For example, \b{Q} is not identical to2836\b{q}. Two kinds of arguments are allowed: numbers (denoted $n$ below)2837and names (denoted \var{filename} below); braces are used to denote optional2838arguments, , e.g.~$\{n\}$ means that a numeric argument is expected but2839can be omitted. Names can be optionally surrounded by double quotes2840and in this case can contain whitespace, e.g. \kbd{"a b"} and are treated2841as ordinary character strings, see \secref{se:strings} for details.28422843Whitespace (or spaces) between the metacommand and its arguments and within2844unquoted arguments is optional. (This can cause problems with \b{w},2845when you insist on having a file name whose first character is a digit, and2846with \b{r} or \b{w}, if the file name itself contains a space. In such cases,2847just quote filenames or use the underlying \tet{read} or \tet{write} function).28482849\subseckbd{?$\{\var{command}\}$} The \kbd{gp} on-line help interface.2850If you type \kbd{?$n$} where $n$ is a number from 1 to 11, you will get the2851list of functions in Section $3.n$ of the manual (the list of sections being2852obtained by simply typing \kbd{?}). \label{se:exthelp}28532854These names are in general not informative enough. More details can be2855obtained by typing \kbd{?\var{function}}, which gives a short explanation of2856the function's calling convention and effects. A help string is also attached2857to a symbolic operator, where arguments are replaced by a placeholder2858character \kbd{\_}:2859\bprog2860? ?sin2861sin(x): sine of x.28622863? ?_*_2864x*y: product of x and y.28652866? ?!_2867!a: boolean operator "not".28682869? ?_!2870n!: factorial of n.28712872? ? _^_2873x^y: compute x to the power y.2874@eprog\noindent Of course, to have complete information, read Chapter 3 of2875this manual. The source code is at your disposal as well, though a trifle2876less readable.28772878If the line before the copyright message indicates that extended help is2879available (this means \kbd{perl} is present on your system and the PARI2880distribution was correctly installed), you can add more \kbd{?} signs for2881extended functionality:28822883\kbd{??~\var{keyword}} yields the function description as it stands in this2884manual, usually in Chapter~2 or~3. If you're not satisfied with the default2885chapter chosen, you can impose a given chapter by ending the keyword with2886\kbd{@} followed by the chapter number, e.g.~\kbd{??~Hello@2} will look in2887Chapter~2 for section heading \kbd{Hello} (which doesn't exist, by the way).28882889All operators (e.g.~\kbd{+}, \kbd{\&\&}, etc.) are accepted by this2890extended help, as well as a few other keywords describing key \kbd{gp} concepts,2891e.g.~\kbd{readline} (the line editor), \kbd{integer}, \kbd{nf} (``number2892field'' as used in most algebraic number theory computations), \kbd{ell}2893(elliptic curves), etc.28942895In case of conflicts between \emph{function} and \emph{default} names (e.g2896\tet{log}, \tet{simplify}), the function has higher priority. To get the2897\emph{default} help, use2898\bprog2899?? default(log)2900?? default(simplify)2901@eprog29022903\kbd{???~\var{pattern}} produces a list of sections in Chapter~3 of the2904manual related to your query. As before, if \var{pattern} ends by \kbd{@}2905followed by a chapter number, that chapter is searched instead; you also2906have the option to append a simple \kbd{@} (without a chapter number) to2907browse through the whole manual.29082909If your query contains dangerous characters (e.g \kbd{?} or blanks) it is2910advisable to enclose it within double quotes, as for GP strings (e.g2911\kbd{???~"elliptic curve"}).29122913Note that extended help is more powerful than the short help, since2914it knows about operators as well: you can type \kbd{??~*} or2915\kbd{??~\&\&}, whereas a single \kbd{?} would just yield a not too helpful2916\bprog2917&&: unknown identifier.2918@eprog\noindent message. Also, you can ask for extended help on section2919number~$n$ in Chapter~3, just by typing \kbd{??~$n$} (where \kbd{?$n$} would2920yield merely a list of functions). Finally, a few key concepts in \kbd{gp} are2921documented in this way: metacommands (e.g \kbd{??~"??"}), defaults (e.g2922\kbd{??~default(log)}) not to be mistaken with \kbd{??~log} (the natural2923logarithm) and type names (e.g \typ{INT} or \kbd{integer}), as well as2924various miscellaneous keywords such as \kbd{edit} (short summary of line2925editor commands), \kbd{operator}, \kbd{member}, \kbd{"user defined"},2926\kbd{nf}, \kbd{ell}, \dots29272928Last but not least: \kbd{??} without argument will open a \kbd{dvi}2929previewer (\kbd{xdvi} by default, \kbd{\$GPXDVI} if it is defined in your2930environment) containing the full user's manual. \kbd{??tutorial} and2931\kbd{??refcard} do the same with the \idx{tutorial} and \idx{reference card}2932respectively.29332934\misctitle{Technical note} This functionality is provided by an2935external \kbd{perl} script that you are free to use outside any \kbd{gp} session2936(and modify to your liking, if you are perl-knowledgeable). It is called2937\tet{gphelp}, lies in the \kbd{doc} subdirectory of your distribution2938(just make sure you run \kbd{Configure} first, see Appendix~A) and is2939really two programs in one. The one which is used from within \kbd{gp} is2940\kbd{gphelp} which runs \TeX\ on a selected part of this manual, then opens2941a previewer. \kbd{gphelp -detex} is a text mode equivalent, which looks2942often nicer especially on a colour-capable terminal (see2943\kbd{misc/gprc.dft} for examples). The default \kbd{help} selects which2944help program will be used from within \kbd{gp}. You are welcome to improve this2945help script, or write new ones (and we would like to know about it2946so that we may include them in future distributions). By the way, outside2947of \kbd{gp} you can give more than one keyword as argument to \kbd{gphelp}.29482949\subseckbd{/*...*/} A comment. Everything between the stars is ignored by2950\kbd{gp}. These comments can span any number of lines.29512952\subseckbd{\bs\bs} A one-line comment. The rest of the line2953is ignored by \kbd{gp}.29542955\subsec{\b{a} $\{n\}$} Prints the object number $n$ ($\%n$)2956in raw format. If the number $n$ is omitted, print the latest computed object2957($\%$). \label{se:history}29582959\subsec{\b{c}}\sidx{available commands} Prints the list of all available2960hardcoded functions under \kbd{gp}, not including operators written as special2961symbols (see \secref{se:operators}). More information can be obtained using2962the \kbd{?} metacommand (see above). For user-defined functions / member2963functions, see \b{u} and \b{um}.29642965\subsec{\b{d}} Prints the \idx{defaults} as described in the2966previous section (shortcut for \kbd{default()}, see \secref{se:default}).29672968\subsec{\b{e} $\{n\}$} Switches the \tet{echo} mode on (1) or off (0). If2969$n$ is explicitly given, set echo to $n$.29702971\subsec{\b{g} $\{n\}$} Sets the debugging level \tet{debug} to the2972nonnegative integer $n$. Diagnostics attached to a particular feature can be2973turned on and off using \kbd{setdebug}.29742975\subsec{\b{gf} $\{n\}$} Sets the file usage debugging level \tet{debugfiles}2976to the nonnegative integer $n$.29772978\subsec{\b{gm} $\{n\}$} Sets the memory debugging level \tet{debugmem}2979to the nonnegative integer $n$.29802981\subsec{\b{h} $\{m$\kbd{-}$n\}$} Outputs some debugging info about the2982hashtable. If the argument is a number $n$, outputs the contents of cell2983$n$. Ranges can be given in the form $m$\kbd{-}$n$ (from cell $m$ to cell2984$n$, \$ = last cell). If a function name is given instead of a number or2985range, outputs info on the internal structure of the hash cell this2986function occupies (a \kbd{struct entree} in C). If the range is reduced to2987a dash ('\kbd{-}'), outputs statistics about hash cell usage.29882989\subsec{\b{l} $\{$\var{logfile}$\}$} Switches \tet{log} mode on and off.2990If a \var{logfile} argument is given, change the default logfile name to2991\var{logfile} and switch log mode on.29922993\subsec{\b{m}} As \b{a}, but using prettymatrix format.29942995\subsec{\b{o} $\{n\}$} Sets \tet{output} mode to $n$ ($0$: raw, $1$:2996prettymatrix, $3$: external prettyprint).29972998\subsec{\b{p} $\{n\}$} Sets \tet{realprecision} to $n$ decimal digits.2999Prints its current value if $n$ is omitted.30003001\subsec{\b{pb} $\{n\}$} Sets \tet{realbitprecision} to $n$ bits.3002Prints its current value if $n$ is omitted.30033004\subsec{\b{ps} $\{n\}$} Sets \tet{seriesprecision} to $n$ significant terms.3005Prints its current value if $n$ is omitted.30063007\subsec{\b{q}} Quits the \kbd{gp} session and returns to the system.3008Shortcut for \tet{quit}\kbd{()} (see \secref{se:quit}).30093010\subsec{\b{r} $\{$\var{filename}$\}$} Reads into \kbd{gp} all the3011commands contained in the named file as if they had been typed from the3012keyboard, one line after the other. Can be used in combination with the \b{w}3013command (see below). Related but not equivalent to the function \kbd{read}3014(see \secref{se:read}); in particular, if the file contains more than one3015line of input, there will be one history entry for each of them, whereas3016\kbd{read} would only record the last one. If \var{filename} is omitted,3017re-read the previously used input file (fails if no file has ever been3018successfully read in the current session). If a \kbd{gp} \tet{binary file}3019(see \secref{se:writebin}) is read using this command, it is silently loaded,3020without cluttering the history.30213022Assuming \kbd{gp} figures how to decompress files on your machine, this3023command accepts compressed files in \tet{compress}ed (\kbd{.Z}) or3024\tet{gzip}ped (\kbd{.gz} or \kbd{.z}) format. They will be uncompressed on3025the fly as \kbd{gp} reads them, without changing the files themselves.30263027\subsec{\b{s}} Prints the state of the PARI \tev{stack} and \tev{heap}.3028This is used primarily as a debugging device for PARI.30293030\subsec{\b{t}} Prints the \idx{internal longword format} of all the PARI3031types. The detailed bit or byte format of the initial codeword(s) is3032explained in Chapter~4, but its knowledge is not necessary for a \kbd{gp}3033user.30343035\subsec{\b{u}} Prints the definitions of all user-defined functions.30363037\subsec{\b{um}} Prints the definitions of all user-defined member functions.30383039\subsec{\b{v}} Prints the \idx{version number} and implementation architecture3040(680x0, Sparc, Alpha, other) of the \kbd{gp} executable you are using.30413042\subsec{\b{w} $\{n\}$ $\{$\var{filename}$\}$} Writes the object number3043$n$ ( $\%n$ ) into the named file, in raw format. If the number $n$ is3044omitted, writes the latest computed object ( $\%$ ). If \var{filename} is3045omitted, appends to \kbd{logfile} (the GP function \tet{write} is a trifle more3046powerful, as you can have arbitrary file names).30473048\subsec{\b{x} $\{n\}$} Prints the complete tree with addresses and contents3049(in hexadecimal) of the \idx{internal representation} of the object number3050$n$ ( $\%n$ ). If the number $n$ is omitted, uses the latest computed object3051in \kbd{gp}. As for \b{s}, this is used primarily as a debugging device for3052PARI, and the format should be self-explanatory. The underlying GP3053function \tet{dbg_x} is more versatile, since it can be applied to other3054objects than history entries.30553056\subsec{\b{y} $\{n\}$} Switches \kbd{simplify} on (1) or off (0). If $n$3057is explicitly given, set simplify to $n$.30583059\subseckbd{\#} Switches the \kbd{timer} on or off.30603061\subseckbd{\#\#} Prints the time taken by the latest computation.3062Useful when you forgot to turn on the \kbd{timer}.30633064\section{The preferences file}\sidx{startup}\sidx{preferences file}3065\label{se:gprc}30663067This file, called \tet{gprc} in the sequel, is used to modify or extend3068\kbd{gp} default behavior, in all \kbd{gp} sessions: e.g customize3069\kbd{default} values or load common user functions and aliases. \kbd{gp}3070opens the \kbd{gprc} file and processes the commands in there, \emph{before}3071doing anything else, e.g.~creating the PARI stack. If the file does not exist3072or cannot be read, \kbd{gp} will proceed to the initialization phase at once,3073eventually emitting a prompt. If any explicit command line switches are3074given, they override the values read from the preferences file.30753076\subsec{Syntax} The syntax in the \kbd{gprc} file (and valid in this file3077only) is simple-minded, but should be sufficient for most purposes. The file3078is read line by line; as usual, white space is ignored unless surrounded by3079quotes and the standard multiline constructions using braces, \kbd{\bs}, or3080\kbd{=} are available (multiline comments between \kbd{/*~\dots~*/} are also3081recognized).30823083\subsubsec{Preprocessor:}3084Two types of lines are first dealt with by a preprocessor:30853086\item comments are removed. This applies to all text surrounded by3087\kbd{/*~\dots~*/} as well as to everything following \kbd{\bs\bs} on a given3088line.30893090\item lines starting with \kbd{\#if} \var{boolean} are treated as3091comments if \var{boolean} evaluates to \kbd{false}, and read normally3092otherwise. The condition can be negated using either \kbd{\#if not} (or3093\kbd{\#if !}). If the rest of the current line is empty, the test applies to3094the next line (same behavior as \kbd{=} under \kbd{gp}). The following3095tests can be performed:30963097\kbd{EMACS}: \kbd{true} if \kbd{gp} is running in an Emacs or TeXmacs shell (see3098\secref{se:emacs}).30993100\kbd{READL}: \kbd{true} if \kbd{gp} is compiled with \kbd{readline} support (see3101\secref{se:readline}).31023103\kbd{VERSION} \var{op} \var{number}: where \var{op} is in the set3104$\{ \kbd{>}, \kbd{<}, \kbd{<=}, \kbd{>=} \}$, and \var{number} is a PARI3105version number of the form \var{Major}.\var{Minor}.\var{patch}, where the3106last two components can be omitted (i.e.~$1$ is understood as version $1.0.0$).3107This is \kbd{true} if \kbd{gp}'s version number satisfies the required3108inequality.31093110\kbd{BITS\_IN\_LONG} \kbd{==} \var{number}: \var{number} is $32$ (resp.~$64$).3111This is \kbd{true} if \kbd{gp} was built for a 32-bit (resp.~64-bit)3112architecture.31133114\subsubsec{Commands:}3115After preprocessing, the remaining lines are executed as3116sequence of expressions (as usual, separated by \kbd{;} if necessary). Only3117two kinds of expressions are recognized:31183119\item \var{default} \kbd{=} \var{value}, where \var{default} is one of3120the available defaults (see \secref{se:defaults}), which will be set to3121\var{value} on actual startup. Don't forget the quotes around strings3122(e.g.~for \kbd{prompt} or \kbd{help}).31233124\item \kbd{read "\var{some\_GP\_file}"} where \kbd{\var{some\_GP\_file}}3125is a regular GP script this time, which will be read just before \kbd{gp}3126prompts you for commands, but after initializing the defaults. In particular,3127file input is delayed until the \kbd{gprc} has been fully loaded. This is the3128right place to input files containing \kbd{alias} commands, or your favorite3129macros.31303131\noindent For instance you could set your prompt in the following portable way:3132\bprog3133\\ self modifying prompt looking like @com\hbox{\rm(18:03) \key{gp}\kbd{ >}}3134prompt = "(%H:%M) \e[1mgp\e[m > "31353136\\ readline wants nonprinting characters to be braced between ^A/^B pairs3137#if READL prompt = "(%H:%M) ^A\e[1m^Bgp^A\e[m^B > "31383139\\ escape sequences not supported under emacs3140#if EMACS prompt = "(%H:%M) gp > "3141@eprog31423143\noindent Note that any of the last two lines could be broken in the3144following way3145\bprog3146#if EMACS3147prompt = "(%H:%M) gp > "3148@eprog3149\noindent since the preprocessor directive applies to the next line if the3150current one is empty.31513152A sample \kbd{gprc} file called \kbd{misc/gprc.dft} is provided in the3153standard distribution. It is a good idea to have a look at it and customize3154it to your needs. Since this file does not use multiline constructs, here is3155one (note the terminating \kbd{;} to separate the expressions):3156\bprog3157#if VERSION > 2.2.33158{3159read "my_scripts"; \\ syntax errors in older versions3160new_galois_format = 1; \\ default introduced in 2.2.43161}3162#if ! EMACS3163{3164colors = "9, 5, no, no, 4, 1, 2";3165help = "gphelp -detex -ch 4 -cb 0 -cu 2";3166}3167@eprog31683169\subsec{The gprc location}3170When \kbd{gp} is started, it looks for a customization file, or \kbd{gprc} in3171the following places (in this order, only the first one found will be3172loaded):31733174\noindent\item \kbd{gp} checks whether the environment variable3175\tet{GPRC} is set. On Unix, this can be done with something like: \smallskip31763177\settabs\+\indent&\kbd{GPRC=/my/dir/anyname; export GPRC}\quad&\cr31783179\+&\kbd{GPRC=/my/dir/anyname; export GPRC}\quad&in \kbd{sh} syntax3180(for instance in your \kbd{.profile}),\cr31813182\+&\kbd{setenv GPRC /my/dir/anyname} &in \kbd{csh} syntax3183(in your \kbd{.login} or \kbd{.cshrc} file).\cr31843185\+&\kbd{env GPRC=/my/dir/anyname gp} &on the command line launching \kbd{gp}.\cr31863187\noindent If so, the file named by \kbd{\$GPRC} is the \kbd{gprc}.31883189\noindent\item If \kbd{GPRC} is not set, and if the environment variable3190\kbd{HOME} is defined, \kbd{gp} then tries31913192\kbd{\$HOME/.gprc} on a Unix system31933194\kbd{\$HOME\bs gprc.txt} on a DOS, OS/2, or Windows system.31953196\noindent\item If no gprc was found among the user files mentioned above3197we look for \kbd{/etc/gprc} for a system-wide gprc file (you will need root3198privileges to set up such a file yourself).31993200\noindent\item Finally, we look in pari's \kbd{datadir} for a file named32013202\kbd{.gprc} on a Unix system32033204\kbd{gprc.txt} on a DOS, OS/2, or Windows system. If you are using our3205Windows installer, this is where the default preferences file is written.32063207\noindent Note that on Unix systems, the \kbd{gprc}'s default name starts3208with a '.' and thus is hidden to regular \kbd{ls} commands; you need to type3209\kbd{ls -a} to list it.321032113212\section{Using readline} \sidx{line editor}\sidx{completion}32133214This very useful library provides line editing and contextual completion3215to \kbd{gp}. You are encouraged to read the \kbd{readline} user manual,3216but we describe basic usage here.32173218\misctitle{A (too) short introduction to readline}\label{se:readline}3219In the following, \kbd{C-} stands for ``the \kbd{Control} key combined with3220another'' and the same for \kbd{M-} with the \kbd{Meta} key; generally3221\kbd{C-} combinations act on characters, while the \kbd{M-} ones operate on3222words. The \kbd{Meta} key might be called \kbd{Alt} on some keyboards, will3223display a black diamond on most others, and can safely be replaced by3224\kbd{Esc} in any case.32253226Typing any ordinary key inserts text where the cursor stands, the arrow keys3227enabling you to move in the line. There are many more movement commands,3228which will be familiar to the Emacs user, for instance \kbd{C-a}/\kbd{C-e}3229will take you to the start/end of the line, \kbd{M-b}/\kbd{M-f} move the3230cursor backward/forward by a word, etc. Just press the \kbd{<Return>} key at3231any point to send your command to \kbd{gp}.32323233All the commands you type at the \kbd{gp} prompt are stored in a history,3234a multiline command being saved as a single concatenated line. The Up and Down3235arrows (or \kbd{C-p}/\kbd{C-n}) will move you through the history,3236\kbd{M-<}/\kbd{M->} sending you to the start/end of the history.3237\kbd{C-r}/\kbd{C-s} will start an incremental backward/forward search. You3238can kill text (\kbd{C-k} kills till the end of line, \kbd{M-d} to the end of3239current word) which you can then yank back using the \kbd{C-y} key (\kbd{M-y}3240will rotate the kill-ring). \kbd{C-\_} will undo your last changes3241incrementally (\kbd{M-r} undoes all changes made to the current line).3242\kbd{C-t} and \kbd{M-t} will transpose the character (word) preceding the3243cursor and the one under the cursor.32443245Keeping the \kbd{M-} key down while you enter an integer (a minus sign3246meaning reverse behavior) gives an argument to your next readline command3247(for instance \kbd{M-- C-k} will kill text back to the start of line). If you3248prefer \idx{Vi}--style editing, \kbd{M-C-j} will toggle you to Vi mode.32493250Of course you can change all these default bindings. For that you need to3251create a file named \kbd{.inputrc} in your home directory. For instance3252(notice the embedding conditional in case you would want specific bindings3253for \kbd{gp}):3254%3255\bprog3256$if Pari-GP3257set show-all-if-ambiguous3258"\C-h": backward-delete-char3259"\e\C-h": backward-kill-word3260"\C-xd": dump-functions3261(: "\C-v()\C-b" #@com can be annoying when copy-pasting!3262[: "\C-v[]\C-b"3263$endif3264@eprog3265\noindent\kbd{C-x C-r} will re-read this init file, incorporating any3266changes made to it during the current session.32673268\misctitle{Note} By default, \kbd{(} and \kbd{[} are bound to the function3269\kbd{pari-matched-insert} which, if ``electric parentheses'' are enabled3270(default: off) will automatically insert the matching closure (respectively3271\kbd{)} and \kbd{]}). This behavior can be toggled on and off by giving3272the numeric argument $-2$ to \kbd{(} (\kbd{M--2(}), which is useful if you3273want, e.g to copy-paste some text into the calculator. If you do not want a3274toggle, you can use \kbd{M--0} / \kbd{M--1} to specifically switch it on or3275off).32763277\misctitle{Note} In some versions of readline (2.1 for instance), the3278\kbd{Alt} or \kbd{Meta} key can give funny results (output 8-bit accented3279characters for instance). If you do not want to fall back to the \kbd{Esc}3280combination, put the following two lines in your \kbd{.inputrc}:3281%3282\bprog3283set convert-meta on3284set output-meta off3285@eprog32863287\misctitle{Command completion and online help} Hitting3288\kbd{<TAB>} will complete words for you. This mechanism is context-dependent:3289\kbd{gp} will strive to only give you meaningful completions in a given3290context (it will fail sometimes, but only under rare and restricted3291conditions).32923293For instance, shortly after a \kbd{\til}, we expect a user name, then a3294path to some file. Directly after \kbd{default(} has been typed, we would3295expect one of the \kbd{default} keywords. After a '.', we expect a member3296keyword. And generally of course, we expect any GP symbol which may be found3297in the hashing lists: functions (both yours and GP's), and variables.32983299If, at any time, only one completion is meaningful, \kbd{gp} will provide it3300together with33013302\item an ending comma if we are completing a default,33033304\item a pair of parentheses if we are completing a function name. In3305that case hitting \kbd{<TAB>} again will provide the argument list as given3306by the online help. (Recall that you can always undo the effect3307of the preceding keys by hitting \kbd{C-\_}; this applies here.)33083309Otherwise, hitting \kbd{<TAB>} once more will give you the list of possible3310completions. Just experiment with this mechanism as often as possible,3311you will probably find it very convenient. For instance, you can obtain3312\kbd{default(seriesprecision,10)}, just by hitting \kbd{def<TAB>se<TAB>10},3313which saves 18 keystrokes (out of 27).33143315Hitting \kbd{M-h} will give you the usual short online help concerning the3316word directly beneath the cursor, \kbd{M-H} will yield the extended help3317corresponding to the \kbd{help} default program (usually opens a \idx{dvi}3318previewer, or runs a primitive tex-to-ASCII program). None of these disturb3319the line you were editing.33203321\section{GNU Emacs and PariEmacs}3322\label{se:emacs}33233324If you install the PariEmacs package (see Appendix A), you may use \kbd{gp}3325as a subprocess in \idx{Emacs}. You then need to include in your \kbd{.emacs}3326file the following lines:3327\bprog3328(autoload 'gp-mode "pari" nil t)3329(autoload 'gp-script-mode "pari" nil t)3330(autoload 'gp "pari" nil t)3331(autoload 'gpman "pari" nil t)33323333(setq auto-mode-alist3334(cons '("\\.gp$" . gp-script-mode) auto-mode-alist))3335@eprog3336\noindent which autoloads functions from the PariEmacs package and ensures3337that file with the \kbd{.gp} suffix are edited in gp-script mode.33383339Once this is done, under GNU Emacs if you type \kbd{M-x gp} (where as usual3340\kbd{M} is the \kbd{Meta} key), a special shell will be started launching3341\kbd{gp} with the default stack size and prime limit. You can then work as3342usual under \kbd{gp}, but with all the facilities of an advanced text editor.3343See the PariEmacs documentation for customizations, menus, etc.33443345\newpage334633473348