a4bb802ec9475c6b8f87ac4becbeaaf22b13cea5
[ginac.git] / ginac / mul.cpp
1 /** @file mul.cpp
2  *
3  *  Implementation of GiNaC's products of expressions. */
4
5 /*
6  *  GiNaC Copyright (C) 1999-2001 Johannes Gutenberg University Mainz, Germany
7  *
8  *  This program is free software; you can redistribute it and/or modify
9  *  it under the terms of the GNU General Public License as published by
10  *  the Free Software Foundation; either version 2 of the License, or
11  *  (at your option) any later version.
12  *
13  *  This program is distributed in the hope that it will be useful,
14  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
15  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  *  GNU General Public License for more details.
17  *
18  *  You should have received a copy of the GNU General Public License
19  *  along with this program; if not, write to the Free Software
20  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
22
23 #include <vector>
24 #include <stdexcept>
25
26 #include "mul.h"
27 #include "add.h"
28 #include "power.h"
29 #include "matrix.h"
30 #include "archive.h"
31 #include "debugmsg.h"
32 #include "utils.h"
33
34 namespace GiNaC {
35
36 GINAC_IMPLEMENT_REGISTERED_CLASS(mul, expairseq)
37
38 //////////
39 // default ctor, dctor, copy ctor assignment operator and helpers
40 //////////
41
42 mul::mul()
43 {
44         debugmsg("mul default ctor",LOGLEVEL_CONSTRUCT);
45         tinfo_key = TINFO_mul;
46 }
47
48 DEFAULT_COPY(mul)
49 DEFAULT_DESTROY(mul)
50
51 //////////
52 // other ctors
53 //////////
54
55 // public
56
57 mul::mul(const ex & lh, const ex & rh)
58 {
59         debugmsg("mul ctor from ex,ex",LOGLEVEL_CONSTRUCT);
60         tinfo_key = TINFO_mul;
61         overall_coeff = _ex1();
62         construct_from_2_ex(lh,rh);
63         GINAC_ASSERT(is_canonical());
64 }
65
66 mul::mul(const exvector & v)
67 {
68         debugmsg("mul ctor from exvector",LOGLEVEL_CONSTRUCT);
69         tinfo_key = TINFO_mul;
70         overall_coeff = _ex1();
71         construct_from_exvector(v);
72         GINAC_ASSERT(is_canonical());
73 }
74
75 mul::mul(const epvector & v)
76 {
77         debugmsg("mul ctor from epvector",LOGLEVEL_CONSTRUCT);
78         tinfo_key = TINFO_mul;
79         overall_coeff = _ex1();
80         construct_from_epvector(v);
81         GINAC_ASSERT(is_canonical());
82 }
83
84 mul::mul(const epvector & v, const ex & oc)
85 {
86         debugmsg("mul ctor from epvector,ex",LOGLEVEL_CONSTRUCT);
87         tinfo_key = TINFO_mul;
88         overall_coeff = oc;
89         construct_from_epvector(v);
90         GINAC_ASSERT(is_canonical());
91 }
92
93 mul::mul(epvector * vp, const ex & oc)
94 {
95         debugmsg("mul ctor from epvector *,ex",LOGLEVEL_CONSTRUCT);
96         tinfo_key = TINFO_mul;
97         GINAC_ASSERT(vp!=0);
98         overall_coeff = oc;
99         construct_from_epvector(*vp);
100         delete vp;
101         GINAC_ASSERT(is_canonical());
102 }
103
104 mul::mul(const ex & lh, const ex & mh, const ex & rh)
105 {
106         debugmsg("mul ctor from ex,ex,ex",LOGLEVEL_CONSTRUCT);
107         tinfo_key = TINFO_mul;
108         exvector factors;
109         factors.reserve(3);
110         factors.push_back(lh);
111         factors.push_back(mh);
112         factors.push_back(rh);
113         overall_coeff = _ex1();
114         construct_from_exvector(factors);
115         GINAC_ASSERT(is_canonical());
116 }
117
118 //////////
119 // archiving
120 //////////
121
122 DEFAULT_ARCHIVING(mul)
123
124 //////////
125 // functions overriding virtual functions from bases classes
126 //////////
127
128 // public
129
130 void mul::print(const print_context & c, unsigned level) const
131 {
132         debugmsg("mul print", LOGLEVEL_PRINT);
133
134         if (is_of_type(c, print_tree)) {
135
136                 inherited::print(c, level);
137
138         } else if (is_of_type(c, print_csrc)) {
139
140                 if (precedence() <= level)
141                         c.s << "(";
142
143                 if (!overall_coeff.is_equal(_ex1())) {
144                         overall_coeff.bp->print(c, precedence());
145                         c.s << "*";
146                 }
147         
148                 // Print arguments, separated by "*" or "/"
149                 epvector::const_iterator it = seq.begin(), itend = seq.end();
150                 while (it != itend) {
151
152                         // If the first argument is a negative integer power, it gets printed as "1.0/<expr>"
153                         if (it == seq.begin() && ex_to_numeric(it->coeff).is_integer() && it->coeff.compare(_num0()) < 0) {
154                                 if (is_of_type(c, print_csrc_cl_N))
155                                         c.s << "recip(";
156                                 else
157                                         c.s << "1.0/";
158                         }
159
160                         // If the exponent is 1 or -1, it is left out
161                         if (it->coeff.compare(_ex1()) == 0 || it->coeff.compare(_num_1()) == 0)
162                                 it->rest.print(c, precedence());
163                         else {
164                                 // Outer parens around ex needed for broken gcc-2.95 parser:
165                                 (ex(power(it->rest, abs(ex_to_numeric(it->coeff))))).print(c, level);
166                         }
167
168                         // Separator is "/" for negative integer powers, "*" otherwise
169                         ++it;
170                         if (it != itend) {
171                                 if (ex_to_numeric(it->coeff).is_integer() && it->coeff.compare(_num0()) < 0)
172                                         c.s << "/";
173                                 else
174                                         c.s << "*";
175                         }
176                 }
177
178                 if (precedence() <= level)
179                         c.s << ")";
180
181         } else {
182
183                 if (precedence() <= level) {
184                         if (is_of_type(c, print_latex))
185                                 c.s << "{(";
186                         else
187                                 c.s << "(";
188                 }
189
190                 bool first = true;
191
192                 // First print the overall numeric coefficient
193                 numeric coeff = ex_to_numeric(overall_coeff);
194                 if (coeff.csgn() == -1)
195                         c.s << '-';
196                 if (!coeff.is_equal(_num1()) &&
197                         !coeff.is_equal(_num_1())) {
198                         if (coeff.is_rational()) {
199                                 if (coeff.is_negative())
200                                         (-coeff).print(c);
201                                 else
202                                         coeff.print(c);
203                         } else {
204                                 if (coeff.csgn() == -1)
205                                         (-coeff).print(c, precedence());
206                                 else
207                                         coeff.print(c, precedence());
208                         }
209                         if (is_of_type(c, print_latex))
210                                 c.s << ' ';
211                         else
212                                 c.s << '*';
213                 }
214
215                 // Then proceed with the remaining factors
216                 epvector::const_iterator it = seq.begin(), itend = seq.end();
217                 while (it != itend) {
218                         if (!first) {
219                                 if (is_of_type(c, print_latex))
220                                         c.s << ' ';
221                                 else
222                                         c.s << '*';
223                         } else {
224                                 first = false;
225                         }
226                         recombine_pair_to_ex(*it).print(c, precedence());
227                         it++;
228                 }
229
230                 if (precedence() <= level) {
231                         if (is_of_type(c, print_latex))
232                                 c.s << ")}";
233                         else
234                                 c.s << ")";
235                 }
236         }
237 }
238
239 bool mul::info(unsigned inf) const
240 {
241         switch (inf) {
242                 case info_flags::polynomial:
243                 case info_flags::integer_polynomial:
244                 case info_flags::cinteger_polynomial:
245                 case info_flags::rational_polynomial:
246                 case info_flags::crational_polynomial:
247                 case info_flags::rational_function: {
248                         for (epvector::const_iterator i=seq.begin(); i!=seq.end(); ++i) {
249                                 if (!(recombine_pair_to_ex(*i).info(inf)))
250                                         return false;
251                         }
252                         return overall_coeff.info(inf);
253                 }
254                 case info_flags::algebraic: {
255                         for (epvector::const_iterator i=seq.begin(); i!=seq.end(); ++i) {
256                                 if ((recombine_pair_to_ex(*i).info(inf)))
257                                         return true;
258                         }
259                         return false;
260                 }
261         }
262         return inherited::info(inf);
263 }
264
265 int mul::degree(const ex & s) const
266 {
267         int deg_sum = 0;
268         for (epvector::const_iterator cit=seq.begin(); cit!=seq.end(); ++cit) {
269                 if (ex_to_numeric(cit->coeff).is_integer())
270                         deg_sum+=cit->rest.degree(s) * ex_to_numeric(cit->coeff).to_int();
271         }
272         return deg_sum;
273 }
274
275 int mul::ldegree(const ex & s) const
276 {
277         int deg_sum = 0;
278         for (epvector::const_iterator cit=seq.begin(); cit!=seq.end(); ++cit) {
279                 if (ex_to_numeric(cit->coeff).is_integer())
280                         deg_sum+=cit->rest.ldegree(s) * ex_to_numeric(cit->coeff).to_int();
281         }
282         return deg_sum;
283 }
284
285 ex mul::coeff(const ex & s, int n) const
286 {
287         exvector coeffseq;
288         coeffseq.reserve(seq.size()+1);
289         
290         if (n==0) {
291                 // product of individual coeffs
292                 // if a non-zero power of s is found, the resulting product will be 0
293                 epvector::const_iterator it = seq.begin();
294                 while (it!=seq.end()) {
295                         coeffseq.push_back(recombine_pair_to_ex(*it).coeff(s,n));
296                         ++it;
297                 }
298                 coeffseq.push_back(overall_coeff);
299                 return (new mul(coeffseq))->setflag(status_flags::dynallocated);
300         }
301         
302         epvector::const_iterator it=seq.begin();
303         bool coeff_found = 0;
304         while (it!=seq.end()) {
305                 ex t = recombine_pair_to_ex(*it);
306                 ex c = t.coeff(s,n);
307                 if (!c.is_zero()) {
308                         coeffseq.push_back(c);
309                         coeff_found = 1;
310                 } else {
311                         coeffseq.push_back(t);
312                 }
313                 ++it;
314         }
315         if (coeff_found) {
316                 coeffseq.push_back(overall_coeff);
317                 return (new mul(coeffseq))->setflag(status_flags::dynallocated);
318         }
319         
320         return _ex0();
321 }
322
323 ex mul::eval(int level) const
324 {
325         // simplifications  *(...,x;0) -> 0
326         //                  *(+(x,y,...);c) -> *(+(*(x,c),*(y,c),...)) (c numeric())
327         //                  *(x;1) -> x
328         //                  *(;c) -> c
329         
330         debugmsg("mul eval",LOGLEVEL_MEMBER_FUNCTION);
331         
332         epvector * evaled_seqp = evalchildren(level);
333         if (evaled_seqp!=0) {
334                 // do more evaluation later
335                 return (new mul(evaled_seqp,overall_coeff))->
336                            setflag(status_flags::dynallocated);
337         }
338         
339 #ifdef DO_GINAC_ASSERT
340         for (epvector::const_iterator cit=seq.begin(); cit!=seq.end(); ++cit) {
341                 GINAC_ASSERT((!is_ex_exactly_of_type((*cit).rest,mul)) ||
342                              (!(ex_to_numeric((*cit).coeff).is_integer())));
343                 GINAC_ASSERT(!(cit->is_canonical_numeric()));
344                 if (is_ex_exactly_of_type(recombine_pair_to_ex(*cit),numeric))
345                     print(print_tree(std::cerr));
346                 GINAC_ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*cit),numeric));
347                 /* for paranoia */
348                 expair p = split_ex_to_pair(recombine_pair_to_ex(*cit));
349                 GINAC_ASSERT(p.rest.is_equal((*cit).rest));
350                 GINAC_ASSERT(p.coeff.is_equal((*cit).coeff));
351                 /* end paranoia */
352         }
353 #endif // def DO_GINAC_ASSERT
354         
355         if (flags & status_flags::evaluated) {
356                 GINAC_ASSERT(seq.size()>0);
357                 GINAC_ASSERT(seq.size()>1 || !overall_coeff.is_equal(_ex1()));
358                 return *this;
359         }
360         
361         int seq_size = seq.size();
362         if (overall_coeff.is_equal(_ex0())) {
363                 // *(...,x;0) -> 0
364                 return _ex0();
365         } else if (seq_size==0) {
366                 // *(;c) -> c
367                 return overall_coeff;
368         } else if (seq_size==1 && overall_coeff.is_equal(_ex1())) {
369                 // *(x;1) -> x
370                 return recombine_pair_to_ex(*(seq.begin()));
371         } else if ((seq_size==1) &&
372                    is_ex_exactly_of_type((*seq.begin()).rest,add) &&
373                    ex_to_numeric((*seq.begin()).coeff).is_equal(_num1())) {
374                 // *(+(x,y,...);c) -> +(*(x,c),*(y,c),...) (c numeric(), no powers of +())
375                 const add & addref = ex_to_add((*seq.begin()).rest);
376                 epvector distrseq;
377                 distrseq.reserve(addref.seq.size());
378                 for (epvector::const_iterator cit=addref.seq.begin(); cit!=addref.seq.end(); ++cit) {
379                         distrseq.push_back(addref.combine_pair_with_coeff_to_pair(*cit, overall_coeff));
380                 }
381                 return (new add(distrseq,
382                                 ex_to_numeric(addref.overall_coeff).
383                                 mul_dyn(ex_to_numeric(overall_coeff))))
384                       ->setflag(status_flags::dynallocated | status_flags::evaluated);
385         }
386         return this->hold();
387 }
388
389 ex mul::evalf(int level) const
390 {
391         if (level==1)
392                 return mul(seq,overall_coeff);
393         
394         if (level==-max_recursion_level)
395                 throw(std::runtime_error("max recursion level reached"));
396         
397         epvector s;
398         s.reserve(seq.size());
399         
400         --level;
401         for (epvector::const_iterator it=seq.begin(); it!=seq.end(); ++it) {
402                 s.push_back(combine_ex_with_coeff_to_pair((*it).rest.evalf(level),
403                                                           (*it).coeff));
404         }
405         return mul(s,overall_coeff.evalf(level));
406 }
407
408 ex mul::evalm(void) const
409 {
410         // numeric*matrix
411         if (seq.size() == 1 && is_ex_of_type(seq[0].rest, matrix))
412                 return ex_to_matrix(seq[0].rest).mul(ex_to_numeric(overall_coeff));
413
414         // Evaluate children first, look whether there are any matrices at all
415         // (there can be either no matrices or one matrix; if there were more
416         // than one matrix, it would be a non-commutative product)
417         epvector *s = new epvector;
418         s->reserve(seq.size());
419
420         bool have_matrix = false;
421         epvector::iterator the_matrix;
422
423         epvector::const_iterator it = seq.begin(), itend = seq.end();
424         while (it != itend) {
425                 const ex &m = recombine_pair_to_ex(*it).evalm();
426                 s->push_back(split_ex_to_pair(m));
427                 if (is_ex_of_type(m, matrix)) {
428                         have_matrix = true;
429                         the_matrix = s->end() - 1;
430                 }
431                 it++;
432         }
433
434         if (have_matrix) {
435
436                 // The product contained a matrix. We will multiply all other factors
437                 // into that matrix.
438                 matrix m = ex_to_matrix(the_matrix->rest);
439                 s->erase(the_matrix);
440                 ex scalar = (new mul(s, overall_coeff))->setflag(status_flags::dynallocated);
441                 return m.mul_scalar(scalar);
442
443         } else
444                 return (new mul(s, overall_coeff))->setflag(status_flags::dynallocated);
445 }
446
447 ex mul::simplify_ncmul(const exvector & v) const
448 {
449         if (seq.size()==0) {
450                 return inherited::simplify_ncmul(v);
451         }
452
453         // Find first noncommutative element and call its simplify_ncmul()
454         for (epvector::const_iterator cit=seq.begin(); cit!=seq.end(); ++cit) {
455                 if (cit->rest.return_type() == return_types::noncommutative)
456                         return cit->rest.simplify_ncmul(v);
457         }
458         return inherited::simplify_ncmul(v);
459 }
460
461 // protected
462
463 /** Implementation of ex::diff() for a product.  It applies the product rule.
464  *  @see ex::diff */
465 ex mul::derivative(const symbol & s) const
466 {
467         exvector addseq;
468         addseq.reserve(seq.size());
469         
470         // D(a*b*c) = D(a)*b*c + a*D(b)*c + a*b*D(c)
471         for (unsigned i=0; i!=seq.size(); ++i) {
472                 epvector mulseq = seq;
473                 mulseq[i] = split_ex_to_pair(power(seq[i].rest,seq[i].coeff - _ex1()) *
474                                              seq[i].rest.diff(s));
475                 addseq.push_back((new mul(mulseq,overall_coeff*seq[i].coeff))->setflag(status_flags::dynallocated));
476         }
477         return (new add(addseq))->setflag(status_flags::dynallocated);
478 }
479
480 int mul::compare_same_type(const basic & other) const
481 {
482         return inherited::compare_same_type(other);
483 }
484
485 bool mul::is_equal_same_type(const basic & other) const
486 {
487         return inherited::is_equal_same_type(other);
488 }
489
490 unsigned mul::return_type(void) const
491 {
492         if (seq.size()==0) {
493                 // mul without factors: should not happen, but commutes
494                 return return_types::commutative;
495         }
496         
497         bool all_commutative = 1;
498         unsigned rt;
499         epvector::const_iterator cit_noncommutative_element; // point to first found nc element
500         
501         for (epvector::const_iterator cit=seq.begin(); cit!=seq.end(); ++cit) {
502                 rt=(*cit).rest.return_type();
503                 if (rt==return_types::noncommutative_composite) return rt; // one ncc -> mul also ncc
504                 if ((rt==return_types::noncommutative)&&(all_commutative)) {
505                         // first nc element found, remember position
506                         cit_noncommutative_element = cit;
507                         all_commutative = 0;
508                 }
509                 if ((rt==return_types::noncommutative)&&(!all_commutative)) {
510                         // another nc element found, compare type_infos
511                         if ((*cit_noncommutative_element).rest.return_type_tinfo()!=(*cit).rest.return_type_tinfo()) {
512                                 // diffent types -> mul is ncc
513                                 return return_types::noncommutative_composite;
514                         }
515                 }
516         }
517         // all factors checked
518         return all_commutative ? return_types::commutative : return_types::noncommutative;
519 }
520    
521 unsigned mul::return_type_tinfo(void) const
522 {
523         if (seq.size()==0)
524                 return tinfo_key;  // mul without factors: should not happen
525         
526         // return type_info of first noncommutative element
527         for (epvector::const_iterator cit=seq.begin(); cit!=seq.end(); ++cit) {
528                 if ((*cit).rest.return_type()==return_types::noncommutative)
529                         return (*cit).rest.return_type_tinfo();
530         }
531         // no noncommutative element found, should not happen
532         return tinfo_key;
533 }
534
535 ex mul::thisexpairseq(const epvector & v, const ex & oc) const
536 {
537         return (new mul(v,oc))->setflag(status_flags::dynallocated);
538 }
539
540 ex mul::thisexpairseq(epvector * vp, const ex & oc) const
541 {
542         return (new mul(vp,oc))->setflag(status_flags::dynallocated);
543 }
544
545 expair mul::split_ex_to_pair(const ex & e) const
546 {
547         if (is_ex_exactly_of_type(e,power)) {
548                 const power & powerref = ex_to_power(e);
549                 if (is_ex_exactly_of_type(powerref.exponent,numeric))
550                         return expair(powerref.basis,powerref.exponent);
551         }
552         return expair(e,_ex1());
553 }
554         
555 expair mul::combine_ex_with_coeff_to_pair(const ex & e,
556                                           const ex & c) const
557 {
558         // to avoid duplication of power simplification rules,
559         // we create a temporary power object
560         // otherwise it would be hard to correctly simplify
561         // expression like (4^(1/3))^(3/2)
562         if (are_ex_trivially_equal(c,_ex1()))
563                 return split_ex_to_pair(e);
564         
565         return split_ex_to_pair(power(e,c));
566 }
567         
568 expair mul::combine_pair_with_coeff_to_pair(const expair & p,
569                                             const ex & c) const
570 {
571         // to avoid duplication of power simplification rules,
572         // we create a temporary power object
573         // otherwise it would be hard to correctly simplify
574         // expression like (4^(1/3))^(3/2)
575         if (are_ex_trivially_equal(c,_ex1()))
576                 return p;
577         
578         return split_ex_to_pair(power(recombine_pair_to_ex(p),c));
579 }
580         
581 ex mul::recombine_pair_to_ex(const expair & p) const
582 {
583         if (ex_to_numeric(p.coeff).is_equal(_num1())) 
584                 return p.rest;
585         else
586                 return power(p.rest,p.coeff);
587 }
588
589 bool mul::expair_needs_further_processing(epp it)
590 {
591         if (is_ex_exactly_of_type((*it).rest,mul) &&
592                 ex_to_numeric((*it).coeff).is_integer()) {
593                 // combined pair is product with integer power -> expand it
594                 *it = split_ex_to_pair(recombine_pair_to_ex(*it));
595                 return true;
596         }
597         if (is_ex_exactly_of_type((*it).rest,numeric)) {
598                 expair ep=split_ex_to_pair(recombine_pair_to_ex(*it));
599                 if (!ep.is_equal(*it)) {
600                         // combined pair is a numeric power which can be simplified
601                         *it = ep;
602                         return true;
603                 }
604                 if (ex_to_numeric((*it).coeff).is_equal(_num1())) {
605                         // combined pair has coeff 1 and must be moved to the end
606                         return true;
607                 }
608         }
609         return false;
610 }       
611
612 ex mul::default_overall_coeff(void) const
613 {
614         return _ex1();
615 }
616
617 void mul::combine_overall_coeff(const ex & c)
618 {
619         GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
620         GINAC_ASSERT(is_ex_exactly_of_type(c,numeric));
621         overall_coeff = ex_to_numeric(overall_coeff).mul_dyn(ex_to_numeric(c));
622 }
623
624 void mul::combine_overall_coeff(const ex & c1, const ex & c2)
625 {
626         GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
627         GINAC_ASSERT(is_ex_exactly_of_type(c1,numeric));
628         GINAC_ASSERT(is_ex_exactly_of_type(c2,numeric));
629         overall_coeff = ex_to_numeric(overall_coeff).mul_dyn(ex_to_numeric(c1).power(ex_to_numeric(c2)));
630 }
631
632 bool mul::can_make_flat(const expair & p) const
633 {
634         GINAC_ASSERT(is_ex_exactly_of_type(p.coeff,numeric));
635         // this assertion will probably fail somewhere
636         // it would require a more careful make_flat, obeying the power laws
637         // probably should return true only if p.coeff is integer
638         return ex_to_numeric(p.coeff).is_equal(_num1());
639 }
640
641 ex mul::expand(unsigned options) const
642 {
643         if (flags & status_flags::expanded)
644                 return *this;
645         
646         exvector sub_expanded_seq;
647         
648         epvector * expanded_seqp = expandchildren(options);
649         
650         const epvector & expanded_seq = expanded_seqp==0 ? seq : *expanded_seqp;
651         
652         int number_of_adds = 0;
653         epvector non_adds;
654         non_adds.reserve(expanded_seq.size());
655         epvector::const_iterator cit = expanded_seq.begin();
656         epvector::const_iterator last = expanded_seq.end();
657         ex last_expanded = _ex1();
658         while (cit!=last) {
659                 if (is_ex_exactly_of_type((*cit).rest,add) &&
660                         ((*cit).coeff.is_equal(_ex1()))) {
661                         ++number_of_adds;
662                         if (is_ex_exactly_of_type(last_expanded,add)) {
663                                 // expand adds
664                                 const add & add1 = ex_to_add(last_expanded);
665                                 const add & add2 = ex_to_add((*cit).rest);
666                                 int n1 = add1.nops();
667                                 int n2 = add2.nops();
668                                 exvector distrseq;
669                                 distrseq.reserve(n1*n2);
670                                 for (int i1=0; i1<n1; ++i1) {
671                                         for (int i2=0; i2<n2; ++i2) {
672                                                 distrseq.push_back(add1.op(i1)*add2.op(i2));
673                                         }
674                                 }
675                                 last_expanded = (new add(distrseq))->setflag(status_flags::dynallocated | status_flags::expanded);
676                         } else {
677                                 non_adds.push_back(split_ex_to_pair(last_expanded));
678                                 last_expanded = (*cit).rest;
679                         }
680                 } else {
681                         non_adds.push_back(*cit);
682                 }
683                 ++cit;
684         }
685         if (expanded_seqp)
686                 delete expanded_seqp;
687
688         if (is_ex_exactly_of_type(last_expanded,add)) {
689                 add const & finaladd = ex_to_add(last_expanded);
690                 exvector distrseq;
691                 int n = finaladd.nops();
692                 distrseq.reserve(n);
693                 for (int i=0; i<n; ++i) {
694                         epvector factors = non_adds;
695                         factors.push_back(split_ex_to_pair(finaladd.op(i)));
696                         distrseq.push_back((new mul(factors,overall_coeff))->setflag(status_flags::dynallocated | status_flags::expanded));
697                 }
698                 return ((new add(distrseq))->
699                         setflag(status_flags::dynallocated | status_flags::expanded));
700         }
701         non_adds.push_back(split_ex_to_pair(last_expanded));
702         return (new mul(non_adds,overall_coeff))->
703                 setflag(status_flags::dynallocated | status_flags::expanded);
704 }
705
706   
707 //////////
708 // new virtual functions which can be overridden by derived classes
709 //////////
710
711 // none
712
713 //////////
714 // non-virtual functions in this class
715 //////////
716
717
718 /** Member-wise expand the expairs representing this sequence.  This must be
719  *  overridden from expairseq::expandchildren() and done iteratively in order
720  *  to allow for early cancallations and thus safe memory.
721  *
722  *  @see mul::expand()
723  *  @return pointer to epvector containing expanded representation or zero
724  *  pointer, if sequence is unchanged. */
725 epvector * mul::expandchildren(unsigned options) const
726 {
727         epvector::const_iterator last = seq.end();
728         epvector::const_iterator cit = seq.begin();
729         while (cit!=last) {
730                 const ex & factor = recombine_pair_to_ex(*cit);
731                 const ex & expanded_factor = factor.expand(options);
732                 if (!are_ex_trivially_equal(factor,expanded_factor)) {
733                         
734                         // something changed, copy seq, eval and return it
735                         epvector *s = new epvector;
736                         s->reserve(seq.size());
737                         
738                         // copy parts of seq which are known not to have changed
739                         epvector::const_iterator cit2 = seq.begin();
740                         while (cit2!=cit) {
741                                 s->push_back(*cit2);
742                                 ++cit2;
743                         }
744                         // copy first changed element
745                         s->push_back(split_ex_to_pair(expanded_factor));
746                         ++cit2;
747                         // copy rest
748                         while (cit2!=last) {
749                                 s->push_back(split_ex_to_pair(recombine_pair_to_ex(*cit2).expand(options)));
750                                 ++cit2;
751                         }
752                         return s;
753                 }
754                 ++cit;
755         }
756         
757         return 0; // nothing has changed
758 }
759
760 } // namespace GiNaC