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:
4 files changed
+42
-2
No files matched your search
+1
-1
@@ -13,7 +13,7 @@ fn main() -> io::Result<()> {
|
||||
|
||||
let line = line.unwrap();
|
||||
let parsed = math::parse(line.trim());
|
||||
println!("{:?}", parsed);
|
||||
println!("{}", parsed);
|
||||
|
||||
prompt()?;
|
||||
}
|
||||
|
||||
@@ -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,5 +1,6 @@
|
||||
use crate::math::types::Expression;
|
||||
|
||||
mod display;
|
||||
mod lexer;
|
||||
mod parser;
|
||||
|
||||
|
||||
@@ -6,7 +6,6 @@ pub enum Expression {
|
||||
Fraction(Box<Expression>, Box<Expression>),
|
||||
Variable(String),
|
||||
Operation(Operator, Box<Expression>, Box<Expression>),
|
||||
Negative(Box<Expression>),
|
||||
Function(String, Vec<Expression>),
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user