From 64d6f8f095f59db1d7b3ad317ccc738f2c43d8d2 Mon Sep 17 00:00:00 2001 From: ozzy <2+ozzy@noreply.localhost> Date: Fri, 25 Sep 2026 20:46:43 -0500 Subject: [PATCH] feat(types): implement display implement display on expression and operator so that math expressions can be turned back into strings that could theoretically be parsed again --- src/main.rs | 2 +- src/math/display.rs | 40 ++++++++++++++++++++++++++++++++++++++++ src/math/mod.rs | 1 + src/math/types.rs | 1 - 4 files changed, 42 insertions(+), 2 deletions(-) create mode 100644 src/math/display.rs diff --git a/src/main.rs b/src/main.rs index 90ca472..9970096 100644 --- a/src/main.rs +++ b/src/main.rs @@ -13,7 +13,7 @@ fn main() -> io::Result<()> { let line = line.unwrap(); let parsed = math::parse(line.trim()); - println!("{:?}", parsed); + println!("{}", parsed); prompt()?; } diff --git a/src/math/display.rs b/src/math/display.rs new file mode 100644 index 0000000..515e77b --- /dev/null +++ b/src/math/display.rs @@ -0,0 +1,40 @@ +use std::fmt::Display; + +use crate::math::types::{Expression, Operator}; + +impl Display for Operator { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let symbol = match self { + Operator::Add => "+", + Operator::Subtract => "-", + Operator::Multiply => "*", + Operator::Divide => "/", + Operator::Power => "^", + Operator::Modulo => "%", + }; + write!(f, "{}", symbol) + } +} + +impl Display for Expression { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Expression::Number(num) => write!(f, "{}", num), + Expression::Variable(var) => write!(f, "{}", var), + Expression::Fraction(numerator, denominator) => { + write!(f, "({}) / ({})", numerator, denominator) + } + Expression::Operation(operator, left, right) => { + write!(f, "({}) {} ({})", left, operator, right) + } + Expression::Function(name, params) => { + let params: String = params + .iter() + .map(|p| p.to_string()) + .collect::>() + .join(", "); + write!(f, "{}({})", name, params) + } + } + } +} diff --git a/src/math/mod.rs b/src/math/mod.rs index 6a5ad7d..65368d0 100644 --- a/src/math/mod.rs +++ b/src/math/mod.rs @@ -1,5 +1,6 @@ use crate::math::types::Expression; +mod display; mod lexer; mod parser; diff --git a/src/math/types.rs b/src/math/types.rs index 3be98ed..e4ae196 100644 --- a/src/math/types.rs +++ b/src/math/types.rs @@ -6,7 +6,6 @@ pub enum Expression { Fraction(Box, Box), Variable(String), Operation(Operator, Box, Box), - Negative(Box), Function(String, Vec), }