File Coverage

blib/lib/Math/Pari.pm
Criterion Covered Total %
statement 132 166 79.5
branch 52 90 57.7
condition 26 59 44.0
subroutine 27 36 75.0
pod 2 13 15.3
total 239 364 65.6


line stmt bran cond sub pod time code
1             =head1 NAME
2              
3             Math::Pari - Perl interface to PARI.
4              
5             =head1 SYNOPSIS
6              
7             use Math::Pari;
8             $a = PARI 2;
9             print $a**10000;
10              
11             or
12              
13             use Math::Pari qw(Mod);
14             $a = Mod(3,5);
15             print $a**10000;
16              
17             =head1 DESCRIPTION
18              
19             This package is a Perl interface to famous library PARI for
20             numerical/scientific/number-theoretic calculations. It allows use of
21             most PARI functions as Perl functions, and (almost) seamless merging
22             of PARI and Perl data. In what follows we suppose prior knowledge of
23             what PARI is (see L, or
24             L).
25              
26             =head1 EXPORTed functions
27              
28             =over 4
29              
30             =item DEFAULT
31              
32             By default the package exports functions PARI(), PARIcol(), PARIvar(),
33             PARImat(), PARImat_tr() and parse_as_gp() which convert their argument(s) to a
34             PARI object. (In fact PARI() is just an alias for C).
35             The function PARI() accepts following data as its arguments
36              
37             =over 17
38              
39             =item One integer
40              
41             Is converted to a PARI integer.
42              
43             =item One float
44              
45             Is converted to a PARI float.
46              
47             =item One string
48              
49             Is executed as a PARI expression (so should not contain whitespace).
50              
51             =item PARI object
52              
53             Is passed unchanged.
54              
55             =item Reference to a Perl array
56              
57             Each element is converted using the same rules, PARI vector-row with these
58             elements is returned.
59              
60             =item Several of above
61              
62             The same as with a reference to array.
63              
64             =back
65              
66             =item Conflicts of rules in PARI()
67              
68             In deciding what rule of the above to apply the preference is given to
69             the uppermost choice of those available I. If none matches, then
70             the string rule is used. So C returns integer, C
71             returns float, C evaluates C<1> as a PARI expression (well,
72             the result is the same as C, only slower).
73              
74             Note that for Perl these data are synonymous, since Perl freely
75             converts between integers, float and strings. However, to PARI() only
76             what the argument I is important. If $v is C<1> in the Perl
77             world, C may convert it to an integer, float, or to the
78             result of evaluating the PARI program C<1> (all depending on how $v
79             was created and accessed in Perl).
80              
81             This is a fundamental limitation of creating an interface between two
82             systems, both with polymorphic objects, but with subtly different
83             semantic of the flavors of these objects. In reality, however, this
84             is rarely a problem.
85              
86             =item PARIcol(), PARImat() and PARImat_tr()
87              
88             PARIcol() behaves in the same way as PARI() unless given several
89             arguments. In the latter case it returns a vector-column instead of
90             a vector-row.
91              
92             PARImat() constructs a matrix out of the given arguments. It will work
93             if PARI() will construct a vector of vectors given the same arguments.
94             The internal vectors become columns of the matrix. PARImat_tr()
95             behaves similarly, but the internal vectors become rows of the matrix.
96              
97             Since PARI matrices are similar to vector-rows of vector-columns,
98             PARImat() is quicker, but PARImat_tr() better corresponds to the PARI
99             input and output forms of matrices:
100              
101             print PARImat [[1,2], [3,4]]; # prints [1,3;2,4]
102             print PARImat_tr [[1,2], [3,4]]; # prints [1,2;3,4]
103              
104             =item parse_as_gp()
105              
106             Did you notice that when taking a string, PARI() requires that there
107             is no whitespace there (outside of string constants)? This is exactly
108             as the C library parses strings.
109             However, to simplify human interaction, the C calculator
110             allows whitespace, comments, breaking into multiple lines, many
111             independent expressions (such as function definitions).
112              
113             We do not include the corresponding C code from the calculator, but provide
114             a Perl clone. It supports whitespace, C<\\>- and C-comments, and, for multi-line
115             arguments, it supports line continuation via trailing C<\>, trailing binary ops,
116             comma, opening parenthesis/bracket; moreover, group of
117             lines in C<{}> are joined into one line. (Additionally, C<\q> and C<\p> are
118             recognized, as well as trailing allocatemem(). C<\e> is tolerated.)
119              
120             Keep in mind that this is just a convenience function, and no attempt was
121             performed to make it particularly quick. Moreover, the PARI user functions
122             (or maybe it is better to call them user macros?) are currently not
123             automatically importable into Perl, so to access functions defined in
124             parse_as_gp()' argument may be awkward. (The temporary fix is to use
125             a temporary convenience function __wrap_PARI_macro():
126              
127             parse_as_gp <
128             add2(x) = x + 2
129             EOP
130             *add2 = Math::Pari::__wrap_PARI_macro 'add2';
131             print add2(17);
132              
133             but keep in mind that the generated this way wrapper is also not designed
134             to be quick.)
135              
136             With the optional second argument C<'quote'>, it would return an unevaluated array
137             of strings instead of the result of evaluation. Special strings C<\q> etc. are
138             replaced by references to appropriate (undocumented) Perl subroutines.
139              
140             With the optional third argument C<'echo'>, would "echo" the commands (preceded by
141             C<"? ">) before execution. With C
142             optional fourth argument (command counter), would "echo" the result too
143             (preceded by C<"%C = ">, with C being the command counter, which is
144             incremented).
145              
146             =item C with arguments
147              
148             If arguments are specified in the C directive, the
149             PARI functions appearing as arguments are exported in the caller
150             context. In this case the function PARI() and friends is not exported,
151             so if you need them, you should include them into export list
152             explicitly, or include C<:DEFAULT> tag:
153              
154             use Math::Pari qw(factorint PARI);
155             use Math::Pari qw(:DEFAULT factorint);
156              
157             or simply do it in two steps
158              
159             use Math::Pari;
160             use Math::Pari 'factorint';
161              
162             The other recognized tags are C<:PARI>, C<:all>, C,
163             overloaded constants tags (C<:int>, C<:float>, C<:hex>) and "section
164             names" tags.
165              
166             Additionally, the number tags (e.g., C<:4>) export
167             functions from the PARI library from the given "section" (moreover,
168             C<:PARI> exports all of the "sections"). Tag C<:all> exports all of the
169             exportable symbols and C<:PARI>.
170              
171             With older versions of B, giving C command to C (the B
172             calculator) lists the following sections:
173              
174             1: Standard monadic or dyadic OPERATORS
175             2: CONVERSIONS and similar elementary functions
176             3: TRANSCENDENTAL functions
177             4: NUMBER THEORETICAL functions
178             5: Functions related to ELLIPTIC CURVES
179             6: Functions related to general NUMBER FIELDS
180             7: POLYNOMIALS and power series
181             8: Vectors, matrices, LINEAR ALGEBRA and sets
182             9: SUMS, products, integrals and similar functions
183             10: GRAPHIC functions
184             11: PROGRAMMING under GP
185              
186             Starting with GP/PARI version 2.9.0, this list depends significantly on this
187             version; for backward compatibility, we follow this older list of section
188             numbers (to avoid confusion, better use symbolic names below). For
189             compatibility, we assign arbitrary numbers to newer sections:
190              
191             100: L-FUNCTIONS
192             101: MODULAR SYMBOLS
193             102: Associative and central simple ALGEBRAS
194             103: functions related to COMBINATORICS
195             104: MODULAR FORMS
196              
197             One can use section names instead of number tags. Recognized names are
198              
199             :standard :conversions :transcendental :number :elliptic
200             :fields :polynomials :vectors :sums :graphic :programming
201             :l_functions :modular_symb :algebras :combinatorics :modular
202              
203             One can get the list of all of the functions accessible by C,
204             or the accessible functions from the given section using listPari() function.
205              
206             Starting from version 5.005 of Perl, three constant-overload tags are
207             supported: C<:int>, C<:float>, C<:hex>. If used, all the
208             integer/float/hex-or-octal-or-binary literals in Perl will be automatically
209             converted to became PARI objects. For example,
210              
211             use Math::Pari ':int';
212             print 2**1000;
213              
214             is equivalent to
215              
216             print PARI(2)**PARI(1000);
217              
218             (The support for this Perl feature is buggy before the Perl version 5.005_57 -
219             unless Perl uses mymalloc options; you can check for this with C
220             -V:usemymalloc>.) Note also that (at least with some versions of Perl)
221             one should enable C<':float'> for conversion of long integer literals
222             (I may consider them as floats, since they won't fit into Perl
223             integers); note that it is PARI which determines which PARI subtype is
224             assigned to each such literal:
225              
226             use Math::Pari ':float', 'type_name';
227             print type_name 22222222222222222222222;
228              
229             prints C.
230              
231             =back
232              
233             =head1 Available functions
234              
235             =head2 Directly accessible from Perl
236              
237             This package supports I the functions from the PARI library with
238             a I which can be recognized by Math::Pari. This means that
239             when you update the PARI library, the newly added functions will we
240             available without any change to this package; only a recompile is
241             needed. In fact no recompile will be needed if you link libPARI
242             dynamically (you need to modify the F manually to do
243             this).
244              
245             You can "reach" unsupported functions via going directly to PARI
246             parser using the string flavor of PARI() function, as in
247              
248             3 + PARI('O(x^17)');
249              
250             For some "unreachable" functions there is a special wrapper functions,
251             such as C).
252              
253             The following functions are specific to GP calculator, thus are not
254             available to Math::Pari in any way:
255              
256             default error extern input print print1 printp printp1
257             printtex quit read system whatnow write write1 writetex
258              
259             whatnow() function is useless, since Math::Pari does not support the
260             "compatibility" mode (with older PARI library). The functionality of
261             print(), write() and variants is available via automatic string
262             translation, and pari_print() function and its variants (see L).
263              
264             default() is the only important function with functionality not
265             supported by the current interface. Note however, that four most
266             important default() actions are supported by allocatemem(),
267             setprimelimit(), setprecision() and setseriesprecision() functions.
268             (When called without arguments, these functions return the current
269             values.)
270              
271             allocatemem($bytes) should not be called from inside Math::Pari
272             functions (such as forprimes()).
273              
274             =head2 Arguments
275              
276             Arguments to PARI functions are automatically converted to C or
277             a PARI object depending on the signature of the actual library function.
278             The arguments are I into the given type, so even if C
279             rejects your code similar to
280              
281             func(2.5); # func() takes a long in C
282              
283             arguing that a particular argument should be of C (i.e., a
284             Pari integer), the corresponding code will work in C,
285             since 2.5 is silently converted to C, per the function
286             signature.
287              
288             =head2 Return values
289              
290             PARI functions return a PARI object or a Perl's integer depending on
291             what the actual library function returns.
292              
293             =head2 Additional functions
294              
295             Some PARI functions are available in C (i.e., in C
296             calculator) via infix notation only. In C these functions
297             are available in functional notations too. Some other convenience
298             functions are also made available.
299              
300             =over 5
301              
302             =item Infix, prefix and postfix operations
303              
304             are available under names
305              
306             gneg, gadd, gsub, gmul, gdiv, gdivent, gmod, gpui,
307             gle, gge, glt, ggt, geq, gne, gegal, gor, gand,
308             gcmp, gcmp0, gcmp1, gcmp_1.
309              
310             C means euclidean quotient, C is power, C checks
311             whether two objects are equal, C is applicable to two real
312             numbers only, C, C, C compare with 0, 1 and -1
313             correspondingly (see PARI user manual for details, or
314             L). Note that all these functions are more readily
315             available via operator overloading, so instead of
316              
317             gadd(gneg($x), $y)
318              
319             one can write
320              
321             -$x+$y
322              
323             (as far as overloading may be triggered, see L, so we assume
324             that at least one of $x or $y is a PARI object).
325              
326             =item Conversion functions
327              
328             pari2iv, pari2nv, pari2num, pari2pv, pari2bool
329              
330             convert a PARI object to an integer, float, integer/float (whatever is
331             better), string, and a boolean value correspondingly. Most the time
332             you do not need these functions due to automatic conversions.
333              
334             =item Printout functions
335              
336             pari_print, pari_pprint, pari_texprint
337              
338             perform the same conversions to strings as their PARI counterparts,
339             but do not print the result. The difference of pari_print() with
340             pari2pv() is the number of significant digits they output, and
341             whitespace in the output. pari2pv(), which is intended for
342             "computer-readable strings", outputs as many digits as is supported by
343             the current precision of the number; while pari_print(), which targets
344             human-readable strings, takes into account the currently specified
345             output precision too.
346              
347             =item Constant functions
348              
349             Some mathematical constants appear as function without arguments in
350             PARI. These functions are available in Math::Pari too. If you export
351             them as in
352              
353             use Math::Pari qw(:DEFAULT Pi I Euler);
354              
355             they can be used as barewords in your program:
356              
357             $x = Pi ** Euler;
358              
359             =item Low-level functions
360              
361             For convenience of low-level PARI programmers some low-level functions
362             are made available as well (all except type_name() and changevalue()
363             are not exportable):
364              
365             typ($x)
366             lg($x)
367             lgef($x)
368             lgefint($x)
369             longword($x, $n)
370             type_name($x)
371             changevalue($name,$newvalue)
372              
373             Here longword($x,$n) returns C<$n>-th word in the memory
374             representation of $x (including non-code words). type_name() differs
375             from the PARI function type(): type() returns a PARI object, while
376             type_name() returns a Perl string. (PARI objects of string type
377             behave very non-intuitive w.r.t. string comparison functions; remember
378             that they are compared using lex() to I of
379             other argument of comparison!)
380              
381             The function listPari($number) outputs a list of names of PARI
382             functions in the section $number. Use listPari(-1) to get the list
383             across all of the sections. (_listPari() behaves likewise, with the
384             version-specific section numbers.)
385              
386             =item Uncompatible functions
387              
388             O
389              
390             Since implementing C would be very tedious, we provide a
391             two-argument form C instead (meaning the same as C in
392             PARI). Note that with polynomials there is no problem like this one,
393             both C and C work.
394              
395             ifact(n)
396              
397             integer factorial functions, available from C as C.
398              
399             =back
400              
401             =head2 Looping functions
402              
403             PARI has a big collection of functions which loops over some set.
404             Such a function takes two I arguments: loop variable, and the
405             code to execute in the loop.
406              
407             The code can be either a string (which contains PARI code to execute -
408             thus should not contain whitespace), or a Perl code reference. The
409             loop variable can be a string giving the name of PARI variable (as in
410              
411             fordiv(28, 'j', 'a=a+j+j^2');
412              
413             or
414              
415             $j= 'j';
416             fordiv(28, $j, 'a=a+j+j^2');
417              
418             ), a PARI monomial (as in
419              
420             $j = PARI 'j';
421             fordiv(28, $j, sub { $a += $j + $j**2 });
422              
423             ), or a "delayed Math::Pari variable" (as in
424              
425             $j = PARIvar 'j';
426             fordiv(28, $j, 'a=a+j+j^2');
427              
428             ). If none of these applies, as in
429              
430             my $j; # Have this in a separate statement
431             fordiv(28, $j, sub { $a += $j + $j**2 });
432              
433             then during the execution of the C, Math::Pari would autogenerate
434             a PARI variable, and would put its value in $j; this value of $j is
435             temporary only, the old contents of $j is restored when fordiv() returns.
436              
437             Note that since you have no control over this name, you will not be
438             able to use this variable from your PARI code; e.g.,
439              
440             $j = 7.8;
441             fordiv(28, $j, 'a=a+j+j^2');
442              
443             will not make C mirror $j (unless you explicitly set up C to be
444             a no-argument PARI function mirroring $j, see L<"Accessing Perl functions from PARI code">).
445              
446             B. There are 2 flavors of the "code" arguments
447             (string/C), and 4 types of the "variable" arguments
448             (string/monomial/C/other). However, not all 8 combinations
449             make sense. As we already explained, an "other" variable cannot work
450             with a "string" code.
451              
452             B Do not
453             use "string" variables with C code, and do not ask I!
454              
455             Additionally, the following code will not do what you expect
456              
457             $x = 0;
458             $j = PARI 'j';
459             fordiv(28, 'j', sub { $x += $j } ); # Use $j as a loop variable!
460              
461             since the PARI function C I the PARI variable C
462             inside the loop, but $j will still reference the old value; the old
463             value is a monomial, not the index of the loop (which is an integer
464             each time C is called). The simplest workaround is not to use
465             the above syntax (i.e., not mixing literal loop variable with Perl
466             loop code, just using $j as the second argument to C is
467             enough):
468              
469             $x = 0;
470             $j = PARI 'j';
471             fordiv(28, $j, sub { $x += $j } );
472              
473             Alternately, one can make a I variable $j which will always
474             reference the same thing C references in PARI I by using
475             C constructor
476              
477             $x = 0;
478             $j = PARIvar 'j';
479             fordiv(28, 'j', sub { $x += $j } );
480              
481             (This problem is similar to
482              
483             $ref = \$_; # $$ref is going to be old value even after
484             # localizing $_ in Perl's grep/map
485              
486             not accessing localized values of $_ in the plain Perl.)
487              
488             Another possible quirk is that
489              
490             fordiv(28, my $j, sub { $a += $j + $j**2 });
491              
492             will not work too - by a different reason. C declarations change
493             the I of $j only I the end of the current statement;
494             thus $j inside C will access a I variable $j
495             (typically a non-lexical, global variable $j) than one you declared on this line.
496              
497             =head2 Accessing Perl functions from PARI code
498              
499             Use the same name inside PARI code:
500              
501             sub counter { $i += shift; }
502             $i = 145;
503             PARI 'k=5' ;
504             fordiv(28, 'j', 'k=k+counter(j)');
505             print PARI('k'), "\n";
506              
507             prints
508              
509             984
510              
511             Due to a difference in the semantic of
512             variable-number-of-parameters-functions between PARI and Perl, if the
513             Perl subroutine takes a variable number of arguments (via C<@> in the
514             prototype or a missing prototype), up to 6 arguments are supported
515             when this function is called from PARI. If called from PARI with
516             fewer arguments, the rest of arguments will be set to be integers C.
517              
518             Note also that no direct import of Perl variables is available yet
519             (but you can write a function wrapper for this):
520              
521             sub getv () {$v}
522              
523             There is an unsupported (and undocumented ;-) function for explicitly
524             importing Perl functions into PARI, possibly with a different name,
525             and possibly with explicitly specifying number of arguments.
526              
527             =head1 PARI objects
528              
529             Functions from PARI library may take as arguments and/or return values
530             the objects of C type C. In Perl these data are encapsulated into
531             special kind of Perl variables: PARI objects. You can check for a
532             variable C<$obj> to be a PARI object using
533              
534             ref $obj and $obj->isa('Math::Pari');
535              
536             Most the time you do not need this due to automatic conversions and overloading.
537              
538             =head1 PARI monomials and Perl barewords
539              
540             If very lazy, one can code in Perl the same way one does it in PARI.
541             Variables in PARI are denoted by barewords, as in C, and in the
542             default configuration (no warnings, no strict) Perl allows the same -
543             up to some extent. Do not do this, since there are many surprising problems.
544              
545             Some bareletters denote Perl operators, like C, C, C,
546             C. This can lead to errors in Perl parsing your expression. E.g.,
547              
548             print sin(tan(t))-tan(sin(t))-asin(atan(t))+atan(asin(t));
549              
550             may parse OK after C. Why?
551              
552             After importing, the word C will denote the PARI function sin(),
553             not Perl operator sin(). The difference is subtle: the PARI function
554             I forces its arguments to be converted PARI objects; it
555             gets C<'t'> as the argument, which is a string, thus is converted to
556             what C denotes in PARI - a monomial. While the Perl operator sin()
557             grants overloading (i.e., it will call PARI function sin() if the
558             argument is a PARI object), it does not I its argument; given
559             C<'t'> as argument, it converts it to what sin() understands, a float
560             (producing C<0.>), so will give C<0.> as the answer.
561              
562             However
563              
564             print sin(tan(y))-tan(sin(y))-asin(atan(y))+atan(asin(y));
565              
566             would not compile. You should avoid lower-case barewords used as PARI
567             variables, e.g., do
568              
569             $y = PARI 'y';
570             print sin(tan($y))-tan(sin($y))-asin(atan($y))+atan(asin($y));
571              
572             to get
573              
574             -1/18*y^9+26/4725*y^11-41/1296*y^13+328721/16372125*y^15+O(y^16)
575              
576             (BTW, it is a very good exercise to get the leading term by hand).
577              
578             Well, the same advice again: do not use barewords anywhere in your program!
579              
580             =head1 Overloading and automatic conversion
581              
582             Whenever an arithmetic operation includes at least one PARI object,
583             the other arguments are converted to a PARI object and the corresponding
584             PARI library functions is used to implement the operation. Currently
585             the following arithmetic operations are overloaded:
586              
587             unary -
588             + - * / % ** abs cos sin exp log sqrt
589             << >>
590             <= == => < > != <=>
591             le eq ge lt gt ne cmp
592             | & ^ ~
593              
594             Numeric comparison operations are converted to C and friends, string
595             comparisons compare in lexicographical order using C.
596              
597             Additionally, whenever a PARI object appears in a situation that requires integer,
598             numeric, boolean or string data, it is converted to the corresponding
599             type. Boolean conversion is subject to usual PARI pitfalls related to
600             imprecise zeros (see documentation of C in PARI reference).
601              
602             For details on overloading, see L.
603              
604             Note that a check for equality is subject to same pitfalls as in PARI
605             due to imprecise values. PARI may also refuse to compare data of
606             different types for equality if it thinks this may lead to
607             counterintuitive results.
608              
609             Note also that in PARI the numeric ordering is not defined for some
610             types of PARI objects. For string comparison operations we use
611             PARI-lexicographical ordering.
612              
613             =head1 PREREQUISITES
614              
615             =head2 Perl
616              
617             In the versions of perl earlier than 5.003 overloading used a
618             different interface, so you may need to convert C line
619             to C<%OVERLOAD>, or, better, upgrade.
620              
621             =head2 PARI
622              
623             Starting from version 2.0, this module comes without a PARI library included.
624              
625             For the source of PARI library see
626             L.
627              
628             =head1 Perl vs. PARI: different syntax
629              
630             Note that the PARI notations should be used in the string arguments to
631             PARI() function, while the Perl notations should be used otherwise.
632              
633             =over 4
634              
635             =item C<^>
636              
637             Power is denoted by C<**> in Perl.
638              
639             =item C<\> and C<\/>
640              
641             There are no such operators in Perl, use the word forms
642             C and C instead.
643              
644             =item C<~>
645              
646             There is no postfix C<~> Perl operator. Use mattranspose() instead.
647              
648             =item C<'>
649              
650             There is no postfix C<'> Perl operator. Use deriv() instead.
651              
652             =item C
653              
654             There is no postfix C Perl operator. Use factorial()/ifact() instead
655             (returning a real or an integer correspondingly).
656              
657             =item big integers
658              
659             Perl converts big I integers to doubles if they could not be
660             put into B integers (the particular flavor can be found in the
661             output of C in newer version of Perl, look for
662             C/C). If you want to input such an integer, use
663              
664             while ($x < PARI('12345678901234567890')) ...
665              
666             instead of
667              
668             while ($x < 12345678901234567890) ...
669              
670             Why? Because conversion to double leads to precision loss (typically
671             above 1e15, see L), and you will get something like
672             12345678901234567168 otherwise.
673              
674             Starting from version 5.005 of Perl, if the tag C<:int> is used on the
675             'use Math::Pari' line, all of the integer literals in Perl will be
676             automatically converted to became PARI objects. E.g.,
677              
678             use Math::Pari ':int';
679             print 2**1000;
680              
681             is equivalent to
682              
683             print PARI(2)**PARI(1000);
684              
685             Similarly, large integer literals do not lose precision.
686              
687             This directive is lexically scoped. There is a similar tag C<:hex>
688             which affects hexadecimal, octal and binary constants. One may
689             also need to use tag C<:float> for auto-conversion of large integer literals
690             which Perl considers as floating point literals (see L with arguments>
691             for details).
692              
693             =item doubles
694              
695             Doubles in Perl are typically of precision approximately 15 digits
696             (see L). When you use them as arguments to PARI
697             functions, they are converted to PARI real variables, and due to
698             intermediate 15-digits-to-binary conversion of Perl variables the
699             result may be different than with the PARI many-digits-to-binary
700             conversion. E.g., C and C differ at 19-th
701             place, as
702              
703             setprecision(38);
704             print pari_print(0.01), "\n",
705             pari_print('0.01'), "\n";
706              
707             shows.
708              
709             Note that setprecision() changes the output format of pari_print() and
710             friends, as well as the default internal precision. The generic
711             PARI===>string conversion does not take into account the output
712             format, thus
713              
714             setprecision(38);
715             print PARI(0.01), "\n",
716             PARI('0.01'), "\n",
717             pari_print(0.01), "\n";
718              
719             will print all the lines with different number of digits after the
720             point: the first one with 22, since the double 0.01 was converted to a
721             low-precision PARI object, the second one with 41, since internal form
722             for precision 38 requires that many digits for representation, and the
723             last one with 39 to have 38 significant digits.
724              
725             Starting from version 5.005 of Perl, if the tag C<:float> is used on
726             the C line, all the float literals in Perl will be
727             automatically converted to became PARI objects. E.g.,
728              
729             use Math::Pari ':float';
730             print atan(1.);
731              
732             is equivalent to
733              
734             print atan(PARI('1.'));
735              
736             Similarly, large float literals do not lose precision.
737              
738             This directive is lexically scoped.
739              
740             =item array base
741              
742             Arrays are 1-based in PARI, are 0-based in Perl. So while array
743             access is possible in Perl, you need to use different indices:
744              
745             $nf = PARI 'nf'; # assume that PARI variable nf contains a number field
746             $a = PARI('nf[7]');
747             $b = $nf->[6];
748              
749             Now $a and $b contain the same value.
750              
751             =item matrices
752              
753             Note that C constructor creates a matrix
754             with specified columns, while in PARI the command C<[1,2,3;4,5,6]>
755             creates a matrix with specified rows. Use a convenience function
756             PARImat_tr() which will transpose a matrix created by PARImat() to use
757             the same order of elements as in PARI.
758              
759             =item builtin perl functions
760              
761             Some PARI functions, like C and C, are Perl
762             (semi-)reserved words. To reach these functions, one should either
763             import them:
764              
765             use Math::Pari qw(length eval);
766              
767             or call them with prefix (like C<&length>) or the full name (like
768             C).
769              
770             =back
771              
772             =head1 High-resolution graphics
773              
774             If you have Term::Gnuplot Perl module installed, you may use high-resolution
775             graphic primitives of B. Before the usage you need to establish
776             a link between Math::Pari and Term::Gnuplot by calling link_gnuplot().
777             You can change the output filehandle by calling set_plot_fh(), and
778             output terminal by calling plotterm(), as in
779              
780             use Math::Pari qw(:graphic asin);
781              
782             link_gnuplot(); # automatically loads Term::Gnuplot
783             plotterm('emtex');
784             plot_outfile_set('out.tex'); # better do after plotterm()
785             ploth($x, .5, .999, sub {asin $x});
786             close FH or die;
787              
788             =head1 libPARI documentation
789              
790             libPARI documentation is included, see L. It is converted
791             from Chapter 3 of B documentation by the F script of GP/PARI.
792              
793             =head1 ENVIRONMENT
794              
795             No environment variables are used.
796              
797             =head1 BUGS
798              
799             =over 5
800              
801             =item *
802              
803             A few of PARI functions are available indirectly only.
804              
805             =item *
806              
807             Using overloading constants with the Perl versions below 5.005_57 could lead to
808             segfaults (at least without C<-D usemymalloc>), as in:
809              
810             use Math::Pari ':int';
811             for ( $i = 0; $i < 10 ; $i++ ) { print "$i\n" }
812              
813             =item *
814              
815             It may be possible that conversion of a Perl value which has both the
816             integer slot and the floating slot set may create a PARI integer, even
817             if the actual value is not an integer.
818              
819             =item *
820              
821             problems with refcounting of array elements and Mod().
822              
823             Workaround: make the modulus live longer than the result of Mod().
824             Until Perl version C<5.6.1>, one should exercise a special care so
825             that the modulus goes out of scope on a different statement than the
826             result:
827              
828             { my $modulus = 125;
829             { my $res = Mod(34, $modulus);
830             print $res;
831             }
832             $fake = 1; # A (fake) statement here is required
833             }
834              
835             Here $res is destructed before the C<$fake = 1> statement, $modulus is
836             destructed before the first statement after the provided block.
837             However, if you remove the C<$fake = 1> statement, both these
838             variables are destructed on the first statement after the provided
839             block (and in a wrong order!).
840              
841             In C<5.6.1> declaring $modulus before $res is all that is needed to
842             circumvent the same problem:
843              
844             { my $modulus = 125;
845             my $res = Mod(34, $modulus);
846             print $res;
847             } # destruction will happen in a correct order.
848              
849             Access to array elements may result in similar problems. Hard to fix
850             since in PARI the data is not refcounted.
851              
852             =item *
853              
854             Legacy implementations of dynalinking require the code of DLL to be
855             compiled to be "position independent" code (PIC). This slows down the
856             execution, while allowing sharing the loaded copy of the DLL between
857             different processes. [On contemporary architectures the same effect
858             is allowed without the position-independent hack.]
859              
860             Currently, PARI assembler files are not position-independent. When
861             compiled for the dynamic linking on legacy systems, this creates a DLL
862             which cannot be shared between processes. Some legacy systems are
863             reported to recognize this situation, and load the DLL as a non-shared
864             module. However, there may be systems (are there?) on which this can
865             cause some "problems".
866              
867             Summary: if the dynaloading on your system requires some kind of C<-fPIC> flag, using "assembler" compiles (anything but C) *may* force you to do a static build (i.e., creation of a custom Perl executable with
868              
869             perl Makefile.PL static
870             make perl
871             make test_static
872              
873             ).
874              
875             =item *
876              
877             isprime() is a misnomer before PARI version 2.3!
878              
879             In older versions of PARI, the one-argument variant of the function isprime()
880             is actually checking for probable primes. Moreover, it has certain problems.
881              
882             B before version 2.3 of PARI, to get probability of
883             misdetecting a prime below 1e-12, call isprime() twice; below 1e-18, call
884             it 3 times; etc. (The algorithm is probabilistic, and the implementation is
885             such that the result depends on which calls to isprime() were performed ealier.)
886              
887             The problems: first, while the default algorithm (before version 2.3) gives practically
888             acceptable results in non-adversarial situations, the worst-case behaviour is
889             significantly worse than the average behaviour. The algorithm is looking for so-called
890             "witnesses" (with up to 10 tries) among random integers; usually, witnesses are abundant. However,
891             there are non-prime numbers for which the fraction of witnesses is close to the theoretical
892             minimum, 0.75; with 10 random tries, the probability
893             of missing a witness for such numbers is close to 1e-6. (The known worst-case numbers M
894             have phi(M)/4 non-witnesses, with M=P(2P-1), prime P, 2P-1 and 4|P+1; the proportion of such
895             numbers near K is expected to be const/sqrt(K)log(K)^2. Note that numbers which have more than
896             about 5% non-witnesses may also be candidates for false positives. Conjecturally, they
897             are of the form (aD+1)(bD+1) with a
898             by high power of 2 (above a=1, b=2 and D is odd); the proportion of such numbers may have
899             a similar asymptotic const/sqrt(K)log(K)^2.)
900              
901             Second, the random number generator is "reset to known state" when PARI library
902             is initialized. That means that the behaviour is actually predictable if one knows
903             which calls to isprime() are performed; an adversary can find non-primes M which will
904             trigger a false positive exactly on the Nth call to isprime(M) (for particular values
905             of N). With enough computing resources, one can find non-primes M for which N is
906             relatively small (with M about 1e9, one can achieve N as low as 1000).
907             Compare with similar (but less abundant) examples for simpler algorithm,
908             L;
909             see also L and L
910             with many non-witnesses|http://oeis.org/A141768>, and L
911             proportion|http://web.archive.org/web/*/http://www.ma.iup.edu/MAA/proceedings/vol1/higgins.pdf>.
912              
913             See L.
914              
915             =back
916              
917             =head1 INITIALIZATION
918              
919             When Math::Pari is loaded, it examines variables $Math::Pari::initmem
920             and $Math::Pari::initprimes. They specify up to which number the
921             initial list of primes should be precalculated, and how large should
922             be the arena for PARI calculations (in bytes). (These values have
923             safe defaults.)
924              
925             Since setting these values before loading requires either a C
926             block, or postponing the loading (C vs. C), it may be
927             more convenient to set them via Math::PariInit:
928              
929             use Math::PariInit qw( primes=12000000 stack=1e8 );
930              
931             C also accepts arbitrary Math::Pari import directives,
932             see L.
933              
934             These values may be changed at runtime too, via allocatemem() and
935             setprimelimit(), with performance penalties for recalculation/reallocation.
936              
937             =head1 AUTHOR
938              
939             Ilya Zakharevich, I
940              
941             =cut
942              
943 25     25   5715 use strict;
  25         70  
  25         1491  
