I'm trying to make an algebraic parser, and I've gotten decently far. I'm at the point where I can successfully multiply polynomials.
Full code here. Use the constructors along with the '*' overload and convert the resulting algexpr
object to a string using .latex()
to multiply and print to stdout. It's alpha at best, and I know there are many optimizations I need to make, I also still need to implement division, but that's not what my question is about.
x^2 is as algebraic term. So it 3ax, 7x^2(sin(x))zx, sin(a+b), and x^(2n+1). I'm having problems with the ones I have made bold. Both of these involve algebraic expressions, even though they are algebraic terms, but an algebraic expression is a vector of algebraic terms. So in order to completely represent an algebraic term, I need an algebraic expression, but an algebraic expression is a vector of algebraic terms. You can start to see my issue. I want to be able to use algebraic expressions inside algebraic terms.
The program doesn't work with the terms in bold, nor any expressions involving them. It enters an infinite loop instead, which is understandable since I haven't been able to figure out how I'd implement this yet.
Here's a minimal reproducible example to illustrate my troubles. This is what I want to do, however, this won't work.
code.cpp:8:3: error: ‘algexpr’ does not name a type
8 | algexpr power; // I can't use algexpr here because it's not defined yet.
code.cpp:
class variable {
public:
std::string name;
algexpr power; // I can't use algexpr here because it's not defined yet.
variable(std::string str) {
// fancy parsing code here
if (str == "x") {
name = "x";
power = algexpr("1");
}
}
};
class algterm {
public:
rfraction constant;
std::vector<variable> variables;
algterm(std::string str) {
// fancy parsing code here
if (str == "parse") {
constant = rfraction("1");
variables.push_back(variable("x"));
}
}
};
class algexpr {
public:
std::vector<algterm> terms;
algexpr(std::string str) {
// fancy parsing code here
terms.push_back(algterm("parse"));
}
};
I've tried thinking about what to do, but couldn't come up with anything that great. One idea was to store everything as strings (the expressions, variables, and terms) and just re-parse it every single time, but that's clearly not that efficient. How do I solve this?