ready_set_boole/src/boolean_evaluation.rs

28 lines
802 B
Rust

mod tests;
use crate::ast::{Node, Token};
fn compute(operator: Token, lhs: bool, rhs: bool) -> bool {
match operator {
Token::Negation => !lhs,
Token::Conjunction => lhs & rhs,
Token::Disjunction => lhs | rhs,
Token::ExclusiveDisjunction => lhs ^ rhs,
Token::MaterialCondition => !(lhs && !rhs),
Token::LogicalEquivalence => lhs == rhs,
}
}
fn evaluate(tree: Node<bool>) -> bool {
match tree {
Node::Unary { operator, operand } => compute(operator, evaluate(*operand), false),
Node::Binary { operator, lhs, rhs } => compute(operator, evaluate(*lhs), evaluate(*rhs)),
Node::Leaf(b) => b,
}
}
pub fn eval_formula(formula: &str) -> bool {
let tree = Node::<bool>::parse_formula(formula);
evaluate(tree)
}