mathhook_core/core/expression/
display.rs1use super::smart_display::SmartDisplayFormatter;
4use super::{Expression, RelationType};
5use std::fmt;
6
7impl fmt::Display for Expression {
8 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
9 match self {
10 Expression::Number(num) => write!(f, "{:?}", num),
11 Expression::Symbol(sym) => write!(f, "{}", sym.name),
12 Expression::Add(terms) => {
13 if terms.is_empty() {
14 write!(f, "0")
15 } else {
16 SmartDisplayFormatter::format_addition_smartly(f, terms)
17 }
18 }
19 Expression::Mul(factors) => {
20 if factors.is_empty() {
21 write!(f, "1")
22 } else {
23 SmartDisplayFormatter::format_multiplication_smartly(f, factors)
24 }
25 }
26 Expression::Pow(base, exp) => write!(f, "{}^{}", base, exp),
27 Expression::Function { name, args } => {
28 let arg_strs: Vec<String> = args.iter().map(|a| format!("{}", a)).collect();
29 write!(f, "{}({})", name, arg_strs.join(", "))
30 }
31 Expression::Constant(c) => write!(f, "{:?}", c),
32 Expression::Set(elements) => {
33 let elem_strs: Vec<String> = elements.iter().map(|e| format!("{}", e)).collect();
34 write!(f, "{{{}}}", elem_strs.join(", "))
35 }
36 Expression::Complex(data) => write!(f, "{} + {}i", data.real, data.imag),
37 Expression::Matrix(matrix) => {
38 let (rows, cols) = matrix.dimensions();
39 let mut row_strs = Vec::with_capacity(rows);
40
41 for i in 0..rows {
42 let mut col_strs = Vec::with_capacity(cols);
43 for j in 0..cols {
44 col_strs.push(format!("{}", matrix.get_element(i, j)));
45 }
46 row_strs.push(format!("[{}]", col_strs.join(", ")));
47 }
48
49 write!(f, "[{}]", row_strs.join(", "))
50 }
51 Expression::Relation(data) => {
52 let op = match data.relation_type {
53 RelationType::Equal => "=",
54 RelationType::NotEqual => "≠",
55 RelationType::Less => "<",
56 RelationType::LessEqual => "≤",
57 RelationType::Greater => ">",
58 RelationType::GreaterEqual => "≥",
59 RelationType::Approximate => "≈",
60 RelationType::Similar => "∼",
61 RelationType::Proportional => "∝",
62 RelationType::Congruent => "≅",
63 };
64 write!(f, "{} {} {}", data.left, op, data.right)
65 }
66 Expression::MethodCall(method_data) => {
67 if method_data.args.is_empty() {
68 write!(f, "{}.{}()", method_data.object, method_data.method_name)
69 } else {
70 let arg_strs: Vec<String> =
71 method_data.args.iter().map(|a| format!("{}", a)).collect();
72 write!(
73 f,
74 "{}.{}({})",
75 method_data.object,
76 method_data.method_name,
77 arg_strs.join(", ")
78 )
79 }
80 }
81 _ => write!(f, "{:?}", self),
82 }
83 }
84}