Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow mean on both f32 and &f32 #122

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 38 additions & 14 deletions src/statistics/mean.rs
Original file line number Diff line number Diff line change
@@ -1,23 +1,36 @@
/// Arithmetic mean
pub trait Mean {
/// Result type
type Result;

/// Compute the arithmetic mean
fn mean(self) -> Self::Result;
/// Provide the Mean trait for Iterators
pub trait MeanExt: Iterator {
/// Compute the arithmetic mean of this iterator
fn mean(self) -> f32
where
Self: Sized,
f32: Mean<Self::Item>,
{
f32::mean(self)
}
}

impl<I> Mean for I
where
I: Iterator<Item = f32>,
{
type Result = f32;
impl<I: Iterator> MeanExt for I {}

/// Types for which a mean can be calculated
pub trait Mean<A = Self> {
/// Compute the arithmetic mean of the given iterator
fn mean<I>(iter: I) -> Self
where
I: Iterator<Item = A>;
}

fn mean(self) -> f32 {
impl Mean for f32 {
fn mean<I>(iter: I) -> Self
where
I: Iterator<Item = f32>,
{
let mut num_items = 0;
let mut sum = 0.0;

for item in self {
for item in iter {
num_items += 1;
sum += item;
}
Expand All @@ -26,12 +39,23 @@ where
}
}

impl<'a> Mean<&'a f32> for f32 {
fn mean<I>(iter: I) -> Self
where
I: Iterator<Item = &'a f32>,
{
iter.copied().mean()
}
}

#[cfg(test)]
mod tests {
use super::Mean;
use super::MeanExt;

#[test]
fn mean_test() {
assert_eq!([1.0, 3.0, 5.0].iter().cloned().mean(), 3.0);
assert_eq!([1.0, 3.0, 5.0].iter().mean(), 3.0);

assert_eq!(IntoIterator::into_iter([1.0, 3.0, 5.0]).mean(), 3.0);
}
}
2 changes: 1 addition & 1 deletion src/statistics/trim.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! Iterate over input slices after culling statistical outliers.

use super::mean::Mean;
use super::mean::MeanExt;
#[allow(unused_imports)]
use crate::F32Ext;
use core::{iter, slice};
Expand Down
2 changes: 1 addition & 1 deletion src/statistics/variance.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use super::mean::Mean;
use super::mean::MeanExt;

/// Statistical variance
pub trait Variance {
Expand Down
Loading