/*evaluator.cc This is an evaluator for a language of well-formed formulae (WFF's) in the propositional calculus. It demonstrates techniques to be understood and used in the design of your PURPLE evaluator, the final project for computer science at Duke University TIP. Copyright (c) 1998 by Matthew Belmonte.*/ /*NOTE: Since WFFs have Boolean values, these evaluation functions return Boolean values. In the parser that you are writing, some subtrees (arithmetic expressions) will have numeric values, and some subtrees (statements) will not have any meaningful value at all. So use this evaluator as a loose guide, but DON'T follow it very closely; it WILL NOT WORK if what you're trying to evaluate is not a Boolean.*/ #include #include "vector.h" #include /*needed for input*/ #include "scanner.h" #include "parser.h" #include "evaluator.h" Variable::Variable() {defined = false;} void Variable::set(bool newvalue) { defined = true; value = newvalue; } bool Variable::get() { char t_or_f; if(!defined) cout << "type a value (T or F): "; while(!defined) { /*The semantics of the WFF language require that if an undefined variable is referenced, a value for the variable is to be asked for. (The semantics of PURPLE differ; in the case of PURPLE, a reference to an undefined variable causes a run-time error.)*/ t_or_f = getchar(); defined = ((t_or_f == 'T') || (t_or_f == 'F')); value = (t_or_f == 'T'); } return(value); } static Vector variables('Z'-'A'+1); /*values for all variables*/ static bool evaluate(Tree *expr) { /*'expr' points to a parse tree representing a formula*/ switch(expr->oper.type) { case NotToken: return(!evaluate(expr->left)); case AndToken: return(evaluate(expr->left) && evaluate(expr->right)); case OrToken: return(evaluate(expr->left) || evaluate(expr->right)); case ImpliesToken: return(!evaluate(expr->left) || evaluate(expr->right)); /*remember DeMorgan's Law*/ case EquivToken: return(evaluate(expr->left) == evaluate(expr->right)); case IdentifierToken: return(variables[expr->oper.identifier - 'A'].get()); } } int main(int argc, char **argv) { cout << "Type a WFF:" << endl; cout << evaluate(parse_formula()) << endl; return(0); }