some cleanups
[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_a<print_tree>(c)) {
135
136                 inherited::print(c, level);
137
138         } else if (is_a<print_csrc>(c)) {
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_a<print_csrc_cl_N>(c))
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_a<print_latex>(c))
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_a<print_latex>(c))
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_a<print_latex>(c))
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_a<print_latex>(c))
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                         epvector::const_iterator i = seq.begin(), end = seq.end();
249                         while (i != end) {
250                                 if (!(recombine_pair_to_ex(*i).info(inf)))
251                                         return false;
252                                 ++i;
253                         }
254                         return overall_coeff.info(inf);
255                 }
256                 case info_flags::algebraic: {
257                         epvector::const_iterator i = seq.begin(), end = seq.end();
258                         while (i != end) {
259                                 if ((recombine_pair_to_ex(*i).info(inf)))
260                                         return true;
261                                 ++i;
262                         }
263                         return false;
264                 }
265         }
266         return inherited::info(inf);
267 }
268
269 int mul::degree(const ex & s) const
270 {
271         // Sum up degrees of factors
272         int deg_sum = 0;
273         epvector::const_iterator i = seq.begin(), end = seq.end();
274         while (i != end) {
275                 if (ex_to<numeric>(i->coeff).is_integer())
276                         deg_sum += i->rest.degree(s) * ex_to<numeric>(i->coeff).to_int();
277                 ++i;
278         }
279         return deg_sum;
280 }
281
282 int mul::ldegree(const ex & s) const
283 {
284         // Sum up degrees of factors
285         int deg_sum = 0;
286         epvector::const_iterator i = seq.begin(), end = seq.end();
287         while (i != end) {
288                 if (ex_to<numeric>(i->coeff).is_integer())
289                         deg_sum += i->rest.ldegree(s) * ex_to<numeric>(i->coeff).to_int();
290                 ++i;
291         }
292         return deg_sum;
293 }
294
295 ex mul::coeff(const ex & s, int n) const
296 {
297         exvector coeffseq;
298         coeffseq.reserve(seq.size()+1);
299         
300         if (n==0) {
301                 // product of individual coeffs
302                 // if a non-zero power of s is found, the resulting product will be 0
303                 epvector::const_iterator i = seq.begin(), end = seq.end();
304                 while (i != end) {
305                         coeffseq.push_back(recombine_pair_to_ex(*i).coeff(s,n));
306                         ++i;
307                 }
308                 coeffseq.push_back(overall_coeff);
309                 return (new mul(coeffseq))->setflag(status_flags::dynallocated);
310         }
311         
312         epvector::const_iterator i = seq.begin(), end = seq.end();
313         bool coeff_found = false;
314         while (i != end) {
315                 ex t = recombine_pair_to_ex(*i);
316                 ex c = t.coeff(s, n);
317                 if (!c.is_zero()) {
318                         coeffseq.push_back(c);
319                         coeff_found = 1;
320                 } else {
321                         coeffseq.push_back(t);
322                 }
323                 ++i;
324         }
325         if (coeff_found) {
326                 coeffseq.push_back(overall_coeff);
327                 return (new mul(coeffseq))->setflag(status_flags::dynallocated);
328         }
329         
330         return _ex0();
331 }
332
333 ex mul::eval(int level) const
334 {
335         // simplifications  *(...,x;0) -> 0
336         //                  *(+(x,y,...);c) -> *(+(*(x,c),*(y,c),...)) (c numeric())
337         //                  *(x;1) -> x
338         //                  *(;c) -> c
339         
340         debugmsg("mul eval",LOGLEVEL_MEMBER_FUNCTION);
341         
342         epvector *evaled_seqp = evalchildren(level);
343         if (evaled_seqp) {
344                 // do more evaluation later
345                 return (new mul(evaled_seqp,overall_coeff))->
346                            setflag(status_flags::dynallocated);
347         }
348         
349 #ifdef DO_GINAC_ASSERT
350         epvector::const_iterator i = seq.begin(), end = seq.end();
351         while (i != end) {
352                 GINAC_ASSERT((!is_ex_exactly_of_type(i->rest, mul)) ||
353                              (!(ex_to<numeric>(i->coeff).is_integer())));
354                 GINAC_ASSERT(!(cit->is_canonical_numeric()));
355                 if (is_ex_exactly_of_type(recombine_pair_to_ex(*i), numeric))
356                     print(print_tree(std::cerr));
357                 GINAC_ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*i), numeric));
358                 /* for paranoia */
359                 expair p = split_ex_to_pair(recombine_pair_to_ex(*i));
360                 GINAC_ASSERT(p.rest.is_equal(i->rest));
361                 GINAC_ASSERT(p.coeff.is_equal(i->coeff));
362                 /* end paranoia */
363                 ++i;
364         }
365 #endif // def DO_GINAC_ASSERT
366         
367         if (flags & status_flags::evaluated) {
368                 GINAC_ASSERT(seq.size()>0);
369                 GINAC_ASSERT(seq.size()>1 || !overall_coeff.is_equal(_ex1()));
370                 return *this;
371         }
372         
373         int seq_size = seq.size();
374         if (overall_coeff.is_zero()) {
375                 // *(...,x;0) -> 0
376                 return _ex0();
377         } else if (seq_size==0) {
378                 // *(;c) -> c
379                 return overall_coeff;
380         } else if (seq_size==1 && overall_coeff.is_equal(_ex1())) {
381                 // *(x;1) -> x
382                 return recombine_pair_to_ex(*(seq.begin()));
383         } else if ((seq_size==1) &&
384                    is_ex_exactly_of_type((*seq.begin()).rest,add) &&
385                    ex_to<numeric>((*seq.begin()).coeff).is_equal(_num1())) {
386                 // *(+(x,y,...);c) -> +(*(x,c),*(y,c),...) (c numeric(), no powers of +())
387                 const add & addref = ex_to<add>((*seq.begin()).rest);
388                 epvector *distrseq = new epvector();
389                 distrseq->reserve(addref.seq.size());
390                 epvector::const_iterator i = addref.seq.begin(), end = addref.seq.end();
391                 while (i != end) {
392                         distrseq->push_back(addref.combine_pair_with_coeff_to_pair(*i, overall_coeff));
393                         ++i;
394                 }
395                 return (new add(distrseq,
396                                 ex_to<numeric>(addref.overall_coeff).
397                                 mul_dyn(ex_to<numeric>(overall_coeff))))
398                       ->setflag(status_flags::dynallocated | status_flags::evaluated);
399         }
400         return this->hold();
401 }
402
403 ex mul::evalf(int level) const
404 {
405         if (level==1)
406                 return mul(seq,overall_coeff);
407         
408         if (level==-max_recursion_level)
409                 throw(std::runtime_error("max recursion level reached"));
410         
411         epvector *s = new epvector();
412         s->reserve(seq.size());
413
414         --level;
415         epvector::const_iterator i = seq.begin(), end = seq.end();
416         while (i != end) {
417                 s->push_back(combine_ex_with_coeff_to_pair(i->rest.evalf(level),
418                                                            i->coeff));
419                 ++i;
420         }
421         return mul(s, overall_coeff.evalf(level));
422 }
423
424 ex mul::evalm(void) const
425 {
426         // numeric*matrix
427         if (seq.size() == 1 && seq[0].coeff.is_equal(_ex1())
428          && is_ex_of_type(seq[0].rest, matrix))
429                 return ex_to<matrix>(seq[0].rest).mul(ex_to<numeric>(overall_coeff));
430
431         // Evaluate children first, look whether there are any matrices at all
432         // (there can be either no matrices or one matrix; if there were more
433         // than one matrix, it would be a non-commutative product)
434         epvector *s = new epvector;
435         s->reserve(seq.size());
436
437         bool have_matrix = false;
438         epvector::iterator the_matrix;
439
440         epvector::const_iterator i = seq.begin(), end = seq.end();
441         while (i != end) {
442                 const ex &m = recombine_pair_to_ex(*i).evalm();
443                 s->push_back(split_ex_to_pair(m));
444                 if (is_ex_of_type(m, matrix)) {
445                         have_matrix = true;
446                         the_matrix = s->end() - 1;
447                 }
448                 ++i;
449         }
450
451         if (have_matrix) {
452
453                 // The product contained a matrix. We will multiply all other factors
454                 // into that matrix.
455                 matrix m = ex_to<matrix>(the_matrix->rest);
456                 s->erase(the_matrix);
457                 ex scalar = (new mul(s, overall_coeff))->setflag(status_flags::dynallocated);
458                 return m.mul_scalar(scalar);
459
460         } else
461                 return (new mul(s, overall_coeff))->setflag(status_flags::dynallocated);
462 }
463
464 ex mul::simplify_ncmul(const exvector & v) const
465 {
466         if (seq.empty())
467                 return inherited::simplify_ncmul(v);
468
469         // Find first noncommutative element and call its simplify_ncmul()
470         epvector::const_iterator i = seq.begin(), end = seq.end();
471         while (i != end) {
472                 if (i->rest.return_type() == return_types::noncommutative)
473                         return i->rest.simplify_ncmul(v);
474                 ++i;
475         }
476         return inherited::simplify_ncmul(v);
477 }
478
479 // protected
480
481 /** Implementation of ex::diff() for a product.  It applies the product rule.
482  *  @see ex::diff */
483 ex mul::derivative(const symbol & s) const
484 {
485         unsigned num = seq.size();
486         exvector addseq;
487         addseq.reserve(num);
488         
489         // D(a*b*c) = D(a)*b*c + a*D(b)*c + a*b*D(c)
490         epvector mulseq = seq;
491         epvector::const_iterator i = seq.begin(), end = seq.end();
492         epvector::iterator i2 = mulseq.begin();
493         while (i != end) {
494                 expair ep = split_ex_to_pair(power(i->rest, i->coeff - _ex1()) *
495                                              i->rest.diff(s));
496                 ep.swap(*i2);
497                 addseq.push_back((new mul(mulseq, overall_coeff * i->coeff))->setflag(status_flags::dynallocated));
498                 ep.swap(*i2);
499                 ++i; ++i2;
500         }
501         return (new add(addseq))->setflag(status_flags::dynallocated);
502 }
503
504 int mul::compare_same_type(const basic & other) const
505 {
506         return inherited::compare_same_type(other);
507 }
508
509 bool mul::is_equal_same_type(const basic & other) const
510 {
511         return inherited::is_equal_same_type(other);
512 }
513
514 unsigned mul::return_type(void) const
515 {
516         if (seq.empty()) {
517                 // mul without factors: should not happen, but commutes
518                 return return_types::commutative;
519         }
520         
521         bool all_commutative = true;
522         epvector::const_iterator noncommutative_element; // point to first found nc element
523         
524         epvector::const_iterator i = seq.begin(), end = seq.end();
525         while (i != end) {
526                 unsigned rt = i->rest.return_type();
527                 if (rt == return_types::noncommutative_composite)
528                         return rt; // one ncc -> mul also ncc
529                 if ((rt == return_types::noncommutative) && (all_commutative)) {
530                         // first nc element found, remember position
531                         noncommutative_element = i;
532                         all_commutative = false;
533                 }
534                 if ((rt == return_types::noncommutative) && (!all_commutative)) {
535                         // another nc element found, compare type_infos
536                         if (noncommutative_element->rest.return_type_tinfo() != i->rest.return_type_tinfo()) {
537                                 // diffent types -> mul is ncc
538                                 return return_types::noncommutative_composite;
539                         }
540                 }
541                 ++i;
542         }
543         // all factors checked
544         return all_commutative ? return_types::commutative : return_types::noncommutative;
545 }
546    
547 unsigned mul::return_type_tinfo(void) const
548 {
549         if (seq.empty())
550                 return tinfo_key;  // mul without factors: should not happen
551         
552         // return type_info of first noncommutative element
553         epvector::const_iterator i = seq.begin(), end = seq.end();
554         while (i != end) {
555                 if (i->rest.return_type() == return_types::noncommutative)
556                         return i->rest.return_type_tinfo();
557                 ++i;
558         }
559         // no noncommutative element found, should not happen
560         return tinfo_key;
561 }
562
563 ex mul::thisexpairseq(const epvector & v, const ex & oc) const
564 {
565         return (new mul(v, oc))->setflag(status_flags::dynallocated);
566 }
567
568 ex mul::thisexpairseq(epvector * vp, const ex & oc) const
569 {
570         return (new mul(vp, oc))->setflag(status_flags::dynallocated);
571 }
572
573 expair mul::split_ex_to_pair(const ex & e) const
574 {
575         if (is_ex_exactly_of_type(e,power)) {
576                 const power & powerref = ex_to<power>(e);
577                 if (is_ex_exactly_of_type(powerref.exponent,numeric))
578                         return expair(powerref.basis,powerref.exponent);
579         }
580         return expair(e,_ex1());
581 }
582         
583 expair mul::combine_ex_with_coeff_to_pair(const ex & e,
584                                           const ex & c) const
585 {
586         // to avoid duplication of power simplification rules,
587         // we create a temporary power object
588         // otherwise it would be hard to correctly simplify
589         // expression like (4^(1/3))^(3/2)
590         if (are_ex_trivially_equal(c,_ex1()))
591                 return split_ex_to_pair(e);
592         
593         return split_ex_to_pair(power(e,c));
594 }
595         
596 expair mul::combine_pair_with_coeff_to_pair(const expair & p,
597                                             const ex & c) const
598 {
599         // to avoid duplication of power simplification rules,
600         // we create a temporary power object
601         // otherwise it would be hard to correctly simplify
602         // expression like (4^(1/3))^(3/2)
603         if (are_ex_trivially_equal(c,_ex1()))
604                 return p;
605         
606         return split_ex_to_pair(power(recombine_pair_to_ex(p),c));
607 }
608         
609 ex mul::recombine_pair_to_ex(const expair & p) const
610 {
611         if (ex_to<numeric>(p.coeff).is_equal(_num1())) 
612                 return p.rest;
613         else
614                 return power(p.rest,p.coeff);
615 }
616
617 bool mul::expair_needs_further_processing(epp it)
618 {
619         if (is_ex_exactly_of_type((*it).rest,mul) &&
620                 ex_to<numeric>((*it).coeff).is_integer()) {
621                 // combined pair is product with integer power -> expand it
622                 *it = split_ex_to_pair(recombine_pair_to_ex(*it));
623                 return true;
624         }
625         if (is_ex_exactly_of_type((*it).rest,numeric)) {
626                 expair ep=split_ex_to_pair(recombine_pair_to_ex(*it));
627                 if (!ep.is_equal(*it)) {
628                         // combined pair is a numeric power which can be simplified
629                         *it = ep;
630                         return true;
631                 }
632                 if (ex_to<numeric>((*it).coeff).is_equal(_num1())) {
633                         // combined pair has coeff 1 and must be moved to the end
634                         return true;
635                 }
636         }
637         return false;
638 }       
639
640 ex mul::default_overall_coeff(void) const
641 {
642         return _ex1();
643 }
644
645 void mul::combine_overall_coeff(const ex & c)
646 {
647         GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
648         GINAC_ASSERT(is_ex_exactly_of_type(c,numeric));
649         overall_coeff = ex_to<numeric>(overall_coeff).mul_dyn(ex_to<numeric>(c));
650 }
651
652 void mul::combine_overall_coeff(const ex & c1, const ex & c2)
653 {
654         GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
655         GINAC_ASSERT(is_ex_exactly_of_type(c1,numeric));
656         GINAC_ASSERT(is_ex_exactly_of_type(c2,numeric));
657         overall_coeff = ex_to<numeric>(overall_coeff).mul_dyn(ex_to<numeric>(c1).power(ex_to<numeric>(c2)));
658 }
659
660 bool mul::can_make_flat(const expair & p) const
661 {
662         GINAC_ASSERT(is_ex_exactly_of_type(p.coeff,numeric));
663         // this assertion will probably fail somewhere
664         // it would require a more careful make_flat, obeying the power laws
665         // probably should return true only if p.coeff is integer
666         return ex_to<numeric>(p.coeff).is_equal(_num1());
667 }
668
669 ex mul::expand(unsigned options) const
670 {
671         if (flags & status_flags::expanded)
672                 return *this;
673         
674         exvector sub_expanded_seq;
675         
676         epvector * expanded_seqp = expandchildren(options);
677         
678         const epvector & expanded_seq = expanded_seqp==0 ? seq : *expanded_seqp;
679         
680         int number_of_adds = 0;
681         epvector non_adds;
682         non_adds.reserve(expanded_seq.size());
683         epvector::const_iterator cit = expanded_seq.begin();
684         epvector::const_iterator last = expanded_seq.end();
685         ex last_expanded = _ex1();
686         while (cit!=last) {
687                 if (is_ex_exactly_of_type((*cit).rest,add) &&
688                         ((*cit).coeff.is_equal(_ex1()))) {
689                         ++number_of_adds;
690                         if (is_ex_exactly_of_type(last_expanded,add)) {
691                                 // expand adds
692                                 const add & add1 = ex_to<add>(last_expanded);
693                                 const add & add2 = ex_to<add>((*cit).rest);
694                                 int n1 = add1.nops();
695                                 int n2 = add2.nops();
696                                 exvector distrseq;
697                                 distrseq.reserve(n1*n2);
698                                 for (int i1=0; i1<n1; ++i1) {
699                                         for (int i2=0; i2<n2; ++i2) {
700                                                 distrseq.push_back(add1.op(i1)*add2.op(i2));
701                                         }
702                                 }
703                                 last_expanded = (new add(distrseq))->setflag(status_flags::dynallocated | status_flags::expanded);
704                         } else {
705                                 non_adds.push_back(split_ex_to_pair(last_expanded));
706                                 last_expanded = (*cit).rest;
707                         }
708                 } else {
709                         non_adds.push_back(*cit);
710                 }
711                 ++cit;
712         }
713         if (expanded_seqp)
714                 delete expanded_seqp;
715
716         if (is_ex_exactly_of_type(last_expanded,add)) {
717                 add const & finaladd = ex_to<add>(last_expanded);
718                 exvector distrseq;
719                 int n = finaladd.nops();
720                 distrseq.reserve(n);
721                 for (int i=0; i<n; ++i) {
722                         epvector factors = non_adds;
723                         factors.push_back(split_ex_to_pair(finaladd.op(i)));
724                         distrseq.push_back((new mul(factors,overall_coeff))->setflag(status_flags::dynallocated | status_flags::expanded));
725                 }
726                 return ((new add(distrseq))->
727                         setflag(status_flags::dynallocated | status_flags::expanded));
728         }
729         non_adds.push_back(split_ex_to_pair(last_expanded));
730         return (new mul(non_adds, overall_coeff))->
731                 setflag(status_flags::dynallocated | status_flags::expanded);
732 }
733
734   
735 //////////
736 // new virtual functions which can be overridden by derived classes
737 //////////
738
739 // none
740
741 //////////
742 // non-virtual functions in this class
743 //////////
744
745
746 /** Member-wise expand the expairs representing this sequence.  This must be
747  *  overridden from expairseq::expandchildren() and done iteratively in order
748  *  to allow for early cancallations and thus safe memory.
749  *
750  *  @see mul::expand()
751  *  @return pointer to epvector containing expanded representation or zero
752  *  pointer, if sequence is unchanged. */
753 epvector * mul::expandchildren(unsigned options) const
754 {
755         epvector::const_iterator last = seq.end();
756         epvector::const_iterator cit = seq.begin();
757         while (cit!=last) {
758                 const ex & factor = recombine_pair_to_ex(*cit);
759                 const ex & expanded_factor = factor.expand(options);
760                 if (!are_ex_trivially_equal(factor,expanded_factor)) {
761                         
762                         // something changed, copy seq, eval and return it
763                         epvector *s = new epvector;
764                         s->reserve(seq.size());
765                         
766                         // copy parts of seq which are known not to have changed
767                         epvector::const_iterator cit2 = seq.begin();
768                         while (cit2!=cit) {
769                                 s->push_back(*cit2);
770                                 ++cit2;
771                         }
772                         // copy first changed element
773                         s->push_back(split_ex_to_pair(expanded_factor));
774                         ++cit2;
775                         // copy rest
776                         while (cit2!=last) {
777                                 s->push_back(split_ex_to_pair(recombine_pair_to_ex(*cit2).expand(options)));
778                                 ++cit2;
779                         }
780                         return s;
781                 }
782                 ++cit;
783         }
784         
785         return 0; // nothing has changed
786 }
787
788 } // namespace GiNaC