aboutsummaryrefslogtreecommitdiff
path: root/src/algebra/polycat.spad.pamphlet
blob: 4f0d80dded924211c98c1f5bbdbd978ecbd239dc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
\documentclass{article}
\usepackage{open-axiom}
\begin{document}
\title{\$SPAD/src/algebra polycat.spad}
\author{Manuel Bronstein}
\maketitle
\begin{abstract}
\end{abstract}
\eject
\tableofcontents
\eject
\section{category AMR AbelianMonoidRing}
<<category AMR AbelianMonoidRing>>=
)abbrev category AMR AbelianMonoidRing
++ Author:
++ Date Created:
++ Date Last Updated: May 19, 2013.
++ Basic Functions:
++ Related Constructors:
++ Also See:
++ AMS Classifications:
++ Keywords:
++ References:
++ Description:
++ Abelian monoid ring elements (not necessarily of finite support)
++ of this ring are of the form formal SUM (r_i * e_i)
++ where the r_i are coefficents and the e_i, elements of the
++ ordered abelian monoid, are thought of as exponents or monomials.
++ The monomials commute with each other, and with
++ the coefficients (which themselves may or may not be commutative).
++ See \spadtype{FiniteAbelianMonoidRing} for the case of finite support
++ a useful common model for polynomials and power series.
++ Conceptually at least, only the non-zero terms are ever operated on.

AbelianMonoidRing(R:Ring, E:OrderedAbelianMonoid): Category ==
        Join(Ring,BiModule(R,R),Functorial R) with
    leadingCoefficient: % -> R
      ++ leadingCoefficient(p) returns the coefficient highest degree term of p.
    leadingMonomial: % -> %
      ++ leadingMonomial(p) returns the monomial of p with the highest degree.
    degree: % -> E
      ++ degree(p) returns the maximum of the exponents of the terms of p.
    monomial?: % -> Boolean
      ++ monomial?(p) tests if p is a single monomial.
    monomial: (R,E) -> %
      ++ monomial(r,e) makes a term from a coefficient r and an exponent e.
    reductum: % -> %
         ++ reductum(u) returns u minus its leading monomial
         ++ returns zero if handed the zero element.
    coefficient: (%,E) -> R
         ++ coefficient(p,e) extracts the coefficient of the monomial with
         ++ exponent e from polynomial p, or returns zero if exponent is not present.
    if R has Field then /: (%,R) -> %
         ++ p/c divides p by the coefficient c.
    if R has CommutativeRing then
       CommutativeRing
       Algebra R
    if R has CharacteristicZero then CharacteristicZero
    if R has CharacteristicNonZero then CharacteristicNonZero
    if R has IntegralDomain then IntegralDomain
    if R has Algebra Fraction Integer then Algebra Fraction Integer
  add
    monomial? x == zero? reductum x

    map(fn:R -> R, x: %) ==
          -- this default definition assumes that reductum is cheap
       zero? x => 0
       r:=fn leadingCoefficient x
       zero? r => map(fn,reductum x)
       monomial(r, degree x) + map(fn,reductum x)

    if R has Algebra Fraction Integer then
      q:Fraction(Integer) * p:% == map(q * #1, p)

@
\section{category FAMR FiniteAbelianMonoidRing}
<<category FAMR FiniteAbelianMonoidRing>>=
import Boolean
import NonNegativeInteger
import List
)abbrev category FAMR FiniteAbelianMonoidRing
++ Author:
++ Date Created:
++ Date Last Updated: 14.08.2000 Exported pomopo! and binomThmExpt [MMM]
++ Basic Functions:
++ Related Constructors:
++ Also See:
++ AMS Classifications:
++ Keywords:
++ References:
++ Description: This category is
++ similar to AbelianMonoidRing, except that the sum is assumed to be finite.
++ It is a useful model for polynomials,
++ but is somewhat more general.

