Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Operand::pointer_type RPNEvaluator::evaluate(TokenList const& rpnExpression) {
- Operand::pointer_type result;
- stack <Operand::pointer_type> operand_stack;
- if (rpnExpression.empty())
- throw exception("Error: insufficient operands");
- for (auto x : rpnExpression)
- {
- if (is<Operand>(x))
- {
- operand_stack.push(convert<Operand>(x));
- }
- else
- {
- auto opera = convert<Operation>(x);
- if (dynamic_pointer_cast<Operation>(x)->number_of_args() > operand_stack.size())
- {
- throw exception("Insufficient # operands for operation");
- }
- OperandList opList;
- unsigned size = opera->number_of_args();
- while (size != 0)
- {
- opList.push_front(operand_stack.top());
- operand_stack.pop();
- --size;
- }
- //operand_stack.push(convert<Operand>(x));
- if (is<UnaryOperator>(opera))
- {
- if (is<Negation>(opera))
- {
- if (opList.size() == 1) {
- if (is<Integer>(opList[0])) {
- if (is<Integer>(opList[0])) {
- Integer::value_type temp = (dynamic_pointer_cast<Integer>(opList[0])->get_value()) * -1;
- operand_stack.push(dynamic_pointer_cast<Operand>(make<Integer>(temp)));
- }
- }
- else if (is<Real>(opList[0])) {
- Real::value_type temp = dynamic_pointer_cast<Real>(opList[0])->get_value() * -1;
- operand_stack.push(dynamic_pointer_cast<Operand>(make<Real>(temp)));
- }
- }
- else
- {
- throw invalid_argument("Operands Not Valid For Operation");
- operand_stack.push(dynamic_pointer_cast<Operand>(make<Integer>(0)));
- }
- }
- if (is<Identity>(opera))
- {
- if (opList.size() == 1)
- {
- Integer::value_type temp = dynamic_pointer_cast<Integer>(opList[0])->get_value();
- operand_stack.push(dynamic_pointer_cast<Operand>(make<Integer>(temp)));
- }
- }
- if (is<Factorial>(opera))
- {
- Integer::value_type temp = dynamic_pointer_cast<Integer>(opList[0])->get_value();
- temp = factorial(temp);
- operand_stack.push(dynamic_pointer_cast<Operand>(make<Integer>(temp)));
- }
- }
- }
- }
- if (operand_stack.size() > 1)
- throw exception("Error: too many operands");
- if (operand_stack.empty())
- throw exception("Too many operations for the number of operands");
- result = operand_stack.top();
- operand_stack.pop();
- //result = rpnExpression;
- return result; // replace this with the result.
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement