It's not hard to see how this leads to a lot of repetitive and error-prone code. |
The
default: assert(false);
so far managed to catch all such mistakes (at least I hope so)- in my experience I didn't lose much time with this switch-design. That doesn't mean yours isn't better of course.
The real mess comes with implementing arbitrary functions. I don't believe it is possible however to get any clean solution there (actually, this problem is hard for humans too, not only for computers).
Imagine you have a function
gaussianElimination( (Rational,...),...)
that takes a matrix of rationals as input.
Now
|
gaussianElimination( (1,1), (1, 2) )
|
(2 by 2 matrix)
should work equally well as
|
gaussianElimination( (1, 2) )
|
(1 by 2 matrix)
should work equally well as
|
gaussianElimination( 1, 1 )
|
(2 by 1 matrix)
However, this should cause an error:
|
gaussianElimination( 1, (1,2) )
|
I don't believe there is a sane way to catch such an error at parsing time. This must be an evaluation-time-error.
[Edit:] As for union-like structures: well, I have implicit type conversion system.
What do you mean?
|
Let me illustrate by example:
Imagine I need to parse & evaluate
2 + x_1
After parsing, my expression tree looks like:
1 2 3 4 5
|
Y0 = Y1 + Y2 Expression type: (?) we dont know yet, at the end will be Polynomial
Y1 = 2 Expression type: Integer (must be converted at the end to Polynomial)
Y2= Y3 _ Y4 Expression type: (?) we dont know yet, at the end will be Polynomial
Y3= the letter x Expression type: Letter
Y4= 1 Expression type: Integer
|
Now when I carry out Y0=Y1+ Y2, I need to carry out an implicit conversion of Y1 from
Integer
to type
Polynomial
(my default polynomials are with rational coefficients). So, besides the
"Y1.Evaluate()"
I also call
"Y1.ConvertToType(typePolynomial, impliedNumberOfVariables)"
The newly produced value of Y1 is the constant polynomial 2. I store the newly produced value in the very same node Y1, but change the expressionType.
This is why I think it is simple to have the all-in-one solution (say, by using unions; I use another uglier solution at the moment).