diff --git a/src/parser/expression/expression.rs b/src/parser/expression/expression.rs index 4ac5ff3..fa1d5d6 100644 --- a/src/parser/expression/expression.rs +++ b/src/parser/expression/expression.rs @@ -46,8 +46,22 @@ impl Expression { } } - // True if this is a power operator applied to a constant or variable - // and an integer. + // True if this is a unitless integer + pub fn is_unitless_integer(&self) -> bool { + match self { + Expression::Quantity(_, q) => { + return q.unitless() && q.fract().is_zero(); + }, + Expression::Operator(_, Operator::Negative, q) => { + assert!(q.len() == 1); + let Expression::Quantity(_, q) = &q[0] else { return false }; + return q.unitless() && q.fract().is_zero(); + } + _ => { return false; } + } + } + + // True if this is a integer power operator applied to a constant or variable. // Examples: pi^2, x ^ 3 pub fn is_poly_power(&self) -> bool { match self { @@ -58,7 +72,7 @@ impl Expression { let base = &a[0]; let power = &a[1]; - // Make sure base ks const or variable + // Make sure base is const or variable match base { Expression::Constant(_, _) | Expression::Variable(_, _) @@ -68,14 +82,7 @@ impl Expression { }; // Make sure power is an integer - match power { - Expression::Quantity(_, q) => { - return q.unitless() && q.fract().is_zero(); - }, - _ => { return false; } - } - - + return power.is_unitless_integer(); }, _ => { return false; } }; diff --git a/src/parser/expression/operator.rs b/src/parser/expression/operator.rs index 7d2e798..1486dd9 100644 --- a/src/parser/expression/operator.rs +++ b/src/parser/expression/operator.rs @@ -206,40 +206,34 @@ impl Operator { }, Operator::Power => { - if let Expression::Quantity(_, q) = &args[1] { - if q.unitless() && q.fract().is_zero() { - // Write integer powers as a superscript - let mut b = String::new(); - for c in q.to_string().chars() { - b.push( match c { - '-' => '⁻', - '0' => '⁰', - '1' => '¹', - '2' => '²', - '3' => '³', - '4' => '⁴', - '5' => '⁵', - '6' => '⁶', - '7' => '⁷', - '8' => '⁸', - '9' => '⁹', - _ => unreachable!() - }); - } + let q = &args[1]; - return format!( - "{}{}", - self.add_parens_to_arg_strict(&args[0]), - b - ); - } else { - return format!( - "{}^{}", - self.add_parens_to_arg_strict(&args[0]), - self.add_parens_to_arg_strict(&args[1]) - ); + if q.is_unitless_integer() { + // Write integer powers as a superscript + let mut b = String::new(); + for c in q.to_string().chars() { + b.push( match c { + '-' => '⁻', + '0' => '⁰', + '1' => '¹', + '2' => '²', + '3' => '³', + '4' => '⁴', + '5' => '⁵', + '6' => '⁶', + '7' => '⁷', + '8' => '⁸', + '9' => '⁹', + _ => unreachable!() + }); } + + return format!( + "{}{}", + self.add_parens_to_arg_strict(&args[0]), + b + ); } else { return format!( "{}^{}",