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