944              
945             # $Id: Pari.pm,v 1.3 1994/11/25 23:40:52 ilya Exp ilya $
946             package Math::Pari::Arr;
947              
948             #sub TIEARRAY { $_[0] }
949 0     0   0 sub STORE { die "Storing into array elements unsupported" }
950              
951             package Math::Pari; # %converted $initmem $initprimes inspected by xs
952 25         4417 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT $AUTOLOAD
953 25     25   115 %converted $initmem $initprimes %names %sections); # XXX may need to access %names %sections?
  25         43  
954              
955             require Exporter;
956             require DynaLoader;
957             #use autouse Carp => 'croak';
958              
959             @ISA = qw(Exporter DynaLoader);
960             @Math::Pari::Ep::ISA = qw(Math::Pari);
961              
962             # Items to export into callers namespace by default
963             # (move infrequently used names to @EXPORT_OK below)
964              
965             @EXPORT = qw(
966             PARI PARIcol PARImat PARIvecL PARIcolL PARImatL PARIvar PARImat_tr parse_as_gp
967             );
968              
969             # Other items we are prepared to export if requested (may be extended during
970             # ->import. )
971             @EXPORT_OK = qw(
972             sv2pari sv2parimat pari2iv pari2nv pari2num pari2pv pari2bool loadPari _bool
973             listPari pari_print pari_pprint pari_texprint O ifact gdivent gdivround
974             changevalue set_plot_fh plot_outfile_set link_gnuplot setprecision setseriesprecision
975             setprimelimit allocatemem type_name pari2num_
976             );
977              
978 25         111 use subs qw(
979             _gneg
980             _gadd
981             _gsub
982             _gmul
983             _gdiv
984             _gmod
985             _gpui
986             _gle
987             _gge
988             _glt
989             _ggt
990             _geq
991             _gne
992             _gcmp
993             _lex
994             _2bool
995             pari2pv
996             pari2num
997             pari2num_
998             _abs
999             _cos
1000             _sin
1001             _exp
1002             _log
1003             _sqrt
1004             _gbitand
1005             _gbitor
1006             _gbitxor
1007             _gbitneg
1008             _to_int
1009             _gbitshiftr
1010             _gbitshiftl
1011 25     25   11322 ); # Otherwise overload->import would complain...
  25         574  
