Annotation of OpenXM_contrib/pari/doc/usersch2.tex, Revision 1.1.1.1
1.1 maekawa 1: \chapter{Specific Use of the GP Calculator}
2:
3: Originally, \idx{GP} was designed as a debugging tool for the PARI system
4: library, and hence not much thought had been given to making it
5: user-friendly. The situation has now changed somewhat, and GP is very
6: useful as a stand-alone tool. The operations and functions available in
7: PARI and GP will be described in the next chapter. In the present one, we
8: describe the specific use of the GP programmable calculator.
9:
10: For starting the calculator, the general commandline syntax is:
11:
12: \kbd{gp [-s stacksize] [-p primelimit]}
13:
14: \noindent
15: where items within brackets are optional\footnote{*}{On the Macintosh, even
16: after clicking on the gp icon, once in the MPW Shell, you still need to type
17: explicitly a command of the above form.}. These correspond to some internal
18: parameters of GP, or {\it defaults}. See \secref{se:defaults} below for a
19: list and explanation of all defaults, there are many more than just those
20: two. These defaults can be changed by adding parameters to the input line
21: as above, or interactively during a GP session or in a preferences file (also
22: known as \kbd{gprc}).
23:
24: \unix Some new features were developed on UNIX platforms, and depend heavily
25: on the operating system in use. It is {\it possible\/} that some of these
26: will be ported to other operating systems (BeOS, MacOS, DOS, OS/2, Windows,
27: etc.) in future versions (most of them should be easy tasks for anybody
28: acquainted with those). As for now, most of them were not. So, whenever a
29: specific feature of the UNIX version is discussed in a paragraph, a UNIX sign
30: sticks out in the left margin, like here. Just skip these if you're stranded
31: on a different operating system: the core GP functions (i.e.~at least
32: everything which is even faintly mathematical in nature) will still be
33: available to you. It may also be possible (and then definitely advisable) to
34: install \idx{Linux} or \idx{FreeBSD} on your machine.
35:
36: \misctitle{Note (added in version 2.0.12):} All the UNIX goodies are now
37: available for DOS, OS/2 and Windows 3.1, thanks to the \tet{EMX} runtime
38: package (\kbd{install} excluded under DOS, since DLLs are not supported by
39: the OS). They've been reported to be available under Windows 95/98 and NT
40: using the Cygwin package (untested by us, but supposedly supported by
41: \kbd{Configure}).
42:
43: \emacs If you have GNU Emacs, you can work in a special Emacs shell (see
44: \secref{se:emacs}), which is started by typing \kbd{M-x gp} (where as
45: usual \kbd{M} is the \kbd{Meta} key) if you accept the default stack, prime
46: and buffer sizes, or \kbd{C-u M-x gp} which will ask you for the name of the
47: gp executable, the stack size, the prime limit and the buffer size. Specific
48: features of this Emacs shell will be indicated by an EMACS sign.\smallskip
49:
50: If a \idx{preferences file} (or \kbd{gprc}, to be discussed in
51: \secref{se:gprc}) can be found, GP will then read it and execute the commands
52: it contains. This provides an easy way to customize GP without having to
53: delve into the code to hardwire it to your likings.
54:
55: A copyright message then appears which includes the version number. Please
56: note this number, so as to be sure to have the most recent version if you
57: wish to have updates of PARI. The present manual is written for version
58: \vers, and has undergone major changes since the 1.39.xx versions.
59:
60: After the copyright, the computer works for a few seconds (it is in fact
61: computing and storing a table of primes), writes the top-level help
62: information, some initial defaults, and then waits after printing its prompt
63: (initially: \kbd{?}).
64:
65: Note that at any point the user can type \kbd{Ctrl-C} (that is press
66: simultaneously the \kbd{Control} and \kbd{C} keys): the current
67: computation will be interrupted and control given back to the user at the GP
68: prompt.
69:
70: The top-level help information tells you that (as in many systems) to get
71: help, you should type a \kbd{?}. When you do this and hit return, a menu
72: appears, describing the eleven main categories of available functions and
73: what to do to get more detailed help. If you now type \kbd{?$n$} with $1\le
74: n\le11$, you will get the list of commands corresponding to category $n$
75: and simultaneously to Section $3.n$ of this manual.
76:
77: If you type \kbd{?}\var{functionname} where \var{functionname} is the
78: name of a PARI function, you will get a short explanation of this
79: function.
80:
81: \unix If extended help (see \secref{se:exthelp}) is available on your
82: system, you can double or triple the \kbd{?} sign to get much more:
83: respectively the complete description of the function (e.g.~\kbd{??~sqrt}),
84: or a list of GP functions relevant to your query (e.g.~ \kbd{???~"elliptic
85: curve"} or \kbd{???~"quadratic field"}).
86:
87: If GP was compiled with the right options (see Appendix A), a line
88: editor will be available to correct the command line, get automatic
89: completions, and so on. See \secref{se:readline} for a short summary of
90: available commands. This might not be available for all architectures.
91:
92: Whether extended on-line help and line editing are available or not is
93: indicated in the GP banner, between the version number and the copyright
94: message.
95:
96: If you type \kbd{?\bs} you will get a short description of the metacommands
97: (keyboard shortcuts).
98:
99: Finally, typing \kbd{?.} will return the list of available (pre-defined)
100: member functions. These are functions attached to specific kind of objects,
101: used to retrieve easily some information from complicated structures (you
102: can define your own but they won't be shown here). We will soon describe
103: these commands in more detail.
104:
105: As a general rule, under GP, commands starting with \b\ or with some
106: other symbols like \kbd{?} or \kbd{\#}, are not computing commands, but are
107: metacommands which allow the user to exchange information with GP. The
108: available metacommands can be divided into default setting commands
109: (explained below) and simple commands (or keyboard shortcuts, to be dealt
110: with in \secref{se:meta}).
111:
112: \section{Defaults and output formats}\sidx{defaults}\sidx{output formats}
113: \label{se:defaults}
114:
115: \noindent
116: There are many internal variables in GP, defining how the system will behave
117: in certain situations, unless a specific override has been given. Most
118: of them are a matter of basic customization (colors, prompt) and will be set
119: once and for all in your \idx{preferences file} (see \secref{se:gprc}), but
120: some of them are useful interactively (set timer on, increase precision,
121: etc.).
122:
123: The function used to manipulate these values is called \kbd{default}, which
124: is described in \secref{se:default}. The basic syntax is
125:
126: \kbd{default(\var{def}, \var{value})},
127:
128: \noindent
129: which sets the default \var{def} to \var{value}. In interactive
130: use, most of these can be abbreviated using historic GP metacommands (mostly,
131: starting with \b), which we shall describe in the next section.
132:
133: Here we will only describe the available defaults and how they are used. Just
134: be aware that typing \kbd{default} by itself will list all of them, as well
135: as their current values (see \b{d}). Just after the default name, we give
136: between parentheses the initial value when GP starts (assuming you did not
137: tamper with it using command-line switches or a~\tet{gprc}).
138:
139: \misctitle{(somewhat technical) Note:} As we will see in \secref{se:strings},
140: the second argument to default will be subject to string context expansion,
141: which means you can use run-time values. In other words, something like
142: \kbd{a = 3; default(logfile, "\var{some filename}" a ".log")} will work.
143:
144: For the user's convenience, some defaults will be expanded further when
145: the values are used (after the above expansion has been performed):
146:
147: $\bullet$ \idx{time expansion}: the string is sent through the library
148: function \tet{strftime}. This means that \kbd{\%}\var{char} combinations have
149: a special meaning, usually related to the time and date. For instance,
150: \kbd{\%H} = hour (24-hour clock) and \kbd{\%M} = minute [00,59] (on a Unix
151: system, you can try \kbd{man strftime} at your shell prompt to get a complete
152: list). This is applied to \kbd{prompt}, \kbd{psfile}, and \kbd{logfile}. For
153: instance,
154:
155: \kbd{default(prompt,"(\%R) ? ")}
156:
157: \noindent
158: will prepend the time of day, in the form \kbd{(\var{hh}:\var{mm})}
159: to GP's usual prompt.
160:
161: \unix $\bullet$ \idx{environment expansion}: When the string contains a
162: sequence of the form \kbd{\${\it SOMEVAR}} (e.g.~\kbd{\$HOME}) the
163: environment is searched and if {\it SOMEVAR} is defined, the sequence is
164: replaced by the corresponding value. Also the \kbd{\til} symbol has the
165: same meaning as in the C and bash shells~--- \kbd{\til} by itself stands
166: for your home directory, and \kbd{\til{}user} is expanded to \kbd{user}'s
167: home directory. This is applied to all filenames\sidx{filename}.
168:
169: \subsecidx{buffersize} (default \kbd{30000}): GP input is buffered, which means
170: only so many bytes of data can be read at a time before a command is
171: executed. This used to be a very important variable, to allow for very
172: large input files to be read into GP, for example large matrices, without it
173: complaining about ``unused characters''. Currently, \kbd{buffersize} is
174: automatically adjusted to the size of the data that are to be read. It will
175: never go down by itself though. Thus this option may come in handy to decrease
176: the buffer size after some unusually large \kbd{read}, when you don't need to
177: keep gigantic buffers around anymore.
178:
179: \subsecidxunix{colors} (default \kbd{""}): this default is only usable if GP
180: \label{se:colors}
181: is running within certain color-capable terminals. For instance \kbd{rxvt},
182: \kbd{color\_xterm} and modern versions of \kbd{xterm} under X Windows, or
183: standard Linux/DOS text consoles. It causes GP to use a small palette of
184: colors for its output. With xterms, the colormap used corresponds to the
185: resources \kbd{Xterm*color$n$} where $n$ ranges from $0$ to $15$ (see the
186: file \kbd{misc/color.dft} for an example). Legal values for this default are
187: strings \kbd{"$a_1$,\dots,$a_k$"} where $k\le7$ and each $a_i$ is either
188:
189: \noindent $\bullet$ the keyword \kbd{no} (use the default color, usually
190: black)
191:
192: \noindent $\bullet$ an integer between 0 and 15 corresponding to the
193: aforementioned colormap
194:
195: \noindent $\bullet$ a triple $[c_0,c_1,c_2]$ where $c_0$ stands for foreground
196: color, $c_1$ for background color, and $c_2$ for attributes (0 is default, 1
197: is bold, 4 is underline).
198:
199: The output objects thus affected are respectively error messages,
200: history numbers, prompt, input line, output, help messages, timer (that's
201: seven of them). If $k < 7$, the remaining $a_i$ are assumed to be $no$. For
202: instance
203: %
204: \bprog%
205: default(colors,"9, 5, no, no, 4")
206: \eprog
207: \noindent
208: typesets error messages in color $9$, history numbers in color $5$, output in
209: color $4$, and does not affect the rest.
210:
211: \emacs{In the present version, this default is incompatible with Emacs.
212: Changing it will just fail silently (the alternative would be to display
213: escape sequences as is, since Emacs will refuse to interpret them). On the
214: other hand, you can customize highlighting in your \kbd{.emacs} so as to mimic
215: exactly this behaviour. See \kbd{emacs/pariemacs.txt}.}
216:
217: If you use an old \kbd{readline} library (version number less than 2.0),
218: you should do as in the example above and leave $a_3$ and $a_4$ (prompt
219: and input line) strictly alone. Since old versions of \kbd{readline} did
220: not handle escape characters correctly (or more accurately, treated them
221: in the only sensible way since they did not care to check all your terminal
222: capabilities: it just ignored them), changing them would result in many
223: annoying display bugs.
224:
225: The hacker's way to check if this is the case would be to look in the
226: \kbd{readline.h} include file (wherever your readline include files are) for
227: the string \kbd{RL\_PROMPT\_START\_IGNORE}. If it's there, you are safe.
228:
229: A more sensible way is to make some experiments, and get a more recent
230: \kbd{readline} if yours doesn't work the way you'd like it to. See the file
231: \kbd{misc/gprc.dft} for some examples.
232:
233: \subsecidx{compatible} (default \kbd{0}): The GP function names and syntax have
234: changed tremendously between versions 1.xx and 2.00. To help you cope with this
235: we provide some kind of backward compatibility, depending on the value of
236: this default:
237:
238: \quad \kbd{compatible} = 0: no backward compatibility. In this mode, a very
239: handy function, to be described in \secref{se:whatnow}, is \kbd{whatnow},
240: which tells you what has become of your favourite functions, which GP
241: suddenly can't seem to remember.
242:
243: \quad \kbd{compatible} = 1: warn when using obsolete functions, but otherwise
244: accept them. The output uses the new conventions though, and there may be
245: subtle incompatibilities between the behaviour of former and current
246: functions, even when they share the same name (the current function is used in
247: such cases, of course!). We thought of this one as a transitory help for GP
248: old-timers. Thus, to encourage switching to \kbd{compatible}=0, it is not
249: possible to disable the warning.
250:
251: \quad \kbd{compatible} = 2: use only the old function naming scheme (as used up
252: to version 1.39.15), but {\it taking case into account}. Thus \kbd{I}
253: (${}=\sqrt{-1}$) is not the same as \kbd{i} (user variable, unbound by
254: default), and you won't get an error message using \kbd{i} as a loop index
255: as used to be the case.
256:
257: \quad \kbd{compatible} = 3: try to mimic exactly the former behaviour. This is
258: not always possible when functions have changed in a fundamental way. But
259: these differences are usually for the better (they were meant to, anyway), and
260: will probably not be discovered by the casual user.
261:
262: One adverse side effect is that any user functions and aliases that have been
263: defined {\it before\/} changing \kbd{compatible} will get erased if this
264: change modifies the function list, i.e.~if you move between groups $\{0,1\}$
265: and $\{2,3\}$ (variables are unaffected). We of course strongly encourage you
266: to try and get used to the setting \kbd{compatible}=0.
267:
268: \subsecidx{debug} (default \kbd{0}): debugging level. If it is non-zero, some
269: extra messages may be printed (some of it in French), according to what is
270: going on (see~\b{g}).
271:
272: \subsecidx{debugfiles} (default \kbd{0}): file usage debugging level. If it is
273: non-zero, GP will print information on file descriptors in use, from PARI's
274: point of view (see~\b{gf}).
275:
276: \subsecidx{debugmem} (default \kbd{0}): memory debugging level. If it is
277: non-zero, GP will regularly print information on memory usage. If it's
278: greater than 2, it will indicate any important garbage collecting and the
279: function it is taking place in (see~\b{gm}).
280:
281: \noindent {\bf Important Note:} As it noticeably slows down the performance
282: (and triggers bugs in a popular compiler), the first functionality (memory
283: usage) is disabled if you're not running a version compiled for debugging
284: (see Appendix~A).
285:
286: \subsecidx{echo} (default \kbd{0}): this is a toggle, which can be either 1
287: (on) or 0 (off). When \kbd{echo} mode is on, each command is reprinted before
288: being executed. This can be useful when reading a file with the \b{r} or
289: \kbd{read} commands. For example, it is turned on at the beginning of the test
290: files used to check whether GP has been built correctly (see \b{e}).
291:
292: \subsecidx{format} (default \kbd{"g0.28"} and \kbd{"g0.38"} on 32-bit and
293: 64-bit machines, respectively): of the form x$m.n$, where x is a letter in
294: $\{\kbd{e},\kbd{f},\kbd{g}\}$, and $n$, $m$ are integers. If x is \kbd{f},
295: real numbers will be printed in \idx{fixed floating point format} with no
296: explicit exponent (e.g.~\kbd{0.000033}); if the letter is \kbd{e}, they will be
297: printed in \idx{scientific format}, always with an explicit exponent (e.g.
298: \kbd{3.3e-5}). If the letter is \kbd{g}, real numbers will be printed in
299: \kbd{f} format, except when their absolute value is less than $2^{-32}$,
300: in which case they are printed in \kbd{e} format. \label{se:format}
301:
302: The number $n$ is the number of significant digits printed for real
303: numbers, except if $n<0$ where all the significant digits will be printed
304: (initial default 28, or 38 for 64-bit machines), and the number $m$ is the
305: number of characters to be used for printing integers, but is ignored if
306: equal to 0 (which is the default). This is a feeble attempt at formatting.
307:
308: \subsecidxunix{help} (default: the location of the \kbd{gphelp} script): the
309: name of the external help program which will be used from within GP when
310: extended help is invoked, usually through a \kbd{??} or \kbd{???} request
311: (see \secref{se:exthelp}), or \kbd{M-H} under readline (see
312: \secref{se:readline}).
313:
314: \subsecidx{histsize} (default \kbd{5000}): GP keeps a history of the last
315: \kbd{histsize} results computed so far, which you can recover using the
316: \kbd{\%} notation (see \secref{se:history}). When this number is exceeded,
317: the oldest values are erased. Tampering with this default is the only way to
318: get rid of the ones you don't need anymore.
319:
320: \subsecidx{lines} (default \kbd{0}): if set to a positive value, GP prints at
321: most that many lines from each result, terminating the last line shown with
322: \kbd{[+++]} if further material has been suppressed. The various \kbd{print}
323: commands (see \secref{se:gp_program}) are unaffected, so you can always type
324: \kbd{print(\%)}, \b{a}, or \b{b} to view the full result. If the actual
325: screen width cannot be determined, a ``line'' is assumed to be 80 characters
326: long.
327:
328: \subsecidx{log} (default \kbd{0}): this is a toggle, which can be either 1
329: (on) or 0 (off). When logging mode is turned on, GP opens a log file, whose
330: exact name is determined by the \kbd{logfile} default. Subsequently, all the
331: commands and results will be written to that file (see \b{l}). In case a file
332: with this precise name already existed, it will not be erased: your data will
333: be {\it appended\/} at the end.
334:
335: \subsecidx{logfile} (default \kbd{"pari.log"}): name of the log file to be
336: used when the \kbd{log} toggle is on. Tilde and time expansion are performed.
337:
338: \subsecidx{output} (default \kbd{1}): this can take any of the following three
339: values: 0 (=~{\it raw\/}), 1 (=~{\it prettymatrix\/}), or 2
340: (=~{\it prettyprint\/}). This means that, independently of the default
341: \kbd{format} for reals which we explained above, you can print results in
342: three ways: either in {\it raw\/}\sidx{raw format} format, i.e.~a format
343: which is equivalent to what you input, including explicit multiplication
344: signs, and everything typed on a line instead of two dimensional boxes. This
345: can have several advantages, for instance it allows you to pick the result
346: with a mouse or an editor, and to put it somewhere else.\label{se:output}
347:
348: The second format is the {\it prettymatrix\/}\sidx{prettymatrix format} format.
349: The only difference to raw format is that matrices are printed as boxes
350: instead of horizontally. This is prettier, but takes more space and cannot be
351: used for input. Column vectors are still printed horizontally.
352:
353: The third format is the {\it prettyprint\/}\sidx{prettyprint format} or
354: beautified format. In the present version \vers, this is not beautiful at
355: all.
356:
357: Independently of the setting of this default, an object can be printed
358: in any of the three formats at any time using the commands \b{a}, \b{m}
359: and~\b{b} respectively (see below).
360:
361: \subsecidx{parisize} (default, 1000000 bytes on the Mac, 4000000 otherwise):
362: GP, and in fact any program using the PARI library, needs a stack in which to
363: do its computations. \kbd{parisize} is the stack size, in bytes. It is
364: strongly recommended you increase this default (using the \kbd{-s}
365: command-line switch, or a \kbd{gprc}) if you can afford it. In case of
366: emergency, you can use the \tet{allocatemem} function to increase
367: \kbd{parisize}, once the session is started. GP will try to {\it double\/} the
368: stack size by itself when memory runs low during a computation, but
369: this very computation will then be lost, and you will have to type the
370: command again.
371:
372: \subsecidx{path} (default \kbd{".:\til:\til/gp"} on UNIX systems,
373: \kbd{".;C:\bs;C:\bs GP} on DOS, OS/2 and Windows, and \kbd{"."} otherwise):
374: This is a list of directories, separated by colons ':' (semicolons ';' in the
375: DOS world, since colons are pre-empted for drive names). When asked to read a
376: file whose name does not contain \kbd{/} (i.e.~no explicit path was given),
377: GP will look for it in these directories, in the order they were written in
378: \kbd{path}. Here, as usual, '.' means the current directory, and '$.\,.$' its
379: immediate parent. Tilde expansion is performed.
380:
381: \subsecidx{primelimit} (default \kbd{200000} on the Mac, and \kbd{500000}
382: otherwise): GP precomputes a list of all primes less than \kbd{primelimit} at
383: initialization time. These are used by many arithmetical functions.
384: If you don't plan to invoke any of them, you can just set this to 1.
385:
386: \subsecidx{prompt} (default \kbd{"? "}): a string that will be printed as
387: prompt. Note that most usual escape sequences are available there: \b{e} for
388: Esc, \b{n} for Newline, \dots, \kbd{\bs\bs} for \kbd{\bs}. Time expansion is
389: performed.
390:
391: This string is sent through the library function \kbd{\idx{strftime}} (on a
392: Unix system, you can try \kbd{man strftime} at your shell prompt). This means
393: that \kbd{\%} constructs have a special meaning, usually related to the time
394: and date. For instance, \kbd{\%H} = hour (24-hour clock) and \kbd{\%M} =
395: minute [00,59] (use \kbd{\%\%} to get a real \kbd{\%}).
396:
397: If you use \kbd{readline}, escape sequences in your prompt will result in
398: display bugs. If you have a relatively recent \kbd{readline} (see the comment
399: at the end of \secref{se:colors}), you can brace them with special sequences
400: (\kbd{\bs[} and \kbd{\bs]}), and you will be safe. If these just result in
401: extra spaces in your prompt, then you'll have to get a more recent
402: \kbd{readline}. See the file \kbd{misc/gprc.dft} for an example.
403:
404: \emacs {\bf Caution}: Emacs needs to know about the prompt pattern to
405: separate your input from previous GP results, without ambiguity. It's not a
406: trivial problem to adapt automatically this regular expression to an
407: arbitrary prompt (which can be self-modifying!). Thus, in this version \vers,
408: Emacs relies on the prompt being the default one. So, do not tamper with the
409: \kbd{prompt} variable {\it unless\/} you modify it simultaneously in your
410: \kbd{.emacs} file (see \kbd{emacs/pariemacs.txt} and \kbd{misc/gprc.dft} for
411: examples).
412:
413: \subsecidx{psfile} (default \kbd{"pari.ps"}): name of the default file where
414: GP is to dump its PostScript drawings (these will always be appended, so that
415: no previous data are lost). Tilde and time expansion are performed.
416:
417: \subsecidx{realprecision} (default \kbd{28} and \kbd{38} on 32-bit and 64-bit
418: machines respectively): the number of significant digits and, at the same
419: time, the number of printed digits of real numbers (see~\b{p}). Note that
420: PARI internal precision works on a word basis (32 or 64 bits), hence may not
421: coincide with the number of decimal digits you input. For instance to get 2
422: decimal digits you need one word of precision which, on a 32-bit machine,
423: actually gives you 9 digits ($9 < \log_{10}(2^{32}) < 10$):
424:
425: \bprog%
426: ? default(realprecision, 2)
427: \q realprecision = 9 significant digits (2 digits displayed)
428: \eprog
429:
430: \subsecidx{secure} (default \kbd{0}): this is a toggle which can be either 1
431: (on) or 0 (off). If on, the \tet{system} and \tet{extern} command are
432: disabled. These two commands are potentially dangerous when you execute
433: foreign scripts since they let GP execute arbitrary UNIX commands. GP will
434: ask for confirmation before letting you (or a script) unset this toggle.
435:
436: \subsecidx{seriesprecision} (default \kbd{16}): precision of power series
437: (see~\b{ps}).
438:
439: \subsecidx{simplify} (default \kbd{1}): this is a toggle which can be either
440: 1 (on) or 0 (off). When the PARI library computes something, the type of the
441: result is not always the simplest possible. The only type conversions which
442: the PARI library does automatically are rational numbers to integers (when
443: they are of type \typ{FRAC} and equal to integers), and similarly rational
444: functions to polynomials (when they are of type \typ{RFRAC} and equal to
445: polynomials). This feature is useful in many cases, and saves time, but can
446: be annoying at times. Hence you can disable this and, whenever you feel like
447: it, use the function \kbd{simplify} (see Chapter 3) which allows you to
448: simplify objects to the simplest possible types recursively (see~\b{y}).
449: \sidx{automatic simplification}
450:
451: \subsecidx{strictmatch} (default \kbd{1}): this is a toggle which can be
452: either 1 (on) or 0 (off). If on, unused characters after a sequence has been
453: processed will produce an error. Otherwise just a warning is printed. This
454: can be useful when you're not sure how many parentheses you have to close after
455: complicated nested loops.
456:
457: \subsecidx{timer} (default \kbd{0}): this is a toggle which can be either 1
458: (on) or 0 (off). If on, every instruction sequence (anything ended by a
459: newline in your input) is timed, to some accuracy depending on the hardware
460: and operating system. The time measured is the user \idx{CPU time},
461: {\it not\/} including the time for printing the results (see \kbd{\#} and
462: \kbd{\#\#}).
463:
464: \subsec{Note on output formats.}
465:
466: \noindent
467: A zero real number is printed in \kbd{e} format as $0.Exx$ where $xx$ is
468: the (usually negative) {\it decimal\/} exponent of the number (cf.\ %
469: \secref{se:whatzero}). This allows the user to check the accuracy of the zero
470: in question (this could also be done using \b{x}, but that would be more
471: technical).
472:
473: When the integer part of a real number $x$ is not known exactly because the
474: exponent of $x$ is greater than the internal precision, the real number is
475: printed in \kbd{e} format (note that in versions before 1.38.93, this was
476: instead printed with a $*$ at the end).
477:
478: Note also that in beautified format, a number of type integer or real is
479: written without enclosing parentheses, while most other types have them.
480: Hence, if you see the expression $( 3.14 )$, it is not of type real, but
481: probably of type complex with zero imaginary part (if you want to be sure, type
482: \b{x} or use the function \kbd{type}).
483:
484: \section{Simple metacommands}\label{se:meta}
485:
486: \noindent
487: Simple metacommands are meant as shortcuts and should not be used in GP
488: scripts (see \secref{se:programming}). Beware that these, as all of GP input,
489: are now {\it case sensitive}. For example, \b{Q} is no longer identical to
490: \b{q}. In the following list, braces are used to denote optional arguments,
491: with their default values when applicable, e.g.~$\{n=0\}$ means that if $n$
492: is not there, it is assumed to be~$0$. Whitespace (or spaces) between the
493: metacommand and its arguments and within arguments is optional. (This can
494: cause problems only with \b{w}, when you insist on having a filename whose
495: first character is a digit, and with \b{r} or \b{w}, if the filename itself
496: contains a space. In such cases, just use the underlying \kbd{read} or
497: \kbd{write} function; see~\secref{se:write}).
498:
499: \subseckbd{?} $\{{\it command}\}$: GP on-line help interface.
500: As already mentioned, if you type \kbd{?$n$} where $n$ is a number from 1
501: to 11, you will get the list of functions in Section $3.n$ of the manual
502: (the list of sections being obtained by simply typing \kbd{?}).
503: \label{se:exthelp}
504:
505: These names are in general not informative enough. More details can be
506: obtained by typing \kbd{?{\it function}}, which gives a short explanation of
507: the function's calling convention and effects. Of course, to have complete
508: information, read Chapter 3 of this manual (the source code is at your
509: disposal as well, though a trifle less readable!). Much better help can be
510: obtained through the extended help system (see below).
511:
512: You then get the function description exactly as it stands
513: in Chapter 3. All operators (e.g.~\kbd{+}, \kbd{\&\&}, etc.) are accepted
514: by this extended help, as well as a few other keywords describing key GP
515: concepts, e.g.~\kbd{readline} (the line editor), \kbd{integer}, \kbd{nf}
516: (``number field'' as used in most algebraic number theory computations),
517: \kbd{ell} (elliptic curves), etc.
518:
519: \unix If the line before the copyright message indicates that extended help
520: is available (this means \kbd{perl} is installed on your system, GP was
521: told about it at compile time, and the whole PARI distribution was
522: correctly installed), you can add more \kbd{?} signs for extended
523: functionalities:
524:
525: \kbd{??~\var{keyword}} yields the functions description as it stands in this
526: manual, usually in Chapter~2 or~3. If you're not satisfied with the default
527: chapter chosen, you can impose a given chapter by ending the keyword with
528: \kbd{@} followed by the chapter number, e.g.~\kbd{??~Hello@2} will look in
529: Chapter~2 for section heading \kbd{Hello} (which doesn't exist, by the way).
530:
531: \kbd{???~\var{pattern}} produces a list of sections in Chapter~3 of the
532: manual related to your query. As before, if \var{pattern} ends by \kbd{@}
533: ifollowed by a chapter number, that chapter is searched instead; you also
534: have the option to append a simple \kbd{@} (without a chapter number) to
535: browse through the whole manual.
536:
537: If your query contains dangerous characters (e.g \kbd{?} or blanks) it is
538: advisable to enclose it within double quotes, as for GP strings (e.g
539: \kbd{???~"elliptic curve"}).
540:
541: Note that extended help is much more powerful than the short help, since
542: it knows about operators as well: you can type \kbd{??~*} or
543: \kbd{??~\&\&}, whereas a single \kbd{?} would just yield a not too helpful
544:
545: \kbd{*** unknown identifier.}
546:
547: \noindent message. Also, you can ask for extended help on section
548: number~$n$ in Chapter~3, just by typing \kbd{??~$n$} (where \kbd{?$n$} would
549: yield merely a list of functions). Finally, a few key concepts in GP are
550: documented in this way: metacommands (e.g \kbd{??~"??"}), defaults (e.g
551: \kbd{??~psfile}) and type names (e.g \typ{INT} or \kbd{integer}), as well as
552: various miscellaneous keywords such as \kbd{edit} (short summary of line
553: editor commands), \kbd{operator}, \kbd{member}, \kbd{"user defined"},
554: \kbd{nf}, \kbd{ell}, \dots
555:
556: Last but not least~: \kbd{??} without argument will open a \kbd{dvi}
557: previewer (\kbd{xdvi} by default, \kbd{\$GPXDVI} if it is defined in your
558: environment) containing the full user's manual. \kbd{??tutorial} and
559: \kbd{??refcard} do the same with the \idx{tutorial} and \idx{reference card}
560: respectively.
561:
562: \misctitle{Technical note:} these functionalities are provided by an
563: external \kbd{perl} script that you are free to use outside any GP session
564: (and modify to your liking, if you are perl-knowledgeable). It is called
565: \kbd{\idx{gphelp}}, lies in the \kbd{doc} subdirectory of your distribution
566: (just make sure you run \kbd{Configure} first, see Appendix~A) and is
567: really two programs in one. The one which is used from within GP is
568: \kbd{gphelp} which runs \TeX\ on a selected part of this manual, then opens
569: a previewer. \kbd{gphelp -detex} is a text mode equivalent, which looks
570: often nicer especially on a colour-capable terminal (see
571: \kbd{misc/gprc.dft} for examples). The default \kbd{help} selects which
572: help program will be used from within GP. You are welcome to improve this
573: help script, or write new ones (and we really would like to know about it
574: so that we may include them in future distributions). By the way, outside
575: of GP you can give more than one keyword as argument to \kbd{gphelp}.
576:
577: \subseckbd{/*...*/}: comment. Everything between the stars is ignored by
578: GP. These comments can span any number of lines.
579:
580: \subseckbd{\bs\bs}: one-line comment. The rest of the line
581: is ignored by GP.
582:
583: \subsec{\b{a}} $\{n\}$: prints the object number $n$ ($\%n$)
584: in raw format. If the number $n$ is omitted, print the latest computed object
585: ($\%$). \label{se:history}
586:
587: \subsec{\b{b}} $\{n\}$: Same as \b{a}, in prettyprint (i.e.~beautified)
588: format.
589:
590: \subsec{\b{c}}:\sidx{available commands} prints the list of all available
591: hardcoded functions under GP, not including operators written as special
592: symbols (see \secref{se:operators}). More information can be obtained using
593: the \kbd{?} metacommand (see above). For user-defined functions / member
594: functions, see \b{u} and \b{um}.
595:
596: \subsec{\b{d}}: prints the \idx{defaults} as described in the
597: previous section (shortcut for \kbd{default()}, see \secref{se:default}).
598:
599: \subsec{\b{e}} $\{n\}$: switches the \kbd{echo} mode on (1) or off (0). If
600: $n$ is explicitly given, set echo to $n$.
601:
602: \subsec{\b{g}} $\{n\}$: sets the debugging level \kbd{debug} to the
603: non-negative integer $n$.
604:
605: \subsec{\b{gf}} $\{n\}$: sets the file usage debugging level \kbd{debufiles}
606: to the non-negative integer $n$.
607:
608: \subsec{\b{gm}} $\{n\}$: sets the memory debugging level \kbd{debugmem}
609: to the non-negative integer $n$.
610:
611: \subsec{\b{h}} $\{m$\kbd{-}$n\}$: outputs some debugging info about the
612: hashtable. If the argument is a number $n$, outputs the contents of cell
613: $n$. Ranges can be given in the form $m$\kbd{-}$n$ (from cell $m$ to cell
614: $n$, \$ = last cell). If a function name is given instead of a number or
615: range, outputs info on the internal structure of the hash cell this
616: function occupies (a \kbd{struct entree} in C). If the range is reduced to
617: a dash ('\kbd{-}'), outputs statistics about hash cell usage.
618:
619: \subsec{\b{l}} $\{${\it logfile/}$\}$: switches \kbd{log} mode on and off.
620: If a {\it logfile} argument is given, change the default logfile name to
621: {\it logfile} and switch log mode on.
622:
623: \subsec{\b{m}}: as \b{a}, but using prettymatrix format.
624:
625: \subsec{\b{p}} $\{n\}$: sets \kbd{realprecision} to $n$ decimal
626: digits. Prints its current value if $n$ is omitted.
627:
628: \subsec{\b{ps}} $\{n\}$: sets \kbd{seriesprecision} to $n$ significant terms.
629: Prints its current value if $n$ is omitted.
630:
631: \subsec{\b{q}}: \idx{quit}s the GP session and returns to the system.
632: Shortcut for the function \kbd{quit} (see \secref{se:quit}).
633:
634: \subsec{\b{r}} $\{${\it filename\/}$\}$: \idx{read}s into GP all the commands
635: contained in the named file as if they had been typed from the keyboard, one
636: line after the other. Can be used in combination with the \b{w} command (see
637: below). Related but not equivalent to the function \kbd{read} (see
638: \secref{se:read}); in particular, if the file contains more than one line of
639: input, there will be one history entry for each of them, whereas \kbd{read}
640: would only record the last one. If {\it filename\/} is omitted, re-read the
641: previously used input file (fails if no file has ever been successfully read
642: in the current session).
643:
644: \unix This command accepts compressed files in \idx{compress}ed (\kbd{.Z})
645: or \idx{gzip}ped (\kbd{.gz} or \kbd{.z}) format. They will be uncompressed on
646: the fly as GP reads them, without changing the files themselves.
647:
648: \subsec{\b{s}}: prints the state of the PARI \idx{stack} and \idx{heap}.
649: This is used primarily as a debugging device for PARI, and is not intended
650: for the casual user.
651:
652: \subsec{\b{t}}: prints the \idx{internal longword format} of all the PARI
653: types. The detailed bit or byte format of the initial codeword(s) is
654: explained in Chapter~4, but its knowledge is not necessary for a GP user.
655:
656: \subsec{\b{u}}: prints the definitions of all user-defined functions.
657:
658: \subsec{\b{um}}: prints the definitions of all user-defined member functions.
659:
660: \subsec{\b{v}}: prints the \idx{version number} and implementation architecture
661: (680x0, Sparc, Alpha, other) of the GP executable you are using. In library
662: mode, you can use instead the two character strings \kbd{PARIVERSION} and
663: \kbd{PARIINFO}, which correspond to the first two lines printed by GP just
664: before the Copyright message.
665:
666: \subsec{\b{w}} $\{n\}$ $\{${\it filename\/}$\}$: \idx{write}s the object number
667: $n$ ( $\%n$ ) into the named file, in raw format. If the number $n$ is
668: omitted, writes the latest computed object ( $\%$ ). If {\it filename\/} is
669: omitted, appends to \kbd{logfile} (the GP function \kbd{write} is a trifle more
670: powerful, as you can have filenames whose first character is a digit).
671:
672: \subsec{\b{x}}: prints the complete tree with addresses and contents (in
673: hexadecimal) of the \idx{internal representation} of the latest computed
674: object in GP. As for \b{s}, this is used primarily as a debugging device for
675: PARI. However, used on a PARI integer, it can be used as a
676: decimal$\rightarrow$hexadecimal converter.
677:
678: \subsec{\b{y}} $\{n\}$: switches \kbd{simplify} on (1) or off (0). If $n$
679: is explicitly given, set simplify to $n$.
680:
681: \subseckbd{\#}: switches the \kbd{timer} on or off.
682:
683: \subseckbd{\#\#}: prints the time taken by the latest computation.
684: Useful when you forgot to turn on the \kbd{timer}.
685:
686: \section{Input formats for the PARI types}
687:
688: \noindent
689: Before describing more sophisticated functions in the next section, let us
690: see here how to input values of the different data types known to PARI.
691: Recall that blanks are ignored in any expression which is not a string (see
692: below).
693:
694: \subsec{Integers} \sidx{integer}
695: (type \typ{INT}\idxtyp{INT}): type the integer (with an initial
696: \kbd{+} or \kbd{-}, if desired) with no decimal point.
697:
698: \subsec{Real numbers} \sidx{real number}
699: (type \typ{REAL}\idxtyp{REAL}): type the number with a decimal
700: point. The internal precision of the real number will be the supremum of the
701: input precision and the default precision. For example, if the default
702: precision is 28 digits, typing \kbd{2.} will give a number with internal
703: precision 28, but typing a 45 significant digit real number will give a
704: number with internal precision at least 45 (although less may be printed).
705:
706: You can also use scientific notation with the letter \kbd{E} or
707: \kbd{e} (like \kbd{6.02 E 23} or \kbd{1e-5}).
708:
709: \subsec{Integermods}\sidx{integermod}
710: (type \typ{INTMOD}\idxtyp{INTMOD}): to enter $n \mod m$, type
711: \kbd{Mod(n,m)}, {\it not\/} \kbd{n\%m} (see Chapter~3).
712:
713: \subsec{Rational numbers}\sidx{rational number}
714: (types \typ{FRAC}\idxtyp{FRAC} and
715: \typ{FRACN}\idxtyp{FRACN}): under GP, all fractions are
716: automatically reduced to lowest terms, so it is in principle impossible to
717: work with reducible fractions (of type \typ{FRACN}), although of course in
718: library mode this is easy. To enter $n/m$ just type it as written. As
719: explained in \secref{se:gdiv}, division will {\it not\/} be performed, only
720: reduction to lowest terms.\label{se:FRAC}
721:
722: If you really want a reducible fraction under GP, you must use the \kbd{type}
723: function (see \secref{se:gptype}), by typing \kbd{type(x,FRACN)}. Be warned
724: however that this function must be used with extreme care.
725:
726: \subsec{Complex numbers}\sidx{complex number}
727: (type \typ{COMPLEX}\idxtyp{COMPLEX}): to enter $x+iy$, type \kbd{x + I*y}
728: ({\it not\/} \kbd{x+i*y}). The letter \kbd{\idx{I}} stands for
729: $\sqrt{-1}$. Recall from Chapter 1 that $x$ and $y$ can be of type
730: \typ{INT}, \typ{REAL}, \typ{INTMOD}, \typ{FRAC}/\typ{FRACN}, or
731: \typ{PADIC}.
732:
733: \subsec{$p$-adic numbers}\sidx{p-adic number}\label{se:padic}
734: (type \typ{PADIC}\idxtyp{PADIC}): to enter a $p$-adic number, simply write a
735: rational or integer expression and add to it \kbd{O($p$\pow $k$)}, where $p$
736: and $k$ are integers. This last expression indicates three things to GP:
737: first that it is dealing with a \typ{PADIC} type (the fact that $p$ is an
738: integer, and not a polynomial, which would be used to enter a series, see
739: \secref{se:series}), secondly the ``prime'' $p$ (note that it is not
740: checked whether $p$ is indeed prime; you can work on 10-adics if you want, but
741: beware of disasters as soon as you do something non-trivial like taking a
742: square root), and finally the number of significant $p$-adic digits $k$.
743: Note that \kbd{O(25)} is not the same as \kbd{O(5\pow 2)}; you probably
744: want the latter!
745:
746: For example, you can type in the $7$-adic number
747:
748: \kbd{2*7\pow(-1) + 3 + 4*7 + 2*7\pow 2 + O(7\pow3)}
749:
750: \noindent
751: exactly as shown, or equivalently as
752: \kbd{905/7 + O(7\pow3)}.
753:
754: \subsec{Quadratic numbers}\sidx{quadratic number}
755: (type \typ{QUAD}\idxtyp{QUAD}): first, you must define the
756: default quadratic order or field in which you want to work. This is done
757: using the \kbd{\idx{quadgen}} function, in the following way. Write something
758: like
759:
760: \kbd{w = quadgen(d)}
761:
762: \noindent
763: where \kbd{d} is the {\it discriminant\/} of the quadratic order in
764: which you want to work (hence $d$ is congruent to $0$ or $1$ modulo $4$). The
765: name \kbd{w} is of course just a suggestion, but corresponds to traditional
766: usage. You can of course use any variable name that you like. However,
767: quadratic numbers are always printed with a \kbd{w}, regardless of the
768: discriminant. So beware, two numbers can be printed in the same way and not
769: be equal. However GP will refuse to add or multiply them for example.
770:
771: Now $(1,w)$ will be the ``canonical'' integral basis of the quadratic order
772: (i.e.~$w=\sqrt{d}/2$ if $d\equiv 0 \mod 4$, and $w=(1+\sqrt{d})/2$ if
773: $d\equiv 1 \mod 4$, where $d$ is the discriminant), and to enter $x+yw$ you
774: just type \kbd{x + y*w}.
775:
776: \subsec{Polmods}\sidx{polmod} (type \typ{POLMOD}\idxtyp{POLMOD}): exactly as
777: for integermods, to enter $x \mod y$ (where $x$ and $y$ are polynomials),
778: type \kbd{Mod(x,y)}, not \kbd{x\%y} (see \secref{se:Mod}). Note that when $y$
779: is an irreducible polynomial in one variable, polmods whose modulus is $y$
780: are simply algebraic numbers in the finite extension defined by the
781: polynomial $y$. This allows us to work easily in \idx{number field}s, finite
782: extensions of the $p$-adic field $\Q_p$, or \idx{finite field}s.
783:
784: \label{se:rempolmod}
785: \misctitle{Important remark.} Since the variables\sidx{variable} occurring
786: in a polmod are not free variables, it is essential in order to avoid
787: inconsistencies that polmods use the same variable in internal operations
788: (i.e.~between polmods) and variables of lower priority (which have been
789: introduced later in the GP session) for external operations (typically
790: between a polynomial and a polmod). For example, PARI will not recognize
791: that \kbd{Mod(y, y\pow2 + 1)} is the same as \kbd{Mod(x, x\pow2 + 1)}.
792: Hopefully, this problem will pass away when type ``element of a number
793: field'' is eventually introduced.
794:
795: On the other hand, \kbd{Mod(x, x\pow2 + 1) + Mod(x, x\pow2 + 1)}
796: (which gives \kbd{Mod(2*x, x\pow2 + 1)}) and \kbd{x + Mod(y, y\pow2 + 1)}
797: (which gives a result mathematically equivalent to $\kbd{x} + i$ with
798: $i^2=-1$) are completely correct, while \kbd{y + Mod(x, x\pow2 + 1)}
799: gives \kbd{Mod(x + y, x\pow2 + 1)}, which may not be what you want (\kbd{y}
800: is treated here as a numerical parameter, not as a polynomial variable).
801:
802: \misctitle{Note (added in version 2.0.16)} As long as the main variables
803: are the same, it is allowed to mix \typ{POL} and \typ{POLMOD}s. The result
804: will be the expected \typ{POLMOD}. For instance \kbd{x + Mod(x, x\pow2 +
805: 1)} is equal to \kbd{Mod(2*x, x\pow2 + 1)}. This wasn't the case prior to
806: version 2.0.16: it returned a polynomial in \kbd{x} equivalent to $\kbd{x}
807: + i$, which was in fact an invalid object (you couldn't \kbd{lift} it).
808:
809: \subsec{Polynomials}\sidx{polynomial}\label{se:pol}
810: (type \typ{POL}\idxtyp{POL}): type the polynomial in a natural way, not
811: forgetting to put a ``$*$'' between a coefficient and a formal variable
812: (this $*$ does not appear in beautified output). Any \idx{variable} name
813: can be used except for the reserved names \kbd{I} (used exclusively for the
814: square root of $-1$), \kbd{Pi} ($3.14\dots$), \kbd{Euler} (Euler's
815: constant), and all the function names: predefined functions, as described
816: in Chapter~3 (use \b{c} to get the complete list of them) and user-defined
817: functions, which you ought to know about (use \b{u} if you are subject to
818: memory lapses). The total number of different variable names is limited to
819: $16384$ and $65536$ on 32-bit and 64-bit machines respectively, which
820: should be enough. If you ever need hundreds of variables, you should
821: probably be using vectors instead.
822:
823: \subsec{Power series}\sidx{power series}\label{se:series}
824: (type \typ{SER}\idxtyp{SER}): type a rational function or
825: polynomial expression and add to it \hbox{\kbd{O({\it expr\/} \pow $k$)}},
826: where {\it expr\/} is an expression which has non-zero valuation (it can be a
827: polynomial, power series, or a rational function; the most common case being
828: simply a variable name).
829: This indicates to GP that it is dealing with a power series, and the desired
830: precision is $k$ times the valuation of {\it expr\/} with respect to the
831: main variable of {\it expr\/} (to check the ordering of the variables, or
832: to modify it, use the function \kbd{reorder}; see~\secref{se:reorder}).
833:
834: \subsec{Rational functions}\sidx{rational function}
835: (types \typ{RFRAC}\idxtyp{RFRAC} and
836: \typ{RFRACN}\idxtyp{RFRACN}): as for fractions, all rational
837: functions are automatically reduced to lowest terms under GP. All that was
838: said about fractions in \secref{se:FRAC} remains valid here.
839:
840: \subsec{Binary quadratic forms of positive or negative discriminant}%
841: \sidx{binary quadratic forms}
842: (type \typ{QFR}\idxtyp{QFR} and \typ{QFI}\idxtyp{QFI}):
843: these are input using the function \kbd{Qfb} (see Chapter~3). For example
844: \kbd{Qfb(1,2,3)} will create the binary form $x^2+2xy+3y^2$. It will be
845: imaginary (of internal type \typ{QFI}) since $2^2 - 4*3 = -8$ is negative.
846:
847: In the case of forms with positive discriminant (type \typ{QFR}), you
848: may add an optional fourth component (related to the regulator, more
849: precisely to Shanks and Lenstra's ``distance''), which must be a real number.
850: See also the function \kbd{qfbprimeform} which directly creates a prime form
851: of given discriminant (see Chapter~3).
852:
853: \subsec{Row and column vectors}\sidx{row vector}\sidx{column vector} (types
854: \typ{VEC}\idxtyp{VEC} and \typ{COL}\idxtyp{COL}): to
855: enter a row vector, type the components separated by commas ``\kbd{,}'', and
856: enclosed between brackets ``\kbd{[}$\,$'' and ``$\,$\kbd{]}'', e.g.~%
857: \kbd{[1,2,3]}. To enter a column vector, type the vector horizontally, and
858: add a tilde ``\til'' to transpose. \kbd{[ ]} yields the empty (row) vector.
859: The function \tet{Vec} can be used to transform any object into a vector (see
860: Chapter~3).
861:
862: \subsec{Matrices} (type \typ{MAT}\idxtyp{MAT}):\sidx{matrix} to
863: enter a matrix, type the components line by line, the components being
864: separated by commas ``\kbd{,}'', the lines by semicolons ``\kbd{;}'', and
865: everything enclosed in brackets ``\kbd{[}$\,$'' and ``$\,$\kbd{]}'', e.g.
866: \kbd{[x,y; z,t; u,v]}. \kbd{[ ; ]} yields the empty (0x0) matrix. The
867: function \tet{Mat} can be used to transform any object into a matrix (see
868: Chapter 3).
869:
870: Note that although the internal representation is essentially the same (only
871: the type number is different), a row vector of column vectors is {\it not\/}
872: a matrix; for example, multiplication will not work in the same way.
873:
874: Note also that it is possible to create matrices (by conversion of empty
875: column vectors and concatenation, or using the \kbd{matrix} function) with a
876: given positive number of columns, each of which has zero rows. It is not
877: possible to create or represent matrices with zero columns and a nonzero
878: number of rows.
879:
880: \subsec{Lists} (type \typ{LIST})\idxtyp{LIST}:\sidx{list}
881: lists cannot be input directly; you have to use the function
882: \kbd{listcreate} first, then \kbd{listput} each time you want to append a
883: new element (but you can access the elements directly as with the
884: vector types described above). The function \kbd{List} can be used to
885: transform (row or column) vectors into lists (see Chapter~3).
886:
887: \subsec{Strings} (type \typ{STR})\idxtyp{STR}:\sidx{string}%
888: \sidx{character string} to enter a string, just enclose it between double
889: quotes \kbd{"}, like this: \kbd{"this is a string"}. The function \kbd{Str}
890: can be used to transform any object into a string (see Chapter~3).
891:
892: \section{GP operators}\label{se:operators}
893:
894: \noindent
895: Loosely speaking, an \idx{operator} is a function (usually associated to
896: basic arithmetic operations) whose name contains only non-alphanumeric
897: characters. In practice, most of these are simple functions, which take
898: arguments, and return a value; assignment operators also have side effects.
899: Each of these has some fixed and unchangeable priority, which means that,
900: in a given expression, the operations with the highest priority will be
901: performed first. Operations at the same priority level will always be
902: performed in the order they were written, i.e.~from left to right. Anything
903: enclosed between parenthesis is considered a complete subexpression, and
904: will be resolved independently of the surrounding context. For instance,
905: assuming that {\it op}$_1$, {\it op}$_2$, {\it op}$_3$ are standard binary
906: operators with increasing priorities (think of \kbd{+}, \kbd{*}, \kbd{\pow}
907: for instance),
908: $$ x~\hbox{\it op}_1~y~\hbox{\it op}_2~z~\hbox{\it op}_2~x~\hbox{\it op}_3~y $$
909: is equivalent to
910: $$ x~\hbox{\it op}_1~((y~\hbox{\it op}_2~z)~\hbox{\it op}_2~
911: (x~\hbox{\it op}_3~y)).$$
912:
913: GP knows quite a lot of different operators, some of them unary (having
914: only one argument), some binary. Unary operators are defined for either
915: prefix (preceding their single argument: {\it op\/}~$x$) or postfix (following
916: the argument: $x$~{\it op\/}) position, never both
917: (some are syntactically correct in both positions, but with different
918: meanings). Binary operators all use the syntax $x$~{\it op\/}~$y$. Most of
919: them are well known, some are borrowed from C~syntax, and a few are specific
920: to GP. Beware that some GP operators may differ slightly from their C
921: counterparts. For instance, GP's postfix \kbd{++} returns the {\it new\/}
922: value, like the prefix \kbd{++} of~C, and the binary shifts \kbd{<<},
923: \kbd{>>} have a priority which is different from (higher than) that of
924: their C counterparts.
925: When in doubt, just surround everything by parentheses (besides, your code
926: will probably be more legible).
927:
928: \noindent Here is the complete list (in order of decreasing priority, binary
929: unless mentioned otherwise):
930:
931: \sidx{priority}
932: \def\point#1{\noindent $\bullet$ #1\hfill\break\indent\strut}
933: \point{Priority 9}
934: %
935: \kbd{++} and \kbd{--} (unary, postfix): \kbd{$x$++} assigns the value $x+1$ to
936: $x$, then returns the new value of $x$. This corresponds to the C
937: statement \kbd{++$x$} (there is no prefix \kbd{++} operator in GP).
938: \kbd{$x$--} does the same with $x-1$.
939:
940: \point{Priority 8}
941: %
942: \kbd{{\it op\/}=}, where {\it op\/} is any simple binary operator
943: (i.e.~a binary operator with no side effects, i.e.~one of those defined below)
944: which is not a boolean operator (comparison or logical).
945: \kbd{x~{\it op\/}=~$y$} assigns $(\kbd{x}~{\it op\/}~y)$ to~\kbd{x},
946: and returns the new value of~\kbd{x}, {\it not\/} a reference to the
947: \idx{variable}~\kbd{x}. (Thus an assignment cannot occur on the lefthand
948: side of another assignment.)
949:
950: \point{Priority 7}
951: %
952: \kbd{=} is the assignment operator. The result of \kbd{x~=~$y$} is the value
953: of the expression~$y$, which is also assigned to the variable~\kbd{x}. This
954: is {\it not\/} the equality test operator. Beware that a statement like
955: \kbd{x~=~1} is always true (i.e.~non-zero), and sets \kbd{x} to~1.
956:
957: \point{Priority 6}
958: %
959: \kbd{!} (unary, prefix): logical {\it not}. \kbd{!$x$} return $1$ if $x$ is
960: equal to $0$ (specifically, if \kbd{gcmp0($x$)==1}), and $0$ otherwise.
961:
962: \kbd{'} (unary, prefix): quote its argument without evaluating it.
963: \bprog%
964: ? a = x + 1; x = 1;
965: ? subst(a,x,1)
966: \ \ ***\ \ \ variable name expected: subst(a,x,1)
967: \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \pow---
968: ? subst(a,'x,1)
969: \%1 = 2
970: \eprog
971:
972: \point{Priority 5}
973: %
974: \kbd{\pow}: powering.
975:
976: \kbd{'} (unary, postfix): derivative with respect to the main variable.
977:
978: \strut\kbd{\til} (unary, postfix): vector/matrix transpose.
979:
980: \kbd{!} (unary, postfix): factorial. $x\kbd{!}=x(x-1)\cdots 1$.
981:
982: \kbd{.}: \kbd{$x$.$b$} extracts member $b$ from structure $x$.
983:
984: \point{Priority 4}
985: %
986: \kbd{+}, \kbd{-} (unary, prefix): \kbd{-} toggles the sign of its argument,
987: \kbd{+} has no effect whatsoever.
988:
989: \point{Priority 3}
990: %
991: \kbd{*}: multiplication.
992:
993: \kbd{/}: exact division (\kbd{3/2}=$3/2$, not $1.5$).
994:
995: \kbd{\bs}, \kbd{\%}: euclidean quotient and remainder, i.e.~if $x =
996: qy + r$, with $0\le r < y$ (if $x$ and $y$ are polynomials, assume instead
997: that $\deg r< \deg y$ and that the leading terms of $r$ and $x$ have the
998: same sign), then $\kbd{x \b{ } y} = q$, $\kbd{x\%y} = r$.
999:
1000: \kbd{\bs/}: rounded euclidean quotient for integers (rounded towards
1001: $+\infty$ when the exact quotient would be a half-integer).
1002:
1003: \kbd{<<}, \kbd{>>}: left and right binary shift: \kbd{x<<n}$~=~x * 2^n$
1004: if $n>0$, and $x \b{/} 2^{-n}$ otherwise; and
1005: \kbd{x>>n}$~=~$\kbd{x<<(-n)}.
1006:
1007: \point{Priority 2}
1008: %
1009: \kbd{+}, \kbd{-}: addition/subtraction.
1010:
1011: \point{Priority 1}
1012: %
1013: \kbd{<}, \kbd{>}, \kbd{<=}, \kbd{>=}: the usual comparison operators,
1014: returning 1 for \kbd{true} and 0 for \kbd{false}. For instance,
1015: \kbd{x<=1} returns $1$ if $x\le 1$ and $0$ otherwise.
1016:
1017: \kbd{<>}, \kbd{!=}: test for (exact) inequality.
1018:
1019: \kbd{==}: test for (exact) equality.
1020:
1021: \point{Priority 0}
1022: %
1023: \kbd{\&}, \kbd{\&\&}: logical {\it and}.
1024:
1025: \kbd{|}, \kbd{||}: logical (inclusive) {\it or}. Any sequence of logical
1026: {\it or\/} and {\it and\/} operations is evaluated from left to right,
1027: and aborted as soon as the final truth value is known. Thus, for instance,
1028: \kbd{(x \&\& 1/x)} or \kbd{(type(p) == "t\_INT" \&\& isprime(p))} will never
1029: produce an error since the second argument need not (and will not) be processed
1030: when the first is already zero (false).
1031:
1032: \misctitle{Remark:} For the sake of efficiency, you should use the
1033: \kbd{++}, \kbd{--} and {\it op\/}\kbd{=} operators whenever possible:
1034:
1035: \bprog%
1036: ? a=200000;
1037: ? i=0; while(i<a, i=i+1)
1038: time = 4,919 ms.
1039: ? i=0; while(i<a, i+=1)
1040: time = 4,478 ms.
1041: ? i=0; while(i<a, i++)
1042: time = 3,639 ms.
1043: \eprog
1044:
1045: \noindent The shift operators should be preferred to multiplication
1046: whenever possible:
1047:
1048: \bprog%
1049: ? a=1<<20000;
1050: ? i=1; while(i<a, i=i*2);
1051: time = 5,255 ms.
1052: ? i=1; while(i<a, i<<=1);
1053: time = 988 ms.
1054: \eprog
1055:
1056: \section{The general GP input line}
1057: \subsec{Generalities}. User interaction with a GP session proceeds as
1058: follows: a sequence of characters is typed by the user at the GP prompt. This
1059: can be either a \b~command, a function definition, an expression, or a
1060: sequence of expressions (i.e.~a program). In the latter two cases, after the
1061: last expression has been computed its result is put into an internal
1062: (``history'') array, and printed. The successive elements of this array are
1063: called \kbd{\%1}, \kbd{\%2}, \dots As a shortcut, the latest computed
1064: expression can also be called \kbd{\%}, the previous one \kbd{\%`}, the one
1065: before that \kbd{\%``} and so on.
1066:
1067: If you want to suppress the printing of the result, for example because it
1068: is a long unimportant intermediate result, end the expression with a
1069: \kbd{;} sign. This same sign is used as an instruction separator when several
1070: instructions are written on the same line (note that for the pleasure of BASIC
1071: addicts, the \kbd{:} sign can also be used, but we will try to stick to
1072: C-style conventions in this manual). The final expression computed, even
1073: if not printed, will still be assigned to the history array, so you may have
1074: to pay close attention when you intend to refer back to it by number since
1075: this number does not appear explicitly. Of course, if you just want to use
1076: it on the next line, use \kbd{\%} as usual.
1077:
1078: Any legal expression can be typed in, and is evaluated using the
1079: conventions about operator priorities and left to right associativity (see
1080: the previous section), using the available operator symbols, function names
1081: (including user-defined functions and member functions see
1082: \secref{se:user_defined}), and special variables. Please note that, from
1083: version $1.900$ on, there\sidx{case distinction} {\it is\/} a distinction
1084: between lowercase and uppercase. Also, note that, outside of constant
1085: strings, blanks are completely ignored in the input to GP.
1086:
1087: The special variable\idx{variable (special)} names known to GP are
1088: \kbd{\idx{Euler}} (Euler's constant $\gamma=0.577\dots$), \kbd{\idx{I}}
1089: (the square root of $-1$), \kbd{\idx{Pi}} (3.14\dots)~--- which could be
1090: thought of as functions with no arguments, and which may therefore be
1091: invoked without parentheses~---, and \kbd{\idx{O}} which obeys the
1092: following syntax:
1093:
1094: \kbd{O({\it expr\/}\pow k)}
1095:
1096: \noindent
1097: When {\it expr\/} is an integer or a rational number, this creates an
1098: {\it expr}-adic number (zero in fact) of precision \kbd{k}. When {\it expr\/}
1099: is a polynomial, a power series or a rational function whose main variable is
1100: $X$, say, this creates a power series (also zero) of precision $v*\kbd{k}$
1101: where $v$ is the $X$-adic valuation of {\it expr\/} (see \ref{se:padic}
1102: and~\ref{se:pol}).
1103:
1104: \subsec{Special editing characters}.\sidx{editing characters} A GP program
1105: can of course have more than one line. Since GP executes your commands as
1106: soon as you have finished typing them, there must be a way to tell it to
1107: wait for the next line or lines of input before doing anything. There are
1108: three ways of doing this.
1109:
1110: The first one is simply to use the \idx{backslash character} \kbd{\bs} at the
1111: end of the line that you are typing, just before hitting \kbd{<Return>}. This
1112: tells GP that what you will write on the next line is the physical
1113: continuation of what you have just written. In other words, it makes GP
1114: forget your newline character. For example if you use this while defining a
1115: function, and if you ask for the definition of the function using
1116: \kbd{?name}, you will see that your backslash has disappeared and that
1117: everything is on the same line. You can type a \kbd{\bs} anywhere. It will be
1118: interpreted as above only if (apart from ignored whitespace characters) it is
1119: immediately followed by a newline. For example, you can type
1120:
1121: \bprog%
1122: ? 3 + \bs
1123: 4%
1124: \eprog
1125:
1126: \noindent instead of typing \kbd{3 + 4}.
1127:
1128: The second one is a slight variation on the first, and is mostly useful when
1129: defining a user function (see \secref{se:user_defined}): since an equal sign
1130: can never end a valid expression, GP will disregard a newline immediately
1131: following an \kbd{=}.
1132:
1133: \bprog%
1134: ? a =
1135: 123
1136: \%1 = 123
1137: \eprog
1138:
1139: The third one cannot be used everywhere, but is in general much more useful.
1140: It is the use of braces \kbd{\obr} and \kbd{\cbr}.\sidx{brace characters}
1141: When GP sees an opening brace (\kbd{\obr}) {\it at the beginning of a line}
1142: (modulo spaces as usual), it understands that you are typing a multi-line
1143: command, and newlines will be ignored until you type a closing brace
1144: \kbd{\cbr}. However, there is an important (but easily obeyed) restriction:
1145: inside an open brace-close brace pair, all your input lines will be
1146: concatenated, suppressing any newlines. Thus, all newlines should occur after
1147: a semicolon (\kbd{;}), a comma (\kbd{,}) or an operator (for clarity's sake,
1148: we don't recommend splitting an identifier over two lines in this way). For
1149: instance, the following program
1150:
1151: \bprog
1152: \obr
1153: \q a = b
1154: \q b = c
1155: \cbr
1156: \eprog
1157:
1158: \noindent would silently produce garbage, since what GP will really see is
1159: \kbd{a=bb=c} which will assign the value of \kbd{c} to both \kbd{bb} and
1160: \kbd{a} (if this really is what you intended, you're a hopeless case).
1161:
1162: \section{The GP/PARI programming language}
1163:
1164: The GP calculator uses a purely interpreted language. The structure of this
1165: language is reminiscent of LISP with a functional notation, \kbd{f(x,y)}
1166: rather than \kbd{(f x y)}: all \idx{programming} constructs, such as
1167: \kbd{if}, \kbd{while,} etc... are functions \footnote{*}{Not exactly, since
1168: not all their arguments need be evaluated. For instance it would be stupid
1169: to evaluate both branches of an \kbd{if} statement: since only one will
1170: apply, GP only expands this one.} (see \secref{se:programming} for a
1171: complete list), and the main loop does not really execute, but rather
1172: evaluates (sequences of) expressions. Of course, it is by no means a true
1173: LISP.
1174:
1175: \subsec{Variables and symbolic expressions}.\sidx{variable}
1176:
1177: In GP you can use up to 16383 variable names (up to 65535 on 64-bit
1178: machines). These names can be any standard identifier names, i.e.~they must
1179: start with a letter and contain only valid keyword characters: \kbd{\_} or
1180: alphanumeric characters ([\kbd{\_A-Za-z0-9}]). To avoid confusion with other
1181: symbols, you must not use other non-alphanumeric symbols like \kbd{\$}, or
1182: '\kbd{.}'. In addition to the function names which you must not use (see the
1183: list with \b{c}), there are exactly three special variable names which you
1184: are not allowed to use: \kbd{Pi} and \tet{Euler}, which represent well known
1185: constants, and $\kbd{I}=\sqrt{-1}$.
1186:
1187: Note that GP names are case sensitive since version 1.900. This means for
1188: instance that the symbol \kbd{i} is perfectly safe to use, and will not be
1189: mistaken for $\sqrt{-1}$, and that \kbd{o} is not synonymous anymore to
1190: \kbd{O}. If you grew addicted to the previous behaviour, you can have it back
1191: by setting the default \kbd{compatible} to $3$.
1192:
1193: Now the main thing to understand is that PARI/GP is {\it not\/} a symbolic
1194: manipulation package, although it shares some of the functionalities. One of
1195: the main consequences of this fact is that all expressions are evaluated as
1196: soon as they are written, they never stay in a purely abstract form%
1197: \footnote{**}{An obvious but important exception are character strings which
1198: are evaluated\dots\ essentially to themselves (type \typ{STR}). Not exactly
1199: so though, since we do some work to treat the quoted characters correctly
1200: (those preceded by a \b{)}.}.
1201: %
1202: As an important example, consider what happens when you use a variable name
1203: {\it before\/} assigning a value into it. This is perfectly acceptable to GP,
1204: which considers this variable in fact as a polynomial of degree 1, with
1205: coefficients 1 in degree 1, 0 in degree 0, whose variable is the variable
1206: name you used.
1207:
1208: If later you assign a value to that variable, the objects which you have
1209: created before will still be considered as polynomials. If you want to obtain
1210: their value, use the function \kbd{eval} (see \secref{se:eval}).
1211:
1212: Finally, note that if the variable $x$ contains a vector or list, you can
1213: assign a result to $x[m]$ (i.e.~write something like $x[k]=\var{expr}$). If
1214: $x$ is a matrix, you can assign a result to $x[m,n]$, but {\it not\/} to
1215: $x[m]$. If you want to assign an expression to the $m$-th column of a matrix
1216: $x$, use $x[,m]=\var{expr}$ instead. Similarly, use $x[m,]=\var{expr}$ to
1217: assign an expression to the $m$-th row of $x$. This process is recursive, so
1218: if $x$ is a matrix of matrices of \dots, an expression such as
1219: $x[1,1][,3][4]=1$ would be perfectly valid (assuming of course that all
1220: matrices along the way have the correct dimensions).
1221:
1222: \misctitle{Note:} We'll see in \secref{se:user_defined} that it is possible
1223: to restrict the use of a given variable by declaring it to be \tet{global} or
1224: \tet{local}. This can be useful to enforce clean programming style, but is in
1225: no way mandatory.
1226:
1227: \misctitle{(Technical) Note:} Variables are numbered in the order that they
1228: appear since the beginning of the session, and the main variable of an
1229: expression is always the lowest numbered variable. Hence if you are working
1230: with expressions involving several variables and want to have them ordered in
1231: a specific manner {\it in the internal representation}, the simplest is just
1232: to write down the variables one after the other under GP before starting any
1233: real computations. If you already have started working and want to change the
1234: names of the variables in an object, use the function \tet{changevar}. If you
1235: only want to have them ordered when the result is printed, you can also use
1236: the function \tet{reorder}, but this won't change anything to the internal
1237: representation.
1238:
1239: \misctitle{(Very technical) Note:}
1240: Each variable has a stack of values, implemented as a linked list. When a new
1241: scope is entered (during a function call which uses it as a parameter, or if
1242: the variable is used as a loop index, see \secref{se:user_defined} and
1243: \secref{se:programming}), the value of the actual parameter is pushed on the
1244: stack. If the parameter is not supplied, a special $0$ value called
1245: \teb{gnil} is pushed on the stack (this value is not printed if it is
1246: returned as the result of a GP expression sequence). Upon exit, the stack
1247: decreases. You can \kbd{kill} a variable, decreasing the stack yourself. This
1248: should be used only at the top level of GP, to undo the effect of an
1249: assignment, not from a function. However, the stack has a bottom: the value
1250: of a variable is the monomial of degree 1 in this variable, as is natural for
1251: a mathematician.
1252:
1253: \subsec{Expressions and expression sequences}.
1254:
1255: An \idx{expression}\sidx{expression sequence} is formed by combining the
1256: GP operators, functions (including user-defined functions, see below) and
1257: control statements. It may be preceded by an assignment statement '$=$'
1258: into a variable. It always has a value, which can be any PARI object.
1259:
1260: Several expressions can be combined on a single line by separating them
1261: with semicolons (';') and also with colons (':') for those who are used to
1262: BASIC. Such an expression sequence will be called simply a \var{seq}. A
1263: \var{seq} also has a value, which is the value of the last non-empty
1264: expression in the sequence. Under GP, the value of the \var{seq}, and only
1265: this last value, is always put on the stack (i.e. it will become the next
1266: object $\%n$). The values of the other expressions in the \var{seq} are
1267: discarded after the execution of the \var{seq} is complete, except of
1268: course if they were assigned into variables. In addition, the value of
1269: the \var{seq} (or of course of an expression if there is only one) is
1270: printed if the line does not end with a semicolon (';').
1271:
1272: \subsec{User defined functions}.\sidx{user defined functions}
1273: \label{se:user_defined}
1274:
1275: It is very easy to define a new function under GP, which can then be used
1276: like any other function. The syntax is as follows:
1277:
1278: \kbd{name(list of formal variables) = local(list of local variables); \var{seq}}
1279:
1280: \noindent which looks better written on consecutive lines:
1281: \bprog% name($x_0$, $x_1$, \dots) =
1282: \obr
1283: \q local($t_0$, $t_1$, \dots);
1284: \q local(\dots);
1285: \q
1286: \q \dots
1287: \cbr
1288: \eprog
1289: \noindent (note that the first newline is disregarded due to the preceding
1290: \kbd{=} sign, and the others because of the enclosing braces). Both lists
1291: of variables are comma-separated and allowed to be empty. The \tet{local}
1292: statements can be omitted; as usual \var{seq} is any expression sequence.
1293:
1294: \kbd{name} is the name given to the function and is subject to the same
1295: restrictions as variable names. In addition, variable names are not valid
1296: function names, you have to \kbd{kill} the variable first (the converse is
1297: true: function names can't be used as variables, see \secref{se:kill}).
1298: Previously used function names can be recycled: you are just redefining the
1299: function (the previous definition is lost of course).
1300:
1301: \kbd{list of formal variables} is the list of variables corresponding to
1302: those which you will actually use when calling your function. The number of
1303: actual parameters supplied when calling the function has to be less than the
1304: number of formal variables.
1305:
1306: Uninitialized formal variables will be given a default value. An equal
1307: (\kbd{=}) sign following a variable name in the function definition,
1308: followed by any expression, gives the variable a default value. The
1309: expression gets evaluated the moment the function is defined, and is fixed
1310: afterward. A variable for which you supply no default value will be
1311: initialized to zero.
1312:
1313: \kbd{list of local variables} is the list of the additional local variables
1314: which are used in the function body. Note that if you omit some or all of
1315: these local variable declarations, the non-declared variables will become
1316: global, hence known outside of the function, and this may have undesirable
1317: side-effects. On the other hand, in some cases it may also be what you want.
1318: Local variables can be given a default value as the formal variables.
1319:
1320: \misctitle{Example:} For instance \kbd{foo(x=1,y=2,z=3) = print(x ":" y ":"
1321: z)}, defines a function which prints its arguments (at most three of them),
1322: separated by colons. This then follows the rules of default arguments
1323: generation as explained at the beginning of \secref{se:functions}.
1324:
1325: \bprog%
1326: ? foo(6,7)
1327: 6:7:3
1328: ? foo(,5)
1329: 1:5:3
1330: ? foo
1331: 1:2:3
1332: \eprog
1333:
1334: Once the function is defined using the above syntax, you can use it like
1335: any other function. In addition, you can also recall its definition exactly
1336: as you do for predefined functions, that is by writing \kbd{?\var{name}}.
1337: This will print the list of arguments, as well as their default values,
1338: the text of \var{seq}, and a short help text if one was provided using
1339: the \kbd{addhelp} function (see \secref{se:addhelp}). One small difference
1340: to predefined functions is that you can never redefine the built-in
1341: functions, while you can redefine a user-defined function as many times
1342: as you want.
1343:
1344: Typing \b{u} will output the list of user-defined functions.
1345:
1346: An amusing example of a user-defined function is the following. It is
1347: intended to illustrate both the use of user-defined functions and the power
1348: of the \kbd{sumalt} function. Although the \idx{Riemann zeta-function} is
1349: included in the standard functions, let us assume that this is not the case
1350: (or that we want another implementation). One way to define it, which is
1351: probably the simplest (but certainly not the most efficient), is as
1352: follows:
1353:
1354: \sidx{zeta function}
1355: \bprog%
1356: zet(s) =
1357: \obr
1358: \q local(j); /* not needed, and possibly confusing (see below) */
1359: \q sumalt(j=1, (-1)\pow(j-1)*j\pow(-s)) / (1 - 2\pow(1-s))
1360: \cbr
1361: \eprog
1362:
1363: \noindent This gives reasonably good accuracy and speed as long as you are
1364: not too far from the domain of convergence. Try it for $s$ integral between
1365: $-5$ and $5$, say, or for $s=0.5+i*t$ where $t=14.134\dots$
1366:
1367: The iterative constructs which use a variable name (\kbd{for$xxx$},
1368: \kbd{prod$xxx$}, \kbd{sum$xxx$}, \kbd{vector}, \kbd{matrix}, \kbd{plot},
1369: etc.) also consider the given variable to be local to the construct. A value
1370: is pushed on entry and pulled on exit. So, it is not necessary for a function
1371: using such a construct to declare the variable as a dummy formal parameter.
1372:
1373: In particular, since loop variables are not visible outside their loops,
1374: the variable \kbd{j} need not be declared in the protoype of our \kbd{zet}
1375: function above.
1376:
1377: \kbd{zet(s) = sumalt(j=1, (-1)\pow(j-1)*j\pow(-s)) / (1 - 2\pow(1-s))}
1378:
1379: \noindent would be a perfectly sensible (and in fact better) definition.
1380: Since local/global scope is a very tricky point, here's one more example.
1381: What's wrong with the following definition?
1382: \bprog%
1383: ? first\_prime\_div(x) =
1384: \obr
1385: \q local(p);
1386: \q forprime(p=2, x, if (x\%p == 0, break));
1387: \q p
1388: \cbr
1389: ? first\_prime\_div(10)
1390: \%1 = 0
1391: \eprog
1392:
1393: \misctitle{Answer:} the index $p$ in the \kbd{forprime} loop is local to
1394: the loop and is not visible to the outside world. Hence, it doesn't survive
1395: the \kbd{break} statement. More precisely, at this point the loop index is
1396: restored to its preceding value, which is 0 (local variables are
1397: initialized to 0 by default). To sum up, the routine returns the $p$
1398: declared local to it, not the one which was local to \kbd{forprime} and ran
1399: through consecutive prime numbers. Here's a corrected version:
1400:
1401: \bprog%
1402: ? first\_prime\_div(x) = forprime(p=2, x, if (x\%p == 0, return(p)))
1403: \eprog
1404:
1405: Again, it is strongly recommended to declare all other local variables that
1406: are used inside a function: if a function accesses a variable which is not
1407: one of its formal parameters, the value used will be the one which happens to
1408: be on top of the stack at the time of the call. This could be a ``global''
1409: value, or a local value belonging to any function higher in the call chain.
1410: So, be warned.
1411:
1412: There's no problem with recursive functions as long as one pays proper
1413: attention to variable scope. Here's a last example, used to retrieve the
1414: coefficient array of a multivariate polynomial (a non-trivial task due to
1415: PARI's unsophisticated representation for those objects)~:
1416: \sidx{multivariate polynomial}
1417:
1418: \bprog%
1419: coeffs(P, nbvar) =
1420: \obr
1421: \q local(v);
1422: \h
1423: \q if (type(P) != "t\_POL",
1424: \q\q for (i=0, nbvar-1, P = [P]);
1425: \q\q return (P)
1426: \q );
1427: \q v = vector(poldegree(P)+1, i, polcoeff(P,i-1));
1428: \q vector(length(v), i, coeffs(v[i], nbvar-1))
1429: \cbr
1430: \eprog
1431:
1432: \noindent If $P$ is a polynomial in $k$ variables, show that after the
1433: assignment {\tt v = coeffs(P,k)}, the coefficient of $x_1^{n_1}\dots
1434: x_k^{n_k}$ in P is given by {\tt v[$n_1$+1][\dots][$n_k$+1]}. What would
1435: happen if the declaration {\tt local(v)} had been omitted ?
1436:
1437: \misctitle{Function which take functions as parameters ?} This is easy
1438: in GP using the following trick (neat example due to Bill Daly):
1439:
1440: \bprog%
1441: calc(f, x) = eval(Str( f "(x)"))
1442: \eprog
1443:
1444: \noindent If you call this with \kbd{calc("sin", 1)}, it will
1445: return $\sin(1)$ (evaluated!).
1446:
1447: \misctitle{Restrictions on variable use:} it is not allowed to use the same
1448: variable name for different parameters of your function. Or to use a given
1449: variable both as a formal parameter and a local variable in a given function.
1450: Hence
1451: \bprog%
1452: ? f(x,x) = 1
1453: \q *** user function f: variable x declared twice.
1454: \eprog
1455:
1456: Also, the statement \kbd{\idx{global}(x, y, z, t)} (see \secref{se:global})
1457: declares the corresponding variables to be global. It is then forbidden to
1458: use them as formal parameters or loop indexes as described above, since the
1459: parameter would ``shadow'' the variable.
1460:
1461: \misctitle{Implementation note.} For the curious reader, here is how these
1462: stacks are handled: a \idx{hashing function} is computed from the identifier,
1463: and used as an index in \tet{hashtable}, a table of pointers. Each of
1464: these pointers begins a linked list of structures (type \tet{entree}).
1465: The linked list is searched linearly for the identifier (each list will
1466: typically have less than 7 components or so). When the correct \kbd{entree}
1467: is found, it points to the top of the stack of values for that identifier if
1468: it is a variable, to the function itself if it is a predefined function, and
1469: to a copy of the text of the function if it is a user-defined function. When
1470: an error occurs, all of this maze (rather a tree, in fact) is searched and
1471: (hopefully) restored to the state preceding the last call of the main
1472: evaluator.
1473:
1474: \misctitle{Note:} The above syntax (using the \tet{local} keyword) was
1475: introduced in version 2.0.13. The old syntax
1476:
1477: \kbd{name(list of true formal variables, list of local variables) = \var{seq}}
1478:
1479: \noindent is still recognized but is deprecated since genuine arguments and
1480: local variables become undistinguishable.
1481:
1482: \subsec{Member functions}.\sidx{member functions}
1483:
1484: Member functions use the `dot' notation to retrieve information from
1485: complicated structures (by default: types \tet{ell}, \tet{nf}, \tet{bnf},
1486: \tet{bnr} and prime ideals). The syntax \kbd{structure.member} is taken to
1487: mean: retrieve \kbd{member} from \kbd{structure}, e.g.~\kbd{ell.j} returns
1488: the $j$-invariant of the elliptic curve \kbd{ell} (or outputs an error
1489: message if \kbd{ell} doesn't have the correct type).
1490:
1491: You can define your own member functions using the syntax:
1492:
1493: \bprog%
1494: structure.member = {\it function text}
1495: \eprog
1496: \noindent where {\it function text\/} is written as the {\it seq\/} in a
1497: standard user function (without local variables), whose only argument would
1498: be \kbd{structure}. For instance, the current implementation of the \kbd{ell}
1499: type is simply an horizontal vector, the $j$-invariant being the thirteenth
1500: component. This could be implemented as
1501:
1502: \bprog
1503: x.j =
1504: \obr
1505: \q if (type(x) != "t\_VEC" || length(x) < 14,
1506: \q\q error("this is not a proper elliptic curve: " x)
1507: \q );
1508: \q x[13]
1509: \cbr
1510: \eprog
1511:
1512: You can redefine one of your own member functions simply by typing a new
1513: definition for it. On the other hand, as a safety measure, you can't redefine
1514: the built-in member functions, so typing the above text would in fact produce
1515: an error (you'd have to call it e.g.~\kbd{x.j2} in order for GP to accept it).
1516:
1517: Typing \b{um} will output the list of user-defined member functions.
1518:
1519: \misctitle{Note:} Member functions were not meant to be too complicated or to
1520: depend on any data that wouldn't be global. Hence they do no have parameters
1521: (besides the implicit \kbd{structure}) or local variables. Of course, if you
1522: need some preprocessing work in there, there's nothing to prevent you from
1523: calling your own functions (using freely their local variables) from a member
1524: function. For instance, one could implement (a dreadful idea as far as
1525: efficiency goes):
1526:
1527: \bprog
1528: correct\_ell\_if\_needed(x) =
1529: \obr
1530: \q local(tmp);
1531: \q if (type(x) != "t\_VEC", tmp = ellinit(x))
1532: \q \bs\bs {\it some further checks}
1533: \q tmp
1534: \cbr
1535: x.j = correct\_ell\_if\_needed(x)[13];
1536: \eprog
1537:
1538: \subsec{Strings and Keywords}\sidx{string}\sidx{keyword}
1539: \label{se:strings}
1540:
1541: \noindent
1542: GP variables can now hold values of type character string
1543: (internal type \typ{STR}).
1544: This section describes how they are actually used, as well as some convenient
1545: tricks (automatic concatenation and expansion, keywords) valid in string
1546: context.
1547:
1548: As explained above, the general way to input a string is to enclose characters
1549: between quotes~\kbd{"}. This is the only input construct where whitespace
1550: characters are significant: the string will contain the exact number
1551: of spaces you typed in. Besides, you can ``escape'' characters by putting a
1552: \kbd{\bs} just before them; this has the following effects:
1553:
1554: {
1555: \def\q{\quad}
1556: \obeylines
1557: \q \b{e}: the \kbd{<Escape>} character.
1558: \q \b{n}: the \kbd{<Newline>} character.
1559: \q \b{t}: the \kbd{<Tab>} character.
1560: \q \b{any-other-char}: the \kbd{any-other-char} character.
1561: }
1562: In particular, the only way to put a \kbd{"} into a string is to escape it.
1563: Thus, for instance, \kbd{"\bs"a\bs""} would produce the
1564: string whose content is ``a''. This is definitely {\it not\/} the same thing as
1565: typing \kbd{"a"}, whose content is merely the one-letter string a.
1566:
1567: You can concatenate two strings using the \tet{concat} function. If either
1568: argument is a string, the other is automatically converted to a string if
1569: necessary (it will be evaluated first).
1570:
1571: \bprog%
1572: ? concat("ex", 1+1)
1573: \%1 = "ex2"
1574: ? a = 2; b = "ex"; concat(b, a)
1575: \%2 = "ex2"
1576: ? concat(a, b)
1577: \%3 = "2ex"
1578: \eprog
1579:
1580: Some functions expect strings for some of their arguments: \tet{print} would
1581: be an obvious example, \tet{Str} is a less obvious but very useful one (see
1582: the end of this section for a complete list). While typing in such an
1583: argument, you will be said to be in {\it \idx{string context}}. The rest of
1584: this section is devoted to special syntactical tricks which can be used with
1585: such arguments (and only here; you will get an error message if you try these
1586: outside of string context):
1587:
1588: $\bullet$ Writing two strings alongside one another will just concatenate
1589: them, producing a longer string. Thus it is equivalent to type in
1590: \kbd{"a " "b"} or \kbd{"a b"}. A little tricky point in the first expression:
1591: the first whitespace is enclosed between quotes, and so is part of a string;
1592: while the second (before the \kbd{"b"}) is completely optional and GP
1593: actually suppresses it, as it would with any number of whitespace characters
1594: at this point (i.e.~outside of any string).
1595:
1596: $\bullet$ If you insert an expression without quotes when GP expects a
1597: string, it gets ``expanded'': it is evaluated as a standard GP expression,
1598: and the final result (as would have been printed if you had typed it by
1599: itself) is then converted to a string, as if you had typed it directly. For
1600: instance \kbd{"a" 1+1 "b"} is equivalent to \kbd{"a2b"}: three strings get
1601: created, the middle one being the expansion of \kbd{1+1}, and these are then
1602: concatenated according to the rule described above. Another tricky point
1603: here: assume you did not assign a value to \kbd{aaa} in a GP expression
1604: before. Then typing \kbd{aaa} by itself in a string context will actually
1605: produce the correct output (i.e.~the string whose content is aaa), but in a
1606: fortuitous way. This \kbd{aaa} gets expanded to the monomial of degree one in
1607: the variable \kbd{aaa}, which is of course printed as \kbd{aaa}, and thus
1608: will expand to the three letters you were expecting. But you will have
1609: defined a variable as a side effect.
1610:
1611: $\bullet$ Since there are cases where expansion is not really desirable, we
1612: now distinguish between ``Keywords'' and ``Strings''. String is what has been
1613: described so far. Keywords are special relatives of Strings which are
1614: automatically assumed to be quoted, whether you actually type in the quotes
1615: or not. Thus expansion is never performed on them. They get concatenated,
1616: though. The analyzer supplies automatically the quotes you have ``forgotten''
1617: and treats Keywords just as normal strings otherwise. For instance, if you
1618: type \kbd{"a"b+b} in Keyword context, you will get the string whose contents
1619: are ab+b. In String context, on the other hand, you would get a2\kbd{*}b
1620: (and you would have created the variable \kbd{b} in the process if it didn't
1621: exist before, but not the variable~\kbd{a}).
1622:
1623: All GP functions have prototypes (described in Chapter~3 below) which specify
1624: the types of arguments they expect: either generic PARI objects (GEN),
1625: or strings, or keywords, or unevaluated expression sequences.
1626: In the keyword case, only a very small set of words
1627: will actually be meaningful (the \kbd{default} function is a prominent
1628: example).
1629:
1630: Let's now try some not-so-stupid exercises to get the hang of it. Try to
1631: guess the results of the following commands without actually typing them,
1632: assuming that the \kbd{print} command evaluates and prints its (string)
1633: arguments in left-to-right order, ending with a newline (and returns 0
1634: as an unprinted result):
1635:
1636: \bprog%
1637: \q print()
1638: \q print(1+3"a,3" ,4)
1639: \q print(a=3, (1 + ((a-3)==print())) (a = (a == 5\bs/2)))
1640: \eprog
1641:
1642: \noindent To round this up, here is a less artificial example, used to create
1643: generic matrices\sidx{generic matrix}:
1644:
1645: \bprog%
1646: ? genmat(u,v,s="x") = \idx{matrix}(u,v,i,j, eval(Str(s "" i "" j)))
1647: ? genmat(2,3) + genmat(2,3,m)
1648: \%1 =
1649: [x11 + m11 x12 + m12 x13 + m13]
1650: [x21 + m21 x22 + m22 x23 + m23]
1651: \eprog
1652:
1653: \noindent
1654: Note that the argument of \kbd{Str} is evaluated in string context, and
1655: really consists of 5 pieces (exercise: why are the empty strings necessary?).
1656: This part could also have been written as \kbd{concat(concat(Str(s), i), j)}
1657: (but {\it not\/} as \kbd{concat(Str(s), concat(i,j))}!). In practice,
1658: \kbd{Str} will often be easier to use than \kbd{concat}, if slightly more
1659: cryptic.
1660:
1661: \noindent The arguments of the following functions are processed in string
1662: context:
1663: \bprog%
1664: \idx{Str}
1665: \idx{addhelp} {\rm (second argument)}
1666: \idx{default} {\rm (second argument)}
1667: \idx{error}
1668: \idx{extern}
1669: \idx{plotstring} {\rm (second argument)}
1670: \idx{plotterm} {\rm (first argument)}
1671: {\rm all the \kbd{\idx{print}{\it xxx\/}} functions}
1672: \idx{read}
1673: \idx{system}
1674: {\rm all the \kbd{\idx{write}{\it xxx\/}} functions}
1675: \eprog
1676:
1677: \noindent The arguments of the following functions are processed as keywords:
1678: \bprog%
1679: \idx{alias}
1680: \idx{default} {\rm (first argument)}
1681: \idx{install} {\rm (all arguments but the last)}
1682: \idx{type} {\rm (second argument)}
1683: \idx{whatnow}
1684: \eprog
1685:
1686: \section{Interfacing GP with other languages}
1687: \noindent
1688: The PARI library was meant to be interfaced with C programs. This specific
1689: use will be dealt with extensively in Chapter~4. GP itself provides a
1690: convenient, if simple-minded, interpreter, which enables you to execute
1691: rather intricate scripts (see \secref{se:programming}).
1692:
1693: Scripts, when properly written, tend to be shorter and much clearer than C
1694: programs, and are certainly easier to write, maintain or debug. You don't
1695: need to deal with memory management, garbage collection, pointers,
1696: declarations, and so on. Because of their intrinsic simplicity, they are more
1697: robust as well. They are unfortunately somewhat slower. Thus their use will
1698: remain complementary: it is suggested that you test and debug your algorithms
1699: using scripts, before actually coding them in C for the sake of speed.
1700:
1701: \unix{Note that the \kbd{install} command enables you to concentrate on
1702: critical parts of your programs only (which can of course be written with the
1703: help of other mathematical libraries than PARI!), and to easily and
1704: efficiently import foreign functions for use under GP
1705: (see~\secref{se:install}).}
1706:
1707: We are aware of three PARI-related public domain libraries. {\it We neither
1708: endorse nor support any of them}. You might want to give them a try if you
1709: are familiar with the languages they are based on. First, there are
1710: \tet{PariPerl}%
1711: \footnote{*}{
1712: see \kbd{%
1713: http://nswt.tuwien.ac.at:8000/htdocs/internet/unix/perl/math-pari.html}},
1714: %
1715: written by Ilya Zakharevich (\kbd{ilya@math.ohio-state.edu}),
1716: and \tet{PariPython}%
1717: \footnote{**}{
1718: see \kbd{http://www.math.jussieu.fr/\til{}fermigie/PariPython/readme.html}},
1719: %
1720: by St\'efane Fermigier (\kbd{fermigie@math.jussieu.fr}). Finaly, Michael Stoll
1721: (\kbd{Michael\_Stoll@math.uni-bonn.de}) has integrated PARI into \tet{CLISP},
1722: which is a Common Lisp implementation by Bruno Haible, Marcus Daniels and
1723: others. These provide interfaces to GP functions for use in \kbd{perl},
1724: \kbd{python} or \kbd{Lisp} programs.\sidx{Perl}\sidx{Python}\sidx{Lisp}
1725: To our knowledge, only the \kbd{python} and \kbd{perl} interfaces have been
1726: upgraded to version 2.0 of PARI, the \kbd{CLISP} one being still based on
1727: version 1.39.$xx$.
1728:
1729: \section{The preferences file}\sidx{startup}\sidx{gprc}\sidx{preferences file}
1730: \label{se:gprc}
1731:
1732: \noindent
1733: When GP is started, it looks for a customization file, or \kbd{gprc} in the
1734: following places (in this order, only the first one found will be read):
1735:
1736: \noindent$\bullet$ On the Macintosh (only), GP looks in the directory which
1737: contains the GP executable itself for a file called \kbd{gprc}. No other places
1738: are examined.
1739:
1740: \noindent$\bullet$ If the operating system supports environment variables
1741: (essentially, anything but MacOS), GP checks whether the environment variable
1742: \tet{GPRC} is set. Under DOS, you can set it in \kbd{AUTOEXEC.BAT}.
1743: On Unix, this can be done with something like:
1744: \smallskip
1745:
1746: \settabs\+\indent&\kbd{GPRC=/my/dir/anyname; export GPRC}\quad&\cr
1747:
1748: \+&\kbd{GPRC=/my/dir/anyname; export GPRC}\quad&in \kbd{sh} syntax
1749: (for instance in your \kbd{.profile}),\cr
1750:
1751: \+&\kbd{setenv GPRC /my/dir/anyname} &in \kbd{csh} syntax
1752: (in your \kbd{.login} or \kbd{.cshrc} file).\cr
1753:
1754: \noindent If so, the file named by \kbd{\$GPRC} is the \kbd{gprc}.
1755:
1756: \noindent$\bullet$ If \kbd{GPRC} is not set, and if the environment variable
1757: \kbd{HOME} is defined, GP then tries
1758:
1759: \kbd{\$HOME/.gprc} on a Unix system
1760:
1761: \kbd{\$HOME\bs\_$\,$gprc} on a DOS, OS/2, or Windows system.
1762:
1763: \noindent$\bullet$ If \kbd{HOME} also leaves us clueless, we try
1764:
1765: \strut\kbd{\til/.gprc} on a Unix system (where as usual \kbd{\til} stands for
1766: your home directory), or
1767:
1768: \kbd{\b{\_}$\,$gprc} on a DOS, OS/2, or Windows system.
1769:
1770: \noindent$\bullet$ Finally, if no gprc was found among the user files
1771: mentioned above we look for \kbd{/etc/gprc} (\kbd{\bs etc\bs gprc})
1772: for a system-wide gprc file (you'll need root privileges to set up such a
1773: file yourself).
1774:
1775: Note that on Unix systems, the \kbd{gprc}'s default name starts with a '.' and
1776: thus is hidden to regular \kbd{ls} commands; you need to type \kbd{ls -a} to
1777: see whether it's already there without your knowing about it.
1778:
1779: In any case, GP will open the corresponding file and process the commands in
1780: there, {\it before\/} doing anything else, e.g.~creating the PARI stack. If
1781: the file doesn't exist or cannot be read, GP will proceed to the
1782: initialization phase at once, eventually emitting a prompt. If any explicit
1783: commandline switches are given, they will override the values read from the
1784: \kbd{gprc} file.
1785:
1786: The syntax in this file (and valid in this file only, at this very precise
1787: moment!) is simple-minded, but should be sufficient for most purposes. It
1788: is read line by line, white space being optional as usual (unless surrounded
1789: by quotes). Two types of lines are first dealt with by a preprocessor:
1790:
1791: $\bullet$ comments are removed. This applies to all text surrounded by
1792: \kbd{/*~\dots~*/} as well as everything following \kbd{\bs\bs} on a given
1793: line.
1794:
1795: $\bullet$ lines starting with \kbd{\#if} \var{keyword} are treated as
1796: comments if \var{keyword} is not defined, and read normally otherwise. The
1797: condition can be negated using either \kbd{\#if not} (or \kbd{\#if !}). Only
1798: two keywords are recognized:
1799:
1800: \kbd{EMACS}: defined if GP is running in an Emacs shell (see
1801: \secref{se:emacs}).
1802:
1803: \kbd{READL}: defined if GP is compiled with \kbd{readline} support (see
1804: \secref{se:readline}).
1805:
1806: \noindent For instance you could set your prompt in the following portable
1807: way:
1808: \bprog%
1809: \b{\bs} self modifying prompt looking like \hbox{{\rm (18:03) \key{gp}} >}
1810: prompt = "(\%R) \b{e}[1mgp\b{e}[m > "
1811: \h
1812: \b{\bs} readline wants non-printing characters to be braced between \pow A/\pow B pairs
1813: \#if READL prompt = "(\%R) \pow A\b{e}[1m\pow Bgp\pow A\b{e}[m\pow B > "
1814: \h
1815: \b{\bs} escape sequences not supported under emacs
1816: \#if EMACS prompt = "(\%R) gp > "
1817: \eprog
1818:
1819: \noindent After the preprocessing there remain two types of lines:
1820:
1821: $\bullet$ lines of the form \var{default} \kbd{=} \var{value}, where
1822: \var{default} is one of the available defaults (see \secref{se:defaults}),
1823: which will be set to \var{value} on actual startup. Don't forget the
1824: quotes around strings (e.g.~for \kbd{prompt} or \kbd{help}).
1825:
1826: $\bullet$ lines of the form \kbd{read "\var{some\_GP\_file}"} where
1827: \kbd{\var{some\_GP\_file}} is a regular GP script this time, which will
1828: be read just before GP prompts you for commands, but after initializing the
1829: defaults. This is the right place to input files containing \kbd{alias}
1830: commands, or your favorite macros.
1831:
1832: A sample \kbd{gprc} file called \kbd{gprc.dft} is provided in the
1833: standard distribution (in directory \kbd{lib}). It's a good idea to have a
1834: look at it and customize it to your needs.
1835:
1836: \section{Using GP under GNU Emacs}
1837: \label{se:emacs}
1838:
1839: Thanks to the initial help of Annette Hoffman from the University of
1840: Saarbr\"ucken, and David Carlisle from the University of Manchester, it is
1841: possible to use GP as a subprocess of GNU \idx{Emacs}. (Of course, you need
1842: GNU Emacs to be installed on your machine!). To use this, you should
1843: include in your \kbd{.emacs} file the following lines:
1844: \bprog%
1845: (autoload 'gp-mode "\miscdir/pari" nil t)
1846: (autoload 'gp-script-mode "\miscdir/pari" nil t)
1847: (autoload 'gp "\miscdir/pari" nil t)
1848: (autoload 'gpman "\miscdir/pari" nil t)
1849: (setq auto-mode-alist
1850: \q (cons '("\bs\bs.gp\$" . gp-script-mode) auto-mode-alist))
1851: \eprog
1852:
1853: where \kbd{pari.el} is the name of the file that will have to be loaded by
1854: GNU Emacs (if you have changed the name, or if you have the file in a
1855: different directory, you must of course supply the correct name). This file
1856: is included in the PARI distribution and probably has been installed at the
1857: same time as GP.
1858:
1859: Once this is done, under GNU Emacs if you type \kbd{M-x gp} (where as usual
1860: \kbd{M} is the \kbd{Meta} key, i.e.~Escape, or on SUN keyboards, the Left
1861: key), a special shell will be started, which in particular launches GP with
1862: the default stack size, prime limit and input buffer size. If you type
1863: instead \kbd{C-u M-x gp}, you will be asked for the name of the GP
1864: executable, the stack size, the prime limit and the input buffer size before
1865: the execution of GP begins. If for any of these you simply type return, the
1866: default value will be used. On UNIX machines it will be the place you told
1867: \kbd{Configure} (usually \kbd{/usr/local/bin/gp}) for the executable, 4000000
1868: for the stack, 500000 for the prime limit and 30000 for the buffer size.
1869:
1870: \smallskip
1871: You can then work as usual under GP, but with two notable advantages (which
1872: don't really matter if readline is available to you, see below). First and
1873: foremost, you have at your disposal all the facilities of a text editor like
1874: Emacs, in particular for correcting or copying blocks. Second, you can have
1875: an on-line help which is much more complete than what you obtain by typing
1876: \kbd{?name}. This is done by typing \kbd{M-?}. In the minibuffer, Emacs asks
1877: what function you want to describe, and after your reply you obtain the
1878: description which is in the users manual, including the description of
1879: functions (such as \kbd{\bs}, \kbd{\%}) which use special symbols.
1880:
1881: This help system can also be menu-driven, by using the command
1882: \kbd{M-\char`\\ c} which opens a help menu window which enables you to choose
1883: the category of commands for which you want an explanation.
1884:
1885: Nevertheless, if extended help is available on your system (see
1886: \secref{se:exthelp}), you should use it instead of the above, since it's
1887: nicer (it ran through \TeX) and understands many more keywords.
1888:
1889: Finally you can use command completion in the following way. After the
1890: prompt, type the first few letters of the command, then \kbd{<TAB>} where
1891: \kbd{<TAB>} is the TAB key. If there exists a unique command starting with
1892: the letters you have typed, the command name will be completed. If not,
1893: either the list of commands starting with the letters you typed will be
1894: displayed in a separate window (which you can then kill by typing as usual
1895: \kbd{C-x 1} or by typing in more letters), or ``no match found'' will be
1896: displayed in the Emacs command line. If your GP was linked with the readline
1897: library, read the section on completion in the section below (the paragraph
1898: on online help is not relevant).
1899:
1900: Note that if for some reason the session crashes (due to a bug in your
1901: program or in the PARI system), you will usually stay under Emacs, but the GP
1902: buffer will be killed. To recover it, simply type again \kbd{M-x gp} (or
1903: \kbd{C-u M-x gp}), and a new session of GP will be started after the old one,
1904: so you can recover what you have typed. Note that this will of course
1905: {\it not} work if for some reason you exited Emacs before coming back (except
1906: for the \kbd{C-z} temporary stopping command).
1907:
1908: \smallskip
1909: You also have at your disposal a few other commands and many possible
1910: customizations (colours, prompt). Read the file \kbd{emacs/pariemacs.txt} in
1911: standard distribution for details.
1912:
1913:
1914: \section{Using GP with readline}
1915: \sidx{line editor}\sidx{completion}
1916:
1917: Thanks to the initial help of Ilya Zakharevich, there is a possibility of
1918: line editing and command name completion outside of an Emacs buffer {\it
1919: if} you have compiled GP with the GNU \idx{readline} library. If you don't
1920: have Emacs available, or can't stand using it, we really advise you to make
1921: sure you get this very useful library before configuring or compiling GP.
1922: In fact, with \kbd{readline}, even line editing becomes {\it more} powerful
1923: outside an Emacs buffer!
1924:
1925: \subsec{A (too) short introduction to readline}:
1926: \label{se:readline}
1927: The basics are as follows (read the readline user manual~!), assume that
1928: \kbd{C-} stands for ``the \kbd{Control} key combined with another'' and the
1929: same for \kbd{M-} with the \kbd{Meta} key (generally \kbd{C-} combinations
1930: act on characters, while the \kbd{M-} ones operate on words). The \kbd{Meta}
1931: key might be called \kbd{Alt} on some keyboards, will display a black diamond
1932: on most others, and can safely be replaced by \kbd{Esc} in any case. Typing
1933: any ordinary key inserts text where the cursor stands, the arrow keys
1934: enabling you to move in the line. There are many more movement commands,
1935: which will be familiar to the Emacs user, for instance \kbd{C-a}/\kbd{C-e}
1936: will take you to the start/end of the line, \kbd{M-b}/\kbd{M-f} move the
1937: cursor backward/forward by a word, etc. Just press the \kbd{Return} key at
1938: any point to send your command to GP.
1939:
1940: All the commands you type in are stored in a history (with multiline
1941: commands being saved as single concatenated lines). The Up and Down arrows (or
1942: \kbd{C-p}/\kbd{C-n}) will move you through it, \kbd{M-<}/\kbd{M->} sending
1943: you to the start/end of the history. \kbd{C-r}/\kbd{C-s} will start an
1944: incremental backward/forward search. You can kill text (\kbd{C-k} kills till
1945: the end of line, \kbd{M-d} to the end of current word) which you can then
1946: yank back using the \kbd{C-y} key (\kbd{M-y} will rotate the kill-ring).
1947: \kbd{C-\_} will undo your last changes incrementally (\kbd{M-r} undoes all
1948: changes made to the current line). \kbd{C-t} and \kbd{M-t} will transpose
1949: the character (word) preceding the cursor and the one under the cursor.
1950:
1951: Keeping the \kbd{M-} key down while you enter an integer (a minus sign
1952: meaning reverse behaviour) gives an argument to your next readline command
1953: (for instance \kbd{M-- C-k} will kill text back to the start of line). If you
1954: prefer \idx{Vi}--style editing, \kbd{M-C-j} will toggle you to Vi mode.
1955:
1956: Of course you can change all these default bindings. For that you need to
1957: create a file named \kbd{.inputrc} in your home directory. For instance
1958: (notice the embedding conditional in case you would want specific bindings
1959: for GP):
1960: %
1961: \bprog%
1962: \$if Pari-GP
1963: \q set show-all-if-ambiguous
1964: \q "\b{C}-h": backward-delete-char
1965: \q "\b{e}\b{C}-h": backward-kill-word
1966: \q "\b{C}-xd": dump-functions
1967: \q (: "\b{C}-v()\b{C}-b" \qquad \# can be annoying when copy-pasting~!
1968: \q [: "\b{C}-v[]\b{C}-b"
1969: \$endif%
1970: \eprog
1971: %
1972: \noindent\kbd{C-x C-r} will re-read this init file, incorporating any
1973: changes made to it during the current session.
1974:
1975: \misctitle{Note:} By default, \kbd{(} and \kbd{[} are bound to the function
1976: \kbd{pari-matched-insert} which, if ``electric parentheses'' are enabled
1977: (default: off) will automatically insert the matching closure (respectively
1978: \kbd{)} and \kbd{]}). This behaviour can be toggled on and off by giving
1979: the numeric argument $-2$ to \kbd{(} (\kbd{M--2(}), which is useful if you
1980: want, e.g to copy-paste some text into the calculator. If you don't want a
1981: toggle, you can use \kbd{M--0} / \kbd{M--1} to specifically switch it on or
1982: off).
1983:
1984: \misctitle{Note:} In recent versions of readline (2.1 for instance), the
1985: \kbd{Alt} or \kbd{Meta} key can give funny results (output 8-bit accented
1986: characters for instance). If you don't want to fall back to the \kbd{Esc}
1987: combination, put the following two lines in your \kbd{.inputrc}:
1988: %
1989: \bprog%
1990: set convert-meta on
1991: set output-meta off%
1992: \eprog
1993:
1994: % don't remove this leading space (needed by gphelp)
1995: \subsec{Command completion and online help}
1996:
1997: As in the Emacs shell, \kbd{<TAB>} will complete words for you. But, under
1998: readline, this mechanism will be context-dependent: GP will strive to only
1999: give you meaningful completions in a given context (it will fail sometimes,
2000: but only under rare and restricted conditions).
2001:
2002: For instance, shortly after a \kbd{\til}, we expect a user name, then a
2003: path to some file. Directly after \kbd{default(} has been typed, we would
2004: expect one of the \kbd{default} keywords. After \kbd{whatnow(} , we expect
2005: the name of an old function, which may well have disappeared from this
2006: version. After a '.', we expect a member keyword. And generally of course, we
2007: expect any GP symbol which may be found in the hashing lists: functions (both
2008: yours and GP's), and variables.
2009:
2010: If, at any time, only one completion is meaningful, GP will provide it
2011: together with
2012:
2013: $\bullet$ an ending comma if we're completing a default,
2014:
2015: $\bullet$ a pair of parentheses if we're completing a function name. In
2016: that case hitting \kbd{<TAB>} again will provide the argument list as given
2017: by the online help\footnote{*}{recall that you can always undo the effect
2018: of the preceding keys by hitting \kbd{C-\_}}.
2019:
2020: Otherwise, hitting \kbd{<TAB>} once more will give you the list of possible
2021: completions. Just experiment with this mechanism as often as possible,
2022: you'll probably find it very convenient. For instance, you can obtain
2023: \kbd{default(seriesprecision,10)}, just by hitting \kbd{def<TAB>se<TAB>10},
2024: which saves 18 keystrokes (out of 27).
2025:
2026: Hitting \kbd{M-h} will give you the usual short online help concerning the
2027: word directly beneath the cursor, \kbd{M-H} will yield the extended help
2028: corresponding to the \kbd{help} default program (usually opens a \idx{dvi}
2029: previewer, or runs a primitive tex-to-ASCII program). None of these disturb
2030: the line you were editing.
2031: \vfill\eject
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>