Skip to main content

filter_unary_function

Function filter_unary_function 

Source
pub fn filter_unary_function<F, G>(
    influencing_factors: &[DynQuantity<f64>],
    match_for: Unit,
    with_matched: F,
    no_match: G,
) -> DynQuantity<f64>
Expand description

A helper function which filters the influencing_factors for a quantity with the type match_for. If a matching quantity is found, it is used as argument for F and the result is returned. Otherwise, the result of G() is returned.

The main purpose of this function is to simplify writing unary functions. For example, the IsQuantityFunction::call implementation of a linear function can look like this:

use dyn_quantity::{DynQuantity, Unit};
use var_quantity::{filter_unary_function, IsQuantityFunction};

// The serde annotations are just here because the doctests of this crate use
// the serde feature - they are not needed if the serde feature is disabled.
#[derive(Clone, serde::Serialize, serde::Deserialize)]
pub struct Linear {
    slope: f64,
    base_value: f64,
}

// Again, the macro annotation is just here because of the serde feature
#[cfg_attr(feature = "serde", typetag::serde)]
impl IsQuantityFunction for Linear {
    fn call(&self, influencing_factors: &[DynQuantity<f64>]) -> DynQuantity<f64> {
        return filter_unary_function(
            influencing_factors,
            Unit::default(),
            |input| {
                DynQuantity::new(
                    self.base_value + self.slope * input.value,
                    Unit::default(),
                )
            },
            || DynQuantity::new(
                    self.base_value,
                    Unit::default(),
                ),
        );
    }
}