1012              
1013             my $two;
1014              
1015             sub _shiftl {
1016 0     0   0 my ($left,$right) = (shift,shift);
1017 0 0       0 ($left,$right) = ($right, $left) if shift;
1018 0         0 $left * $two**$right;
1019             }
1020              
1021             sub _shiftr {
1022 7     7   33 my ($left,$right) = (shift,shift);
1023 7 100       15 ($left,$right) = ($right, $left) if shift;
1024 7         137 floor($left / $two**$right);
1025             }
1026              
1027             $initmem ||= 4000000; # How much memory for the stack
1028             $initprimes ||= 500000; # Calculate primes up to this number
1029              
1030             $VERSION = '2.03052201';
1031              
1032             my $true = 1;
1033             # Propagate sv_true, sv_false to SvIOK:
1034             my $dummy = pack 'ii', $true == 1, $true == 0;
1035              
1036             bootstrap Math::Pari;
1037              
1038 25         152 use overload qw(
1039             neg _gneg
1040             + _gadd
1041             - _gsub
1042             * _gmul
1043             / _gdiv
1044             % _gmod
1045             ** _gpui
1046             <= _gle
1047             >= _gge
1048             < _glt
1049             > _ggt
1050             == _geq
1051             != _gne
1052             <=> _gcmp
1053             cmp _lex
1054             bool _2bool
1055             "" pari2pv
1056             0+ pari2num_
1057             abs _abs
1058             cos _cos
1059             sin _sin
1060             exp _exp
1061             log _log
1062             sqrt _sqrt
1063             int _to_int
1064 25     25   14090 );
  25         4662  
