Improved superscripts

pull/2/head
Mark 2023-08-02 12:37:29 -07:00
parent f35aeefeb1
commit 9698a691aa
Signed by: Mark
GPG Key ID: AD62BB059C2AAEE4
2 changed files with 43 additions and 42 deletions

View File

@ -46,8 +46,22 @@ impl Expression {
} }
} }
// True if this is a power operator applied to a constant or variable // True if this is a unitless integer
// and an 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 // Examples: pi^2, x ^ 3
pub fn is_poly_power(&self) -> bool { pub fn is_poly_power(&self) -> bool {
match self { match self {
@ -58,7 +72,7 @@ impl Expression {
let base = &a[0]; let base = &a[0];
let power = &a[1]; let power = &a[1];
// Make sure base ks const or variable // Make sure base is const or variable
match base { match base {
Expression::Constant(_, _) Expression::Constant(_, _)
| Expression::Variable(_, _) | Expression::Variable(_, _)
@ -68,14 +82,7 @@ impl Expression {
}; };
// Make sure power is an integer // Make sure power is an integer
match power { return power.is_unitless_integer();
Expression::Quantity(_, q) => {
return q.unitless() && q.fract().is_zero();
},
_ => { return false; }
}
}, },
_ => { return false; } _ => { return false; }
}; };

View File

@ -206,40 +206,34 @@ impl Operator {
}, },
Operator::Power => { Operator::Power => {
if let Expression::Quantity(_, q) = &args[1] {
if q.unitless() && q.fract().is_zero() {
// Write integer powers as a superscript let q = &args[1];
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!( if q.is_unitless_integer() {
"{}{}", // Write integer powers as a superscript
self.add_parens_to_arg_strict(&args[0]), let mut b = String::new();
b for c in q.to_string().chars() {
); b.push( match c {
} else { '-' => '⁻',
return format!( '0' => '⁰',
"{}^{}", '1' => '¹',
self.add_parens_to_arg_strict(&args[0]), '2' => '²',
self.add_parens_to_arg_strict(&args[1]) '3' => '³',
); '4' => '⁴',
'5' => '⁵',
'6' => '⁶',
'7' => '⁷',
'8' => '⁸',
'9' => '⁹',
_ => unreachable!()
});
} }
return format!(
"{}{}",
self.add_parens_to_arg_strict(&args[0]),
b
);
} else { } else {
return format!( return format!(
"{}^{}", "{}^{}",