#[derive(Debug, PartialEq, Clone)]
pub struct Operator {
pub id: char,
pub function: fn(f64, f64) -> f64,
order: usize,
}
impl Operator {
pub fn after(&self, other: &Self) -> bool {
self.order > other.order
}
pub fn divide() -> Self {
Self {
id: '/',
function: |x, y| x / y,
order: 2,
}
}
pub fn multiply() -> Self {
Self {
id: '*',
function: |x, y| x * y,
order: 2,
}
}
pub fn add() -> Self {
Self {
id: '+',
function: |x, y| x + y,
order: 3,
}
}
pub fn subtract() -> Self {
Self {
id: '-',
function: |x, y| x - y,
order: 3,
}
}
}
impl TryFrom<&str> for Operator {
type Error = &'static str;
fn try_from(value: &str) -> Result<Self, Self::Error> {
match value {
"*" => Ok(Operator::multiply()),
"/" => Ok(Operator::divide()),
"+" => Ok(Operator::add()),
"-" => Ok(Operator::subtract()),
_ => Err("Unknown operator."),
}
}
}
#[cfg(test)]
mod tests {
use super::Operator;
#[test]
fn after_true() {
let add = Operator::add();
let multiply = Operator::multiply();
assert!(add.after(&multiply), "Addition comes after multiplication.");
}
#[test]
fn after_false() {
let add = Operator::add();
let multiply = Operator::multiply();
assert!(
!multiply.after(&add),
"Multiplication does not come after addition."
);
}
}