FiniteAbelianMonoidRing(R:Ring, E:OrderedAbelianMonoid): Category ==
   Join(AbelianMonoidRing(R,E),FullyRetractableTo R) with
    ground?: % -> Boolean
      ++ ground?(p) tests if polynomial p is a member of the coefficient ring.
                    -- can't be defined earlier, since a power series
                    -- might not know if there were other terms or not
    ground: % -> R
      ++ ground(p) retracts polynomial p to the coefficient ring.
    coefficients: % -> List R
      ++ coefficients(p) gives the list of non-zero coefficients of polynomial p.
    numberOfMonomials: % -> NonNegativeInteger
      ++ numberOfMonomials(p) gives the number of non-zero monomials in polynomial p.
    minimumDegree: % -> E
      ++ minimumDegree(p) gives the least exponent of a non-zero term of polynomial p.
      ++ Error: if applied to 0.
    mapExponents: (E -> E, %) -> %
      ++ mapExponents(fn,u) maps function fn onto the exponents
      ++ of the non-zero monomials of polynomial u.
    pomopo!: (%,R,E,%) -> %
         ++ \spad{pomopo!(p1,r,e,p2)} returns \spad{p1 + monomial(e,r) * p2}
         ++ and may use \spad{p1} as workspace. The constaant \spad{r} is
         ++ assumed to be nonzero.
    if R has CommutativeRing then
       binomThmExpt: (%,%,NonNegativeInteger) -> %
         ++ \spad{binomThmExpt(p,q,n)} returns \spad{(x+y)^n}
         ++ by means of the binomial theorem trick.
    if R has IntegralDomain then
       exquo: (%,R) -> Union(%,"failed")
       ++ exquo(p,r) returns the exact quotient of polynomial p by r, or "failed"
       ++ if none exists.
    if R has GcdDomain then
       content: % -> R
         ++ content(p) gives the gcd of the coefficients of polynomial p.
       primitivePart: % -> %
         ++ primitivePart(p) returns the unit normalized form of polynomial p
         ++ divided by the content of p.
  add
    pomopo!(p1,r,e,p2) == p1 + r * mapExponents(#1+e,p2)

    if R has CommutativeRing then 
       binomThmExpt(x,y,nn) ==
               nn = 0 => 1$%
               ans,yn: %
               bincoef: Integer
               powl: List(%):= [x]
               for i in 2..nn repeat powl:=[x * powl.first, :powl]
               yn := y
               ans := powl.first
               i: Integer := 1
               bincoef := nn
               for xn in powl.rest repeat
                  ans:= bincoef * xn * yn + ans
                  bincoef:= (nn-i) * bincoef quo (i+1);  i:= i+1
                  -- last I and BINCOEF unused
                  yn:= y * yn
               ans + yn
    ground? x ==
      retractIfCan(x)@Union(R,"failed") case "failed" => false
      true
    ground x == retract(x)@R
    mapExponents (fn:E -> E, x: %) ==
         -- this default definition assumes that reductum is cheap
       zero? x => 0
       monomial(leadingCoefficient x,fn degree x)+mapExponents(fn,reductum x)
    coefficients x ==
      zero? x => empty()
      concat(leadingCoefficient x, coefficients reductum x)

    if R has Field then
       x/r == map(#1/r,x)
    if R has IntegralDomain then
       (x: %) exquo (r: R) ==
          -- probably not a very good definition in most special cases
          zero? x => 0
          ans:% :=0
          t:=leadingCoefficient x exquo r
          while not (t case "failed") and not zero? x repeat
            ans:=ans+monomial(t::R,degree x)
            x:=reductum x
            if not zero? x then t:=leadingCoefficient x exquo r
          t case "failed" => "failed"
          ans
    if R has GcdDomain then
       content x ==       -- this assumes  reductum is cheap
          zero? x => 0
          r:=leadingCoefficient x
          x:=reductum x
          while not zero? x and not one? r repeat
            r:=gcd(r,leadingCoefficient x)
            x:=reductum x
          r
       primitivePart x ==
          zero? x => x
          c := content x
          unitCanonical((x exquo c)::%)

@
\section{category POLYCAT PolynomialCategory}
<<category POLYCAT PolynomialCategory>>=
)abbrev category POLYCAT PolynomialCategory
++ Author:
++ Date Created:
++ Date Last Updated:
++ Basic Functions: Ring, monomial, coefficient, differentiate, eval
++ Related Constructors: Polynomial, DistributedMultivariatePolynomial
++ Also See: UnivariatePolynomialCategory
++ AMS Classifications:
++ Keywords:
++ References:
++ Description:
++ The category for general multi-variate polynomials over a ring
++ R, in variables from VarSet, with exponents from the
++ \spadtype{OrderedAbelianMonoidSup}.

PolynomialCategory(R:Ring, E:OrderedAbelianMonoidSup, VarSet:OrderedSet):
        Category ==
  Join(PartialDifferentialRing VarSet, FiniteAbelianMonoidRing(R, E),
       Evalable %, InnerEvalable(VarSet, R),
       InnerEvalable(VarSet, %), RetractableTo VarSet,
       FullyLinearlyExplicitRingOver R) with
    -- operations
    degree : (%,VarSet) -> NonNegativeInteger
      ++ degree(p,v) gives the degree of polynomial p with respect to the variable v.
    degree : (%,List(VarSet)) -> List(NonNegativeInteger)
      ++ degree(p,lv) gives the list of degrees of polynomial p
      ++ with respect to each of the variables in the list lv.
    coefficient: (%,VarSet,NonNegativeInteger) -> %
      ++ coefficient(p,v,n) views the polynomial p as a univariate
      ++ polynomial in v and returns the coefficient of the \spad{v**n} term.
    coefficient: (%,List VarSet,List NonNegativeInteger) -> %
      ++ coefficient(p, lv, ln) views the polynomial p as a polynomial
      ++ in the variables of lv and returns the coefficient of the term
      ++ \spad{lv**ln}, i.e. \spad{prod(lv_i ** ln_i)}.
    monomials: % -> List %
      ++ monomials(p) returns the list of non-zero monomials of polynomial p, i.e.
      ++ \spad{monomials(sum(a_(i) X^(i))) = [a_(1) X^(1),...,a_(n) X^(n)]}.
    univariate   : (%,VarSet) -> SparseUnivariatePolynomial(%)
      ++ univariate(p,v) converts the multivariate polynomial p
      ++ into a univariate polynomial in v, whose coefficients are still
      ++ multivariate polynomials (in all the other variables).
    univariate   : % -> SparseUnivariatePolynomial(R)
        ++ univariate(p) converts the multivariate polynomial p,
        ++ which should actually involve only one variable,
        ++ into a univariate polynomial
        ++ in that variable, whose coefficients are in the ground ring.
        ++ Error: if polynomial is genuinely multivariate
    mainVariable  : % -> Union(VarSet,"failed")
           ++ mainVariable(p) returns the biggest variable which actually
           ++ occurs in the polynomial p, or "failed" if no variables are
           ++ present.
           ++ fails precisely if polynomial satisfies ground?
    minimumDegree : (%,VarSet) -> NonNegativeInteger
      ++ minimumDegree(p,v) gives the minimum degree of polynomial p
      ++ with respect to v, i.e. viewed a univariate polynomial in v
    minimumDegree : (%,List(VarSet)) -> List(NonNegativeInteger)
      ++ minimumDegree(p, lv) gives the list of minimum degrees of the
      ++ polynomial p with respect to each of the variables in the list lv
    monicDivide : (%,%,VarSet) -> Record(quotient:%,remainder:%)
       ++ monicDivide(a,b,v) divides the polynomial a by the polynomial b,
       ++ with each viewed as a univariate polynomial in v returning
       ++ both the quotient and remainder.
       ++ Error: if b is not monic with respect to v.
    monomial : (%,VarSet,NonNegativeInteger) -> %
        ++ monomial(a,x,n) creates the monomial \spad{a*x**n} where \spad{a} is
        ++ a polynomial, x is a variable and n is a nonnegative integer.
    monomial : (%,List VarSet,List NonNegativeInteger) -> %
        ++ monomial(a,[v1..vn],[e1..en]) returns \spad{a*prod(vi**ei)}.
    multivariate : (SparseUnivariatePolynomial(R),VarSet) -> %
        ++ multivariate(sup,v) converts an anonymous univariable
        ++ polynomial sup to a polynomial in the variable v.
    multivariate : (SparseUnivariatePolynomial(%),VarSet) -> %
        ++ multivariate(sup,v) converts an anonymous univariable
        ++ polynomial sup to a polynomial in the variable v.
    isPlus: % -> Union(List %, "failed")
        ++ isPlus(p) returns \spad{[m1,...,mn]} if polynomial \spad{p = m1 + ... + mn} and
        ++ \spad{n >= 2} and each mi is a nonzero monomial.
    isTimes: % -> Union(List %, "failed")
        ++ isTimes(p) returns \spad{[a1,...,an]} if polynomial \spad{p = a1 ... an}
        ++ and \spad{n >= 2}, and, for each i, ai is either a nontrivial constant in R or else of the
        ++ form \spad{x**e}, where \spad{e > 0} is an integer and x in a member of VarSet.
    isExpt: % -> Union(Record(var:VarSet, exponent:NonNegativeInteger),_
                       "failed")
        ++ isExpt(p) returns \spad{[x, n]} if polynomial p has the form \spad{x**n} and \spad{n > 0}.
    totalDegree : % -> NonNegativeInteger
        ++ totalDegree(p) returns the largest sum over all monomials
        ++ of all exponents of a monomial.
    totalDegree : (%,List VarSet) -> NonNegativeInteger
        ++ totalDegree(p, lv) returns the maximum sum (over all monomials of polynomial p)
        ++ of the variables in the list lv.
    variables : % -> List(VarSet)
        ++ variables(p) returns the list of those variables actually
        ++ appearing in the polynomial p.
    primitiveMonomials: % -> List %
        ++ primitiveMonomials(p) gives the list of monomials of the
        ++ polynomial p with their coefficients removed.
        ++ Note: \spad{primitiveMonomials(sum(a_(i) X^(i))) = [X^(1),...,X^(n)]}.
    -- OrderedRing view removed to allow EXPR to define abs
    --if R has OrderedRing then OrderedRing
    if (R has ConvertibleTo InputForm) and
       (VarSet has ConvertibleTo InputForm) then
         ConvertibleTo InputForm
    if (R has ConvertibleTo Pattern Integer) and
       (VarSet has ConvertibleTo Pattern Integer) then
         ConvertibleTo Pattern Integer
    if (R has ConvertibleTo Pattern Float) and
       (VarSet has ConvertibleTo Pattern Float) then
         ConvertibleTo Pattern Float
    if (R has PatternMatchable Integer) and
       (VarSet has PatternMatchable Integer) then
         PatternMatchable Integer
    if (R has PatternMatchable Float) and
       (VarSet has PatternMatchable Float) then
         PatternMatchable Float
    if R has CommutativeRing then
      resultant : (%,%,VarSet) -> %
         ++ resultant(p,q,v) returns the resultant of the polynomials
         ++ p and q with respect to the variable v.
      discriminant : (%,VarSet) -> %
         ++ discriminant(p,v) returns the disriminant of the polynomial p
         ++ with respect to the variable v.
    if R has GcdDomain then
      GcdDomain
      content: (%,VarSet) -> %
        ++ content(p,v) is the gcd of the coefficients of the polynomial p
        ++ when p is viewed as a univariate polynomial with respect to the
        ++ variable v.
        ++ Thus, for polynomial 7*x**2*y + 14*x*y**2, the gcd of the
        ++ coefficients with respect to x is 7*y.
      primitivePart: % -> %
        ++ primitivePart(p) returns the unitCanonical associate of the
        ++ polynomial p with its content divided out.
      primitivePart: (%,VarSet) -> %
        ++ primitivePart(p,v) returns the unitCanonical associate of the
        ++ polynomial p with its content with respect to the variable v
        ++ divided out.
      squareFree: % -> Factored %
        ++ squareFree(p) returns the square free factorization of the
        ++ polynomial p.
      squareFreePart: % -> %
        ++ squareFreePart(p) returns product of all the irreducible factors
        ++ of polynomial p each taken with multiplicity one.

    -- assertions
    if R has canonicalUnitNormal then canonicalUnitNormal
             ++ we can choose a unique representative for each
             ++ associate class.
             ++ This normalization is chosen to be normalization of
             ++ leading coefficient (by default).
    if R has PolynomialFactorizationExplicit then
       PolynomialFactorizationExplicit
 add
    ln:List NonNegativeInteger
    lv:List VarSet
    n:NonNegativeInteger
    pp,qq:SparseUnivariatePolynomial %
    eval(p:%, l:List Equation %) ==
      empty? l => p
      for e in l repeat
        retractIfCan(lhs e)@Union(VarSet,"failed") case "failed" => 
             error "cannot find a variable to evaluate"
      lvar:=[retract(lhs e)@VarSet for e in l]
      eval(p, lvar,[rhs e for e in l]$List(%))
    monomials p ==
--    zero? p => empty()
--    concat(leadingMonomial p, monomials reductum p)
--    replaced by sequential version for efficiency, by WMSIT, 7/30/90
      ml:= empty()$List(%)
      while p ~= 0 repeat
        ml:=concat(leadingMonomial p, ml)
        p:= reductum p
      reverse ml
    isPlus p ==
      empty? rest(l := monomials p) => "failed"
      l
    isTimes p ==
      empty?(lv := variables p) or not monomial? p => "failed"
      l := [monomial(1, v, degree(p, v)) for v in lv]
      one?(r := leadingCoefficient p) =>
        empty? rest lv => "failed"
        l
      concat(r::%, l)
    isExpt p ==
      (u := mainVariable p) case "failed" => "failed"
      p = monomial(1, u::VarSet, d := degree(p, u::VarSet)) =>
        [u::VarSet, d]
      "failed"
    coefficient(p,v,n) == coefficient(univariate(p,v),n)
    coefficient(p,lv,ln) ==
       empty? lv =>
         empty? ln => p
         error "mismatched lists in coefficient"
       empty? ln  => error "mismatched lists in coefficient"
       coefficient(coefficient(univariate(p,first lv),first ln),
                   rest lv,rest ln)
    monomial(p,lv,ln) ==
       empty? lv =>
         empty? ln => p
         error "mismatched lists in monomial"
       empty? ln  => error "mismatched lists in monomial"
       monomial(monomial(p,first lv, first ln),rest lv, rest ln)
    retract(p:%):VarSet ==
      q := mainVariable(p)::VarSet
      q::% = p => q
      error "Polynomial is not a single variable"
    retractIfCan(p:%):Union(VarSet, "failed") ==
      ((q := mainVariable p) case VarSet) and (q::VarSet::% = p) => q
      "failed"
    mkPrim(p:%):% == monomial(1,degree p)
    primitiveMonomials p == [mkPrim q for q in monomials p]
    totalDegree p ==
        ground? p => 0
        u := univariate(p, mainVariable(p)::VarSet)
        d: NonNegativeInteger := 0
        while u ~= 0 repeat
          d := max(d, degree u + totalDegree leadingCoefficient u)
          u := reductum u
        d
    totalDegree(p,lv) ==
        ground? p => 0
        u := univariate(p, v:=(mainVariable(p)::VarSet))
        d: NonNegativeInteger := 0
        w: NonNegativeInteger := 0
        if member?(v, lv) then w:=1
        while u ~= 0 repeat
          d := max(d, w*(degree u) + totalDegree(leadingCoefficient u,lv))
          u := reductum u
        d

    if R has CommutativeRing then
        resultant(p1,p2,mvar) ==
          resultant(univariate(p1,mvar),univariate(p2,mvar))
        discriminant(p,var) ==
          discriminant(univariate(p,var))

    if R has IntegralDomain then
      allMonoms(l:List %):List(%) ==
        removeDuplicates! concat [primitiveMonomials p for p in l]
      P2R(p:%, b:List E, n:NonNegativeInteger):Vector(R) ==
        w := new(n, 0)$Vector(R)
        for i in minIndex w .. maxIndex w for bj in b repeat
          qsetelt!(w, i, coefficient(p, bj))
        w
      eq2R(l:List %, b:List E):Matrix(R) ==
        matrix [[coefficient(p, bj) for p in l] for bj in b]
      reducedSystem(m:Matrix %):Matrix(R) ==
        l := listOfLists m
        b := removeDuplicates!
                           concat [allMonoms r for r in l]$List(List(%))
        d := [degree bj for bj in b]
        mm := eq2R(first l, d)
        l := rest l
        while not empty? l repeat
          mm := vertConcat(mm, eq2R(first l, d))
          l := rest l
        mm
      reducedSystem(m:Matrix %, v:Vector %):
       Record(mat:Matrix R, vec:Vector R) ==
        l := listOfLists m
        r := entries v
        b : List % := removeDuplicates! concat(allMonoms r,
                          concat [allMonoms s for s in l]$List(List(%)))
        d := [degree bj for bj in b]
        n := #d
        mm := eq2R(first l, d)
        w := P2R(first r, d, n)
        l := rest l
        r := rest r
        while not empty? l repeat
          mm := vertConcat(mm, eq2R(first l, d))
          w := concat(w, P2R(first r, d, n))
          l := rest l
          r := rest r
        [mm, w]

    if R has PolynomialFactorizationExplicit then
       -- we might be in trouble if its actually only
       -- a univariate polynomial category - have to remember to
       -- over-ride these in UnivariatePolynomialCategory
       PFBR ==>PolynomialFactorizationByRecursion(R,E,VarSet,%)
       gcdPolynomial(pp,qq) ==
          gcdPolynomial(pp,qq)$GeneralPolynomialGcdPackage(E,VarSet,R,%)
       solveLinearPolynomialEquation(lpp,pp) ==
         solveLinearPolynomialEquationByRecursion(lpp,pp)$PFBR
       factorPolynomial(pp) ==
         factorByRecursion(pp)$PFBR
       factorSquareFreePolynomial(pp) ==
         factorSquareFreeByRecursion(pp)$PFBR
       factor p ==
         v:Union(VarSet,"failed"):=mainVariable p
         v case "failed" =>
           ansR:=factor leadingCoefficient p
           makeFR(unit(ansR)::%,
                  [[w.flg,w.fctr::%,w.xpnt] for w in factorList ansR])
         up:SparseUnivariatePolynomial %:=univariate(p,v)
         ansSUP:=factorByRecursion(up)$PFBR
         makeFR(multivariate(unit(ansSUP),v),
                [[ww.flg,multivariate(ww.fctr,v),ww.xpnt]
                 for ww in factorList ansSUP])
       if R has CharacteristicNonZero then
          mat: Matrix %
          conditionP mat ==
            ll:=listOfLists transpose mat   -- hence each list corresponds to a
                                            -- column, i.e. to one variable
            llR:List List R := [ empty() for z in first ll]
            monslist:List List % := empty()
            ch:=characteristic$%
            for l in ll repeat
                mons:= "setUnion"/[primitiveMonomials u for u in l]
                redmons:List % :=[]
                for m in mons repeat
                    vars:=variables m
                    degs:=degree(m,vars)
                    deg1:List NonNegativeInteger
                    deg1:=[ ((nd:=d:Integer exquo ch:Integer)
                               case "failed" => return "failed" ;
                                nd::Integer::NonNegativeInteger)
                           for d in degs ]
                    redmons:=[monomial(1,vars,deg1),:redmons]
                    llR:=[[ground coefficient(u,vars,degs),:v] for u in l for v in llR]
                monslist:=[redmons,:monslist]
            ans:=conditionP transpose matrix llR
            ans case "failed" => "failed"
            i:NonNegativeInteger:=0
            [ +/[m*(ans.(i:=i+1))::% for m in mons ]
              for mons in monslist]

    if R has CharacteristicNonZero then
          charthRootlv: (%,List VarSet,NonNegativeInteger) -> Maybe %
          charthRoot p ==
            vars:= variables p
            empty? vars =>
              ans := charthRoot ground p
              ans case nothing => nothing
              just(ans::R::%)
            ch:=characteristic$%
            charthRootlv(p,vars,ch)
          charthRootlv(p,vars,ch) ==
            empty? vars =>
              ans := charthRoot ground p
              ans case nothing => nothing
              just(ans::R::%)
            v:=first vars
            vars:=rest vars
            d:=degree(p,v)
            ans:% := 0
            while positive? d repeat
               (dd:=(d::Integer exquo ch::Integer)) case "failed" =>
                      return nothing
               cp:=coefficient(p,v,d)
               p:=p-monomial(cp,v,d)
               ansx:=charthRootlv(cp,vars,ch)
               ansx case nothing => return nothing
               d:=degree(p,v)
               ans:=ans+monomial(ansx,v,dd::Integer::NonNegativeInteger)
            ansx:=charthRootlv(p,vars,ch)
            ansx case nothing => return nothing
            return just(ans+ansx)

    monicDivide(p1,p2,mvar) ==
       result:=monicDivide(univariate(p1,mvar),univariate(p2,mvar))
       [multivariate(result.quotient,mvar),
        multivariate(result.remainder,mvar)]


    if R has GcdDomain then
      if R has EuclideanDomain and R has CharacteristicZero then
       squareFree p == squareFree(p)$MultivariateSquareFree(E,VarSet,R,%)
      else
        squareFree p == squareFree(p)$PolynomialSquareFree(VarSet,E,R,%)
      squareFreePart p ==
        unit(s := squareFree p) * */[f.factor for f in factors s]
      content(p,v) == content univariate(p,v)
      primitivePart p ==
        unitNormal((p exquo content p) ::%).canonical
      primitivePart(p,v) ==
        unitNormal((p exquo content(p,v)) ::%).canonical

    before?(p:%, q:%) ==
      (dp:= degree p) < (dq := degree q) => before?(0, leadingCoefficient q)
      dq < dp => before?(leadingCoefficient p,0)
      before?(leadingCoefficient(p - q),0)

    if (R has PatternMatchable Integer) and
       (VarSet has PatternMatchable Integer) then
	 patternMatch(p:%, pat:Pattern Integer,
	  l:PatternMatchResult(Integer, %)) ==
	    patternMatch(p, pat,
	      l)$PatternMatchPolynomialCategory(Integer,E,VarSet,R,%)
    if (R has PatternMatchable Float) and
       (VarSet has PatternMatchable Float) then
	 patternMatch(p:%, pat:Pattern Float,
	  l:PatternMatchResult(Float, %)) ==
	    patternMatch(p, pat,
	      l)$PatternMatchPolynomialCategory(Float,E,VarSet,R,%)

    if (R has ConvertibleTo Pattern Integer) and
       (VarSet has ConvertibleTo Pattern Integer) then
         convert(x:%):Pattern(Integer) ==
           map(convert, convert,
              x)$PolynomialCategoryLifting(E,VarSet,R,%,Pattern Integer)
    if (R has ConvertibleTo Pattern Float) and
       (VarSet has ConvertibleTo Pattern Float) then
         convert(x:%):Pattern(Float) ==
           map(convert, convert,
            x)$PolynomialCategoryLifting(E, VarSet, R, %, Pattern Float)
    if (R has ConvertibleTo InputForm) and
       (VarSet has ConvertibleTo InputForm) then
         convert(p:%):InputForm ==
           map(convert, convert,
                    p)$PolynomialCategoryLifting(E,VarSet,R,%,InputForm)

@

\section{package POLYLIFT PolynomialCategoryLifting}

<<package POLYLIFT PolynomialCategoryLifting>>=
)abbrev package POLYLIFT PolynomialCategoryLifting
++ Author: Manuel Bronstein
++ Date Created:
++ Date Last Updated:
++ Basic Functions:
++ Related Constructors:
++ Also See:
++ AMS Classifications:
++ Keywords:
++ References:
++ Description:
++ This package provides a very general map function, which
++ given a set S and polynomials over R with maps from the
++ variables into S and the coefficients into S, maps polynomials
++ into S. S is assumed to support \spad{+}, \spad{*} and \spad{**}.

