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
This commit is contained in:
ozzy committed 2026-09-25 20:46:43 -05:00
1 parent 66da876e2a
commit 64d6f8f095
4 files changed
+42 -2

No files matched your search

+1 -1
View File
@@ -13,7 +13,7 @@ fn main() -> io::Result<()> {
let line = line.unwrap(); let line = line.unwrap();
let parsed = math::parse(line.trim()); let parsed = math::parse(line.trim());
println!("{:?}", parsed); println!("{}", parsed);
prompt()?; prompt()?;
} }
+40
View File
@@ -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::<Vec<_>>()
.join(", ");
write!(f, "{}({})", name, params)
}
}
}
}
+1
View File
@@ -1,5 +1,6 @@
use crate::math::types::Expression; use crate::math::types::Expression;
mod display;
mod lexer; mod lexer;
mod parser; mod parser;
-1
View File
@@ -6,7 +6,6 @@ pub enum Expression {
Fraction(Box<Expression>, Box<Expression>), Fraction(Box<Expression>, Box<Expression>),
Variable(String), Variable(String),
Operation(Operator, Box<Expression>, Box<Expression>), Operation(Operator, Box<Expression>, Box<Expression>),
Negative(Box<Expression>),
Function(String, Vec<Expression>), Function(String, Vec<Expression>),
} }