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