PolynomialCategoryLifting(E,Vars,R,P,S): Exports == Implementation where
  E   : OrderedAbelianMonoidSup
  Vars: OrderedSet
  R   : Ring
  P   : PolynomialCategory(R, E, Vars)
  S   : SetCategory with
           + : (%, %) -> %
           * : (%, %) -> %
           **: (%, NonNegativeInteger) -> %

  Exports ==> with
    map: (Vars -> S, R -> S, P) -> S
      ++ map(varmap, coefmap, p) takes a
      ++ varmap, a mapping from the variables of polynomial p into S,
      ++ coefmap, a mapping from coefficients of p into S, and p, and
      ++ produces a member of S using the corresponding arithmetic.
      ++ in S

  Implementation ==> add
    map(fv, fc, p) ==
      (x1 := mainVariable p) case "failed" => fc leadingCoefficient p
      up := univariate(p, x1::Vars)
      t  := fv(x1::Vars)
      ans:= fc 0
      while not ground? up repeat
        ans := ans + map(fv,fc, leadingCoefficient up) * t ** (degree up)
        up  := reductum up
      ans + map(fv, fc, leadingCoefficient up)

@
\section{category UPOLYC UnivariatePolynomialCategory}
<<category UPOLYC UnivariatePolynomialCategory>>=
)abbrev category UPOLYC UnivariatePolynomialCategory
++ Author:
++ Date Created:
++ Date Last Updated:
++ Basic Functions: Ring, monomial, coefficient, reductum, differentiate,
++ elt, map, resultant, discriminant
++ Related Constructors:
++ Also See:
++ AMS Classifications:
++ Keywords:
++ References:
++ Description:
++ The category of univariate polynomials over a ring R.
++ No particular model is assumed - implementations can be either
++ sparse or dense.