1065              
1066             if (pari_version_exp() >= 2000018) {
1067             'overload'->import( qw(
1068             | _gbitor
1069             & _gbitand
1070             ^ _gbitxor
1071             ~ _gbitneg
1072             ) );
1073             }
1074              
1075             if (pari_version_exp() >= 2002001) {
1076             'overload'->import( qw( << _gbitshiftl ) );
1077             } else {
1078             'overload'->import( qw( << _shiftl ) );
1079             }
1080             if (pari_version_exp() >= 2002001 && pari_version_exp() <= 2002007) {
1081             'overload'->import( qw( >> _gbitshiftr ) );
1082             } else {
1083             'overload'->import( qw( >> _shiftr ) );
1084             }
1085              
1086             sub AUTOLOAD {
1087 117     117   6492 $AUTOLOAD =~ /^(?:Math::Pari::)?(.*)/;
1088             # warn "Autoloading $1...\n";
1089             # exit 4 if $1 eq 'loadPari';
1090 117         1052 my $cv = loadPari($1);
1091              
1092             # goto &$cv;
1093             # goto &$AUTOLOAD;
1094             # &$cv;
1095 25     25   10890 no strict 'refs';
  25         48  
  25         34362  
1096 117         14162 &$1;
1097             # &$AUTOLOAD;
1098             }
1099              
1100             # Needed this guy to circumvent autoloading while no XS definition
1101              
1102             #### sub DESTROY {}
1103              
1104              
1105             # sub AUTOLOAD {
1106             # if ((caller(0))[4]) {
1107             # $AutoLoader::AUTOLOAD = $AUTOLOAD;
1108             # goto &AutoLoader::AUTOLOAD;
1109             # }
1110             # local($constname);
1111             # ($constname = $AUTOLOAD) =~ s/.*:://;
1112             # $val = constant($constname, @_ ? $_[0] : 0);
1113             # if ($! != 0) {
1114             # if ($! =~ /Invalid/) {
1115             # $AutoLoader::AUTOLOAD = $AUTOLOAD;
1116             # goto &AutoLoader::AUTOLOAD;
1117             # }
1118             # else {
1119             # ($pack,$file,$line) = caller;
1120             # die "Your vendor has not defined Math::Pari macro $constname, used at $file line $line.
1121             # ";
1122             # }
1123             # }
1124             # eval "sub $AUTOLOAD { $val }";
1125             # goto &$AUTOLOAD;
1126             # }
1127              
1128             # Preloaded methods go here. Autoload methods go after __END__, and are
1129             # processed by the autosplit program.
1130              
1131             sub new {
1132 7     7 0 502 shift;
1133 7 50       17 if (@_>1) {my(@t)=@_;return sv2pari(\@t)}
  0         0  
  0         0  
1134 7         160 return sv2pari(shift);
1135             }
1136              
1137             ###sub PARI {new Math::Pari @_}
1138              
1139             %names = qw(
1140             1 standard
1141             2 conversions
1142             3 transcendental
1143             4 number
1144             5 elliptic
1145             6 fields
1146             7 polynomials
1147             8 vectors
1148             9 sums
1149             10 graphic
1150             11 programming
1151              
1152             100 l_functions
1153             101 modular_symb
1154             102 algebras
1155             103 combinatorics
1156             104 modular
1157             );
1158             @sections{values %names} = keys %names;
1159             # warn "No code to handle added sections yet" if added_sections(); # Now tested in 02_sections.t
1160              
1161             if (pari_version_exp() < 2009000) {
1162             *listPari = \&_listPari;
1163 0     0   0 *old2newsec = sub ($) {shift};
1164             } else { # XXX only 2.9.* supported so far
1165             my %sec2;
1166             if (pari_version_exp() < 2011000) {
1167             %sec2 = (100 => 6+2, 101 => 7+2, 102 => 9+2, map {($_, $_ + 2 + 2*($_>=6) + ($_>=7))} -1..11);
1168             } else {
1169             my @S = (0, 2, 3, 8, 5, 12, 10, 6, 7, undef, 16, 1); # (1,2,4) +1; 3 -> 8, (5,6) -> (12,10), (7,8) -> -1, (10,11) -> 16,1
1170             my @aS = (13,15,11,4,14);
1171             %sec2 = (-1, 1, map {($_, 2+($S[$_] || $aS[$_-100] || $_))} 0..11, 100..104);
1172             }
1173             *old2newsec = sub ($) {($sec2{shift()} || 202) - 2}; # unknowns => 200
1174             *listPari = sub ($) {_listPari(($sec2{shift()} || 202) - 2)};
1175             # *listPari = sub ($) {_listPari(old2newsec(shift))};
1176             }
1177              
1178             # buch* not appearing in newer PARIs (at least as of 2.3.5)
1179             @converted{qw(buchimag buchreal
1180             buchgen buchgenforcefu buchgenfu buchinit buchinitforcefu buchinitfu
1181             plotstring addhelp kill)} = (1) x 100;
1182              
1183             # Now even tested...
1184 6     6   150 sub _cvt { PARI(shift) }
1185             sub _hex_cvt {
1186 7     7   19 my $in = shift;
1187 7         20 my $mult = PARI(1);
1188 7         9 my $ret = 0;
1189 7         8 my $shift = 1<<(4*7);
1190              
1191 7 50       33 $in =~ s/^0([xb])?// or die;
1192 7         15 my $hex = $1;
1193 7 100 100     25 if ($hex and $1 eq 'b') {
1194 5         33 my $b = '0' x (15 * length($in) % 16) . $in;
1195 5         8 $hex = '';
1196 5         7 while ($b) {
1197 21         28 my $s = substr $b, 0, 16;
1198 21         25 substr($b, 0, 16) = '';
1199 21         58 $hex .= unpack 'H4', pack 'B16', $s;
1200             }
1201 5         8 $in = $hex;
1202             }
1203 7 100       12 $shift = 1<<(3*7) unless $hex;
1204 7         26 while ($in =~ s/([a-fA-F\d]{1,7})$//) {
1205             # In 5.6.0 hex() can return a floating number:
1206 16 50       40 my $part = int($hex ? hex $1 : oct $1);
1207              
1208 16         78 $ret += $part * $mult;
1209 16         104 $mult *= $shift;
1210             }
1211 7 50       47 die "Cannot hex '$in'" if length $in;
1212 7         177 return $ret;
1213             }
1214             my %overloaded_const = ( 'int' => \&_cvt, float => \&_cvt, 'hex' => \&_hex_cvt);
1215             my %overloaded_const_word
1216             = ( 'int' => 'integer', float => 'float', 'hex' => 'binary');
1217              
1218             my %export_ok;
1219              
1220             sub import {
1221 31     31   387 my $p=shift;
1222 31         52 my @const; # Need to do it outside any block!
1223             @_ = map {
1224 31 100       74 if (/^:(?!DEFAULT)(.*)/) {
  66         251  
1225 23         70 my $tag = $1;
1226 23         38 my $sect = $tag;
1227 23         29 my @pre;
1228 23 100       143 $tag = -1, @pre = (@EXPORT_OK,@EXPORT) if ($tag eq 'all');
1229 23 50       66 $tag = -1 if ($tag eq 'PARI');
1230 23 50 66     111 $tag = $sections{$tag} if $tag !~ /^-?\d+$/ and exists $sections{$tag};
1231 23 50       265 push @pre, 'link_gnuplot', 'set_plot_fh', 'plot_outfile_set' if $tag eq $sections{graphic};
1232 23 50 33     211 if ($tag =~ /^prec=(\d+)$/) {
    100          
    50          
1233 0         0 setprecision($1);
1234 0         0 ();
1235             } elsif ($tag =~ /^(int|hex|float)$/) {
1236 3 50       9 die "Overloaded constants are not supported in this version of Perl"
1237             if $] < 5.004_69;
1238 3         16 push @const, $overloaded_const_word{$tag} => $overloaded_const{$tag};
1239             # print "Constants: $overloaded_const_word{$tag} => $overloaded_const{$tag} \n";
1240 3         8 ();
1241             } elsif (defined $tag and $tag =~ /^-?\d+$/) {
1242 20         3270 (@pre, listPari($tag));
1243             } else {
1244 0         0 die "Unknown section '$sect' specified";
1245             }
1246             } else {
1247 43         98 ($_);
1248             }
1249             } @_;
1250              
1251 31         195 overload::constant(splice @const, 0, 2) while @const;
1252              
1253             # print "EXPORT_OK: @EXPORT_OK\n";
1254             push @EXPORT_OK,
1255             grep( ($_ ne ':DEFAULT'
1256             and not $export_ok{$_}++
1257 31   66     1363 and (eval {loadPari($_), 1} or warn $@), !$@) ,
1258             @_);
1259             # Invalidate Exporter cache, so that new %EXPORT_OK is noticed:
1260 31         114 undef %EXPORT;
1261             # print "EXPORT_OK: @EXPORT_OK\n";
1262 31         60387 &Exporter::export($p,(caller(0))[0],@_);
1263             }
1264              
1265             sub _can { # Without taking into account inheritance...
1266 3     3   121 my ($obj, $meth) = (shift, shift);
1267 3 100       15 return \&$meth if defined &$meth;
1268 2 100       3 return \&$meth if eval {loadPari($meth), 1};
  2         26  
1269 1         4 return;
1270             }
1271              
1272             sub can {
1273 7     7 0 1136 my ($obj, $meth) = (@_);
1274 7         41 my $f = $obj->SUPER::can($meth);
1275 7 100       26 return $f if defined $f;
1276             # There is no "usual" way to get the function; try loadPari()
1277 3         5 $f = eval { loadPari($meth) };
  3         59  
1278 3 100       14 return $f if defined $f;
1279 1         5 return;
1280             }
1281              
1282             sub O ($;$) {
1283 3 100   3 0 161 return PARI("O($_[0]^$_[1])") if @_ == 2;
1284 1 50       20 return PARI("O($_[0])") if typ($_[0]) == 10; # Poly
1285 0         0 Carp::croak("O(number**power) not implemented, use O(number,power) instead");
1286             }
1287              
1288 59     59 1 7080 sub PARImat_tr {mattranspose(PARImat(@_))}
1289             #sub string ($$) {
1290             # PARI (qq'string($_[0],"$_[1]")');
1291             #}
1292              
1293 1     1 0 60 sub installPerlFunction {my @a=@_; $a[0] = \&{$a[0]}; installPerlFunctionCV(@a)}
  1         2  
  1         3  
  1         12  
