Trait arithmetic_eval::arith::ArithmeticExt[][src]

pub trait ArithmeticExt<T>: Arithmetic<T> + Sized {
    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::builder("test", &program)?.build();
assert_eq!(
    module.with_arithmetic(&base.without_comparisons()).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(r#"
    (x, y, z) = (1, 12, 5);
    x == y && x < z && y > z
"#)?;
let module = ExecutableModule::builder("test", &program)?.build();
assert_eq!(
    module.with_arithmetic(&bogus_arithmetic).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))
});
assert_eq!(
    module.with_arithmetic(&less_bogus_arithmetic).run()?,
    Value::Bool(false)
);

Provided methods

fn without_comparisons(self) -> FullArithmetic<T, Self>[src]

Combines this arithmetic with a comparison function that assumes any two values are incomparable.

fn with_natural_comparison(self) -> FullArithmetic<T, Self> where
    T: PartialOrd
[src]

Combines this arithmetic with a comparison function specified by the PartialOrd implementation for T.

fn with_comparison(
    self,
    comparison: fn(_: &T, _: &T) -> Option<Ordering>
) -> FullArithmetic<T, Self>
[src]

Combines this arithmetic with the specified comparison function.

Implementors

impl<T, A> ArithmeticExt<T> for A where
    A: Arithmetic<T>, 
[src]