UnivariatePolynomialCategory(R:Ring): Category ==
 Join(PolynomialCategory(R, NonNegativeInteger, SingletonAsOrderedSet),
      Eltable(R, R), Eltable(%, %), DifferentialRing,
      DifferentialExtension R) with
    vectorise        : (%,NonNegativeInteger) -> Vector R
      ++ vectorise(p, n) returns \spad{[a0,...,a(n-1)]} where
      ++ \spad{p = a0 + a1*x + ... + a(n-1)*x**(n-1)} + higher order terms.
      ++ The degree of polynomial p can be different from \spad{n-1}.
    makeSUP: % -> SparseUnivariatePolynomial R
      ++ makeSUP(p) converts the polynomial p to be of type
      ++ SparseUnivariatePolynomial over the same coefficients.
    unmakeSUP: SparseUnivariatePolynomial R -> %
      ++ unmakeSUP(sup) converts sup of type \spadtype{SparseUnivariatePolynomial(R)}
      ++ to be a member of the given type.
      ++ Note: converse of makeSUP.
    multiplyExponents: (%,NonNegativeInteger) -> %
      ++ multiplyExponents(p,n) returns a new polynomial resulting from
      ++ multiplying all exponents of the polynomial p by the non negative
      ++ integer n.
    divideExponents: (%,NonNegativeInteger) -> Union(%,"failed")
      ++ divideExponents(p,n) returns a new polynomial resulting from
      ++ dividing all exponents of the polynomial p by the non negative
      ++ integer n, or "failed" if some exponent is not exactly divisible
      ++ by n.
    monicDivide: (%,%) -> Record(quotient:%,remainder:%)
      ++ monicDivide(p,q) divide the polynomial p by the monic polynomial q,
      ++ returning the pair \spad{[quotient, remainder]}.
      ++ Error: if q isn't monic.
