%mathpiper,def="FactorCancel"

//Retract("FactorCancel",*);

10 # FactorCancel( p_IsRational ) <-- Factor(p);

15 # FactorCancel( p_IsRationalFunction ) <--
[
    If(InVerboseMode(),Tell(FactorCancel,p));
    Local(pp,ff,n,d,fn,fd,f,tnu,newn,newd,s,k);
    pp   := Simplify(p);
    If(InVerboseMode(),Tell("  ",pp));
    ff   := Factors(pp);
    If(InVerboseMode(),Tell("  ",ff));
    tnu  := {ff[1]};
    If(IsListOfLists(ff), tnu  := RemoveDuplicates(Transpose(ff)[1]));
    newn := {};
    newd := {};
    If(InVerboseMode(),Tell("      ",tnu));
    ForEach(f,tnu)
    [
       s := Select(ff,Lambda({X},X[1]=f));
       If(InVerboseMode(),Tell("      ",{f,s}));
       If( s != {},
         [
            k := Sum(Transpose(s)[2]);
            If(InVerboseMode(),Tell("      ",{s,k}));
            If( k > 0, DestructiveAppend(newn,{f,k}) );
            If( k < 0, DestructiveAppend(newd,{f,-k}) );
         ],
         [
            k := 1;
            DestructiveAppend(newn,{f,k});
         ]
       );
    ];
    If(InVerboseMode(),Tell("    ",{newn,newd}));
    FW(newn)/FW(newd);
];

20 # FactorCancel( _p ) <-- Factor(p);

%/mathpiper

    %output,preserve="false"
      Result: True
.   %/output

   
   
.  



%mathpiper_docs,name="FactorCancel",categories="User Functions;Polynomials (Operations)"

*CMD FactorCancel -- Factors a Rational Function and cancels where possible

*CALL
FactorCancel( expr )

*PARMS
{expr} -- A function which is a quotient of two polynomials

*DESC
A quotient of two polynomials P(z) and Q(z),
    R(z)=(P(z))/(Q(z)),
is called a rational function, or sometimes a rational polynomial function.

By convention, the {Domain} of the function {excludes} any points which are
zeros of the denominator, even though some of these may be cancelable by
equivalent zeros in the numerator.   Therefore, the function {Factor}, when
applied to such a function, retains all the factors of both numerator and
denominator, whether or not they might subsequently cancel.

But sometimes a user might want to see the factored function in the form which
results when such cancellation has been performed.  {FactorCancel} performs
this operation.

*E.G.

In> P:=Expand(x^2-1)
Result: x^2-1

In> Q:=Expand((x+1)^2)
Result: x^2+2*x+1

In> F:=P/Q
Result: (x^2-1)/(x^2+2*x+1)

In> Factor(F)
Result: ((x-1)*(x+1))/(x+1)^2

In> FactorCancel(F)
Result: (x-1)/(x+1)

    
*SEE Factor,Factors

%/mathpiper_docs