1294              
1295             my $name;
1296              
1297             for $name (keys %converted) {
1298             push @EXPORT_OK, $name;
1299             next if defined &$name;
1300             # string needs to format numbers to 8.3...
1301 25     25   188 no strict 'refs';
  25         49  
  25         25536  
1302             if ($name eq 'addhelp' or $name eq 'plotstring') {
1303 4     4   104 *$name = sub { PARI ( qq($name($_[0],"$_[1]")) ) }
1304             } else { # probably `kill' only
1305 1     1   3 *$name = sub { local $"=','; PARI("$name(@_)") } # "
  1         22  
1306             }
1307             }
1308              
1309             @export_ok{@EXPORT_OK,@EXPORT} = (1) x (@EXPORT_OK + @EXPORT);
1310              
1311       0     sub __my_NOP {}
1312              
1313             my %supported_cmd = qw(q 0 p setprecision e __my_NOP); # ??? WRONG !!!
1314             my $supported_cmd_rx = '(?:' . join( '|', keys %supported_cmd) . ')';
1315             $supported_cmd_rx = qr($supported_cmd_rx);
1316             my $matched_par;
1317             $matched_par = qr[[^()]*(?:\((??{$matched_par})\)[^()]*)*]; # arbitrary string with ( and ) matching
1318              
1319 0     0 0 0 sub remove_nl ($) { (my $in = shift) =~ s/\n//g; $in }
  0         0  
1320              
1321             my %POSTF = qw(K 1 M 2 G 3 T 4);
1322             sub allocatemem_prot ($) {
1323 0     0 0 0 my $mem = shift;
1324 0         0 $mem =~ s/^(.*)([KMGT])/$1*1000**$POSTF{$2}/e;
  0         0  
1325 0 0 0     0 eval {allocatemem($mem); 1} or $@ =~ /^PARI:\s\sat\s+\S*\s+line\s+\d+\.?\s*$/ or die "allocatemem($mem) died: $@"
  0         0  
  0         0  
1326             }
1327              
1328 1444     1444 0 111770 sub MP___a___($) { $Math::Pari::__args::a->[shift] }
1329             sub __wrap_PARI_macro ($) {
1330 7     7   44 my $name = shift;
1331             sub {
1332 1444     1444   2392 local $Math::Pari::__args::a = [@_];
1333 1444         11562 PARI("$name(" . (join ',', map "MP___a___($_)", 0..$#_) . ")")
1334             }
1335 7         55 }
1336              
1337             sub PARI_with_default_mem ($) {
1338 19     19 0 39 my($in) = shift;
1339 19 50       997 $in =~ s/(?:^|;)default\(parisize,("?)($matched_par)\1\)\s*$// or return PARI($in);
1340 0         0 my $s = "$2";
1341 0         0 PARI($in);
1342 0         0 allocatemem_prot($s);
1343             }
1344              
1345             sub parse_as_gp ($;$$$) { # string, quote-and-return, , count to use on the first numbered output (like %33 = 2*x+1)
1346 13     13 1 174 my($in, $quote, $echo, $c, $def) = (shift, shift, shift, shift);
1347 13   33     101 $def = ($quote and ($quote eq 'define' or ref $quote) and $quote);
1348 13 50 66 0   58 $def = sub ($) {shift} if $def and not ref $def;
  0         0  
1349 13   66     61 $quote = ($quote and not $def);
1350 13 100       71 $in =~ s/(\\(?!\\)|\/(?!\*)|[^"\s\\\/]|\n|"([^"\\]|\\.)*")|\/\*.*?\*\/|[^\S\n\/]+|\\\\[^\n]*/ defined($1) ? $1 : '' /ges;
  209         548  
1351             # Now all unneeded whitespace (except LF) and comments are removed
1352 13         65 $in =~ s/(?:^\s*\{|\{\s*$)(.*?)(?:^\s*\}|\}\s*$)/ remove_nl $1 /gems; # XXXX In fact, braces may appear everywhere??? Strings?
  0         0  
1353 13         47 $in =~ s/(?<=[-=+*\/%^><|&,\(\[])\n(?