-- These three are for Karatsuba
    karatsubaDivide: (%,NonNegativeInteger) -> Record(quotient:%,remainder:%)
      ++ \spad{karatsubaDivide(p,n)} returns the same as \spad{monicDivide(p,monomial(1,n))}
    shiftRight: (%,NonNegativeInteger) -> %
      ++ \spad{shiftRight(p,n)} returns \spad{monicDivide(p,monomial(1,n)).quotient}
    shiftLeft: (%,NonNegativeInteger) -> %
      ++ \spad{shiftLeft(p,n)} returns \spad{p * monomial(1,n)}
    pseudoRemainder: (%,%) -> %
       ++ pseudoRemainder(p,q) = r, for polynomials p and q, returns the remainder when
       ++ \spad{p' := p*lc(q)**(deg p - deg q + 1)}
       ++ is pseudo right-divided by q, i.e. \spad{p' = s q + r}.
    differentiate: (%, R -> R, %) -> %
       ++ differentiate(p, d, x') extends the R-derivation d to an
       ++ extension D in \spad{R[x]} where Dx is given by x', and returns \spad{Dp}.
    if R has StepThrough then StepThrough
    if R has CommutativeRing then
      discriminant: % -> R
        ++ discriminant(p) returns the discriminant of the polynomial p.
      resultant: (%,%) -> R
        ++ resultant(p,q) returns the resultant of the polynomials p and q.
    if R has IntegralDomain then
        Eltable(Fraction %, Fraction %)
        elt  : (Fraction %, Fraction %) -> Fraction %
             ++ elt(a,b) evaluates the fraction of univariate polynomials \spad{a}
             ++ with the distinguished variable replaced by b.
        order: (%, %) -> NonNegativeInteger
             ++ order(p, q) returns the largest n such that \spad{q**n} divides polynomial p
             ++ i.e. the order of \spad{p(x)} at \spad{q(x)=0}.
        subResultantGcd: (%,%) -> %
           ++ subResultantGcd(p,q) computes the gcd of the polynomials p and q
           ++ using the SubResultant GCD algorithm.
        composite: (%, %) -> Union(%, "failed")
           ++ composite(p, q) returns h if \spad{p = h(q)}, and "failed" no such h exists.
        composite: (Fraction %, %) -> Union(Fraction %, "failed")
           ++ composite(f, q) returns h if f = h(q), and "failed" is no such h exists.
        pseudoQuotient: (%,%) -> %
           ++ pseudoQuotient(p,q) returns r, the quotient when
           ++ \spad{p' := p*lc(q)**(deg p - deg q + 1)}
           ++ is pseudo right-divided by q, i.e. \spad{p' = s q + r}.
        pseudoDivide: (%, %) -> Record(coef:R, quotient: %, remainder:%)
           ++ pseudoDivide(p,q) returns \spad{[c, q, r]}, when
           ++ \spad{p' := p*lc(q)**(deg p - deg q + 1) = c * p}
           ++ is pseudo right-divided by q, i.e. \spad{p' = s q + r}.
    if R has GcdDomain then
        separate: (%, %) -> Record(primePart:%, commonPart: %)
           ++ separate(p, q) returns \spad{[a, b]} such that polynomial \spad{p = a b} and
           ++ \spad{a} is relatively prime to q.
    if R has Field then
        EuclideanDomain
        additiveValuation
          ++ euclideanSize(a*b) = euclideanSize(a) + euclideanSize(b)
        elt      : (Fraction %, R) -> R
            ++ elt(a,r) evaluates the fraction of univariate polynomials \spad{a}
            ++ with the distinguished variable replaced by the constant r.
    if R has Algebra Fraction Integer then
      integrate: % -> %
        ++ integrate(p) integrates the univariate polynomial p with respect
        ++ to its distinguished variable.
  add
    pp,qq: SparseUnivariatePolynomial %
    variables(p) ==
      zero? p or zero?(degree p) => []
      [create()]
    degree(p:%,v:SingletonAsOrderedSet) == degree p
    totalDegree(p:%,lv:List SingletonAsOrderedSet) ==
       empty? lv => 0
       totalDegree p
    degree(p:%,lv:List SingletonAsOrderedSet) ==
       empty? lv => []
       [degree p]
    eval(p:%,lv: List SingletonAsOrderedSet,lq: List %):% ==
      empty? lv => p
      not empty? rest lv => error "can only eval a univariate polynomial once"
      eval(p,first lv,first lq)$%
    eval(p:%,v:SingletonAsOrderedSet,q:%):% == p(q)
    eval(p:%,lv: List SingletonAsOrderedSet,lr: List R):% ==
      empty? lv => p
      not empty? rest lv => error "can only eval a univariate polynomial once"
      eval(p,first lv,first lr)$%
    eval(p:%,v:SingletonAsOrderedSet,r:R):% == p(r)::%
    eval(p:%,le:List Equation %):% == 
      empty? le  => p
      not empty? rest le => error "can only eval a univariate polynomial once"
      mainVariable(lhs first le) case "failed" => p
      p(rhs first le)
    mainVariable(p:%) ==
      zero? degree p =>  "failed"
      create()$SingletonAsOrderedSet
    minimumDegree(p:%,v:SingletonAsOrderedSet) == minimumDegree p
    minimumDegree(p:%,lv:List SingletonAsOrderedSet) ==
       empty? lv => []
       [minimumDegree p]
    monomial(p:%,v:SingletonAsOrderedSet,n:NonNegativeInteger) ==
       mapExponents(#1+n,p)
    coerce(v:SingletonAsOrderedSet):% == monomial(1,1)
    makeSUP p ==
      zero? p => 0
      monomial(leadingCoefficient p,degree p) + makeSUP reductum p
    unmakeSUP sp ==
      zero? sp => 0
      monomial(leadingCoefficient sp,degree sp) + unmakeSUP reductum sp
    karatsubaDivide(p:%,n:NonNegativeInteger) == monicDivide(p,monomial(1,n))
    shiftRight(p:%,n:NonNegativeInteger) == monicDivide(p,monomial(1,n)).quotient
    shiftLeft(p:%,n:NonNegativeInteger) == p * monomial(1,n)
    if R has PolynomialFactorizationExplicit then
       PFBRU ==>PolynomialFactorizationByRecursionUnivariate(R,%)
       pp,qq:SparseUnivariatePolynomial %
       lpp:List SparseUnivariatePolynomial %
       SupR ==> SparseUnivariatePolynomial R
       sp:SupR

       solveLinearPolynomialEquation(lpp,pp) ==
         solveLinearPolynomialEquationByRecursion(lpp,pp)$PFBRU
       factorPolynomial(pp) ==
         factorByRecursion(pp)$PFBRU
       factorSquareFreePolynomial(pp) ==
         factorSquareFreeByRecursion(pp)$PFBRU
       import FactoredFunctions2(SupR,S)
       factor p ==
         zero? degree p  =>
           ansR:=factor leadingCoefficient p
           makeFR(unit(ansR)::%,
                  [[w.flg,w.fctr::%,w.xpnt] for w in factorList ansR])
         map(unmakeSUP,factorPolynomial(makeSUP p)$R)

    vectorise(p, n) ==
      m := minIndex(v := new(n, 0)$Vector(R))
      for i in minIndex v .. maxIndex v repeat
        qsetelt!(v, i, coefficient(p, (i - m)::NonNegativeInteger))
      v
    retract(p:%):R ==
      zero? p => 0
      zero? degree p => leadingCoefficient p
      error "Polynomial is not of degree 0"
    retractIfCan(p:%):Union(R, "failed") ==
      zero? p => 0
      zero? degree p => leadingCoefficient p
      "failed"

    if R has StepThrough then
       init() == init()$R::%
       nextItemInner: % -> Maybe %
       nextItemInner(n) ==
         zero? n => just(nextItem(0$R)::R::%) -- assumed not to fail
         zero? degree n =>
           nn:=nextItem leadingCoefficient n
           nn case nothing => nothing
           just(nn::R::%)
         n1:=reductum n
         n2:=nextItemInner n1 -- try stepping the reductum
         n2 case % => just(monomial(leadingCoefficient n,degree n) + n2)
         1+degree n1 < degree n => -- there was a hole between lt n and n1
           just(monomial(leadingCoefficient n,degree n)+
             monomial(nextItem(init()$R)::R,1+degree n1))
         n3:=nextItem leadingCoefficient n
         n3 case nothing => nothing
         just monomial(n3,degree n)
       nextItem(n) ==
         n1:=nextItemInner n
         n1 case nothing => just monomial(nextItem(init()$R)::R,1+degree(n))
         n1

    if R has GcdDomain then

      content(p:%,v:SingletonAsOrderedSet) == content(p)::%

      primeFactor: (%, %) -> %

      primeFactor(p, q) ==
        (p1 := (p exquo gcd(p, q))::%) = p => p
        primeFactor(p1, q)

      separate(p, q) ==
        a := primeFactor(p, q)
        [a, (p exquo a)::%]

    if R has CommutativeRing then
      differentiate(x:%, deriv:R -> R, x':%) ==
        d:% := 0
        while positive?(dg := degree x) repeat
          lc := leadingCoefficient x
          d := d + x' * monomial(dg * lc, (dg - 1)::NonNegativeInteger)
                 + monomial(deriv lc, dg)
          x := reductum x
        d + deriv(leadingCoefficient x)::%
    else
      ncdiff: (NonNegativeInteger, %) -> %
      -- computes d(x**n) given dx = x', non-commutative case
      ncdiff(n, x') ==
        zero? n => 0
        zero?(n1 := (n - 1)::NonNegativeInteger) => x'
        x' * monomial(1, n1) + monomial(1, 1) * ncdiff(n1, x')

      differentiate(x:%, deriv:R -> R, x':%) ==
        d:% := 0
        while positive?(dg := degree x) repeat
          lc := leadingCoefficient x
          d := d + monomial(deriv lc, dg) + lc * ncdiff(dg, x')
          x := reductum x
        d + deriv(leadingCoefficient x)::%
    differentiate(x:%, deriv:R -> R) == differentiate(x, deriv, 1$%)$%
    differentiate(x:%) ==
        d:% := 0
        while positive?(dg := degree x) repeat
          d := d + monomial(dg * leadingCoefficient x, (dg - 1)::NonNegativeInteger)
          x := reductum x
        d
    differentiate(x:%,v:SingletonAsOrderedSet) == differentiate x
    if R has IntegralDomain then
      elt(g:Fraction %, f:Fraction %) == ((numer g) f) / ((denom g) f)

      pseudoQuotient(p, q) ==
        (n := degree(p)::Integer - degree q + 1) < 1 => 0
        ((leadingCoefficient(q)**(n::NonNegativeInteger) * p
          - pseudoRemainder(p, q)) exquo q)::%

      pseudoDivide(p, q) ==
        n: Integer := degree(p)::Integer - degree q + 1
        n < 1 => [1, 0, p]
        prem := pseudoRemainder(p, q)
        lc   := leadingCoefficient(q)**(n::NonNegativeInteger)
        [lc,((lc*p - prem) exquo q)::%, prem]

      composite(f:Fraction %, q:%) ==
        (n := composite(numer f, q)) case "failed" => "failed"
        (d := composite(denom f, q)) case "failed" => "failed"
        n::% / d::%

      composite(p:%, q:%) ==
        ground? p => p
        cqr := pseudoDivide(p, q)
        ground?(cqr.remainder) and
          ((v := cqr.remainder exquo cqr.coef) case %) and
            ((u := composite(cqr.quotient, q)) case %) and
              ((w := (u::%) exquo cqr.coef) case %) =>
                v::% + monomial(1, 1) * w::%
        "failed"

      elt(p:%, f:Fraction %) ==
        zero? p => 0
        ans:Fraction(%) := (leadingCoefficient p)::%::Fraction(%)
        n := degree p
        while not zero?(p:=reductum p) repeat
          ans := ans * f ** (n - (n := degree p))::NonNegativeInteger +
                    (leadingCoefficient p)::%::Fraction(%)
        zero? n => ans
        ans * f ** n

      order(p, q) ==
        zero? p => error "order: arguments must be nonzero"
        degree(q) < 1 => error "order: place must be non-trivial"
        ans:NonNegativeInteger := 0
        repeat
          (u  := p exquo q) case "failed" => return ans
          p   := u::%
          ans := ans + 1

    if R has GcdDomain then
      squareFree(p:%) ==
        squareFree(p)$UnivariatePolynomialSquareFree(R, %)

      squareFreePart(p:%) ==
        squareFreePart(p)$UnivariatePolynomialSquareFree(R, %)

    if R has PolynomialFactorizationExplicit then

      gcdPolynomial(pp,qq) ==
            zero? pp => unitCanonical qq  -- subResultantGcd can't handle 0
            zero? qq => unitCanonical pp
            unitCanonical(gcd(content (pp),content(qq))*
                   primitivePart
                      subResultantGcd(primitivePart pp,primitivePart qq))

      squareFreePolynomial pp ==
         squareFree(pp)$UnivariatePolynomialSquareFree(%,
                                    SparseUnivariatePolynomial %)

    if R has Field then
      elt(f:Fraction %, r:R) == ((numer f) r) / ((denom f) r)

      euclideanSize x ==
            zero? x =>
              error "euclideanSize called on 0 in Univariate Polynomial"
            degree x
      divide(x,y) ==
            zero? y => error "division by 0 in Univariate Polynomials"
            quot: % := 0
            lc := inv leadingCoefficient y
            while not zero?(x) and (degree x >= degree y) repeat
               f:=lc*leadingCoefficient x
               n:=(degree x - degree y)::NonNegativeInteger
               quot:=quot+monomial(f,n)
               x:=x-monomial(f,n)*y
            [quot,x]
    if R has Algebra Fraction Integer then
      integrate p ==
        ans:% := 0
        while p ~= 0 repeat
          l := leadingCoefficient p
          d := 1 + degree p
          ans := ans + inv(d::Fraction(Integer)) * monomial(l, d)
          p := reductum p
        ans

@

\section{package UPOLYC2 UnivariatePolynomialCategoryFunctions2}

<<package UPOLYC2 UnivariatePolynomialCategoryFunctions2>>=
)abbrev package UPOLYC2 UnivariatePolynomialCategoryFunctions2
++ Author:
++ Date Created:
++ Date Last Updated:
++ Basic Functions:
++ Related Constructors:
++ Also See:
++ AMS Classifications:
++ Keywords:
++ References:
++ Description:
++ Mapping from polynomials over R to polynomials over S
++ given a map from R to S assumed to send zero to zero.

UnivariatePolynomialCategoryFunctions2(R,PR,S,PS): Exports == Impl where
  R, S: Ring
  PR  : UnivariatePolynomialCategory R
  PS  : UnivariatePolynomialCategory S

  Exports ==> with
    map: (R -> S, PR) -> PS
     ++ map(f, p) takes a function f from R to S,
     ++ and applies it to each (non-zero) coefficient of a polynomial p
     ++ over R, getting a new polynomial over S.
     ++ Note: since the map is not applied to zero elements, it may map zero
     ++ to zero.

  Impl ==> add
    map(f, p) ==
      ans:PS := 0
      while p ~= 0 repeat
        ans := ans + monomial(f leadingCoefficient p, degree p)
        p   := reductum p
      ans

@
\section{package COMMUPC CommuteUnivariatePolynomialCategory}
<<package COMMUPC CommuteUnivariatePolynomialCategory>>=
)abbrev package COMMUPC CommuteUnivariatePolynomialCategory
++ Author: Manuel Bronstein
++ Date Created:
++ Date Last Updated:
++ Basic Functions:
++ Related Constructors:
++ Also See:
++ AMS Classifications:
++ Keywords:
++ References:
++ Description:
++ A package for swapping the order of two variables in a tower of two
++ UnivariatePolynomialCategory extensions.

CommuteUnivariatePolynomialCategory(R, UP, UPUP): Exports == Impl where
  R   : Ring
  UP  : UnivariatePolynomialCategory R
  UPUP: UnivariatePolynomialCategory UP

  N ==> NonNegativeInteger

  Exports ==> with
    swap: UPUP -> UPUP
      ++ swap(p(x,y)) returns p(y,x).

  Impl ==> add
    makePoly: (UP, N) -> UPUP

-- converts P(x,y) to P(y,x)
    swap poly ==
      ans:UPUP := 0
      while poly ~= 0 repeat
        ans  := ans + makePoly(leadingCoefficient poly, degree poly)
        poly := reductum poly
      ans

    makePoly(poly, d) ==
      ans:UPUP := 0
      while poly ~= 0 repeat
        ans  := ans +
             monomial(monomial(leadingCoefficient poly, d), degree poly)
        poly := reductum poly
      ans

@
\section{License}
<<license>>=
--Copyright (c) 1991-2002, The Numerical ALgorithms Group Ltd.
--All rights reserved.
--Copyright (C) 2007-2013, Gabriel Dos Reis.
--All rights reserved.
--
--Redistribution and use in source and binary forms, with or without
--modification, are permitted provided that the following conditions are
--met:
--
--    - Redistributions of source code must retain the above copyright
--      notice, this list of conditions and the following disclaimer.
--
--    - Redistributions in binary form must reproduce the above copyright
--      notice, this list of conditions and the following disclaimer in
--      the documentation and/or other materials provided with the
--      distribution.
--
--    - Neither the name of The Numerical ALgorithms Group Ltd. nor the
--      names of its contributors may be used to endorse or promote products
--      derived from this software without specific prior written permission.
--
--THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
--IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
--TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
--PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
--OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
--EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
--PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
--PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
--LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
--NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
--SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@
<<*>>=
<<license>>

<<category AMR AbelianMonoidRing>>
<<category FAMR FiniteAbelianMonoidRing>>
<<category POLYCAT PolynomialCategory>>
<<package POLYLIFT PolynomialCategoryLifting>>
<<category UPOLYC UnivariatePolynomialCategory>>
<<package UPOLYC2 UnivariatePolynomialCategoryFunctions2>>
<<package COMMUPC CommuteUnivariatePolynomialCategory>>
@
\eject
\begin{thebibliography}{99}
\bibitem{1} nothing
\end{thebibliography}
\end{document}