Trait arithmetic_eval::arith::ArithmeticExt
source · pub trait ArithmeticExt<T>: Arithmetic<T> + Sized {
// Provided methods
fn without_comparisons(self) -> FullArithmetic<T, Self> { ... }
fn with_natural_comparison(self) -> FullArithmetic<T, Self>
where T: PartialOrd { ... }
fn with_comparison(
self,
comparison: fn(_: &T, _: &T) -> Option<Ordering>,
) -> FullArithmetic<T, Self> { ... }
}
Expand description
Extension trait for Arithmetic
allowing to combine the arithmetic with comparisons.
§Examples
use arithmetic_eval::arith::{ArithmeticExt, ModularArithmetic};
let base = ModularArithmetic::new(11);
// `ModularArithmetic` requires to define how numbers will be compared -
// and the simplest solution is to not compare them at all.
let program = Untyped::<NumGrammar<u32>>::parse_statements("1 < 3 || 1 >= 3")?;
let module = ExecutableModule::new("test", &program)?;
let env = Environment::with_arithmetic(base.without_comparisons());
assert_eq!(module.with_env(&env)?.run()?, Value::Bool(false));
// We can compare numbers by their integer value. This can lead
// to pretty confusing results, though.
let bogus_arithmetic = base.with_natural_comparison();
let program = Untyped::<NumGrammar<u32>>::parse_statements("
(x, y, z) = (1, 12, 5);
x == y && x < z && y > z
")?;
let module = ExecutableModule::new("test", &program)?;
let env = Environment::with_arithmetic(bogus_arithmetic);
assert_eq!(module.with_env(&env)?.run()?, Value::Bool(true));
// It's possible to fix the situation using a custom comparison function,
// which will compare numbers by their residual class.
let less_bogus_arithmetic = base.with_comparison(|&x: &u32, &y: &u32| {
(x % 11).partial_cmp(&(y % 11))
});
let env = Environment::with_arithmetic(less_bogus_arithmetic);
assert_eq!(module.with_env(&env)?.run()?, Value::Bool(false));
Provided Methods§
sourcefn without_comparisons(self) -> FullArithmetic<T, Self>
fn without_comparisons(self) -> FullArithmetic<T, Self>
Combines this arithmetic with a comparison function that assumes any two values are incomparable.
sourcefn with_natural_comparison(self) -> FullArithmetic<T, Self>where
T: PartialOrd,
fn with_natural_comparison(self) -> FullArithmetic<T, Self>where
T: PartialOrd,
Combines this arithmetic with a comparison function specified by the PartialOrd
implementation for T
.
sourcefn with_comparison(
self,
comparison: fn(_: &T, _: &T) -> Option<Ordering>,
) -> FullArithmetic<T, Self>
fn with_comparison( self, comparison: fn(_: &T, _: &T) -> Option<Ordering>, ) -> FullArithmetic<T, Self>
Combines this arithmetic with the specified comparison function.
Object Safety§
This trait is not object safe.