iliekturtles / uom

Units of measurement -- type-safe zero-cost dimensional analysis
Apache License 2.0
1.01k stars 92 forks source link

Missing implementation of product for Ratio #404

Closed JuliusHerrmann closed 1 year ago

JuliusHerrmann commented 1 year ago

Hi everyone, this is my first contribution/issue so please correct me on anything :). During a university course I came across the problem of calculating the product of an iterator of Ratios. This is an example that would not work but I think should be possible:

extern crate uom;

use uom::si::ratio::percent;
use uom::si::rational64::Ratio;

fn test_uom() -> Ratio {
    let ratios = vec![Ratio::new::<percent>(100.into()), Ratio::new::<percent>(200.into())];
    ratios.into_iter().product()
}

I searched around a bit and came across the "num" crate. This implements Ratio and product of ratios, so I think it should be possible for "uom" to do the same. This here works in the "num" crate:

use num::rational::Ratio;

fn test_num() -> num::rational::Ratio<usize> {
    let ratios = vec![Ratio::from_integer(1), Ratio::from_integer(2)];
    ratios.into_iter().product()
}

In the end I used

ratios.into_iter().fold(
    Ratio::new::<percent>(100.into()),
    |acc, x| acc * x
)

which worked. Which leads me to the conclusion that there is no fundamental problem hindering the support of product on ratios.

To sum it up I think product over ratios should/could be supported. Thanks :)

iliekturtles commented 1 year ago

Thanks for the issue, however this functionality was removed in #15 as it doesn't work in the general case! While the product of ratios is still a ratio the product of other quantities is not that same quantity. e.g. Length length = area. Length length * length = volume. Product requires that all items are of the same type and the result is also that same type.