From 6dcf7e0e253fa0fa29ca2831a1f59eee5d1e502f Mon Sep 17 00:00:00 2001 From: Jack Wrenn Date: Tue, 19 Feb 2019 18:00:29 -0500 Subject: [PATCH] Implement `iter::Sum` for `DMatrix` Fixes #514. --- src/base/ops.rs | 62 ++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 61 insertions(+), 1 deletion(-) diff --git a/src/base/ops.rs b/src/base/ops.rs index 96d4626fc..301232f2e 100644 --- a/src/base/ops.rs +++ b/src/base/ops.rs @@ -11,7 +11,7 @@ use base::allocator::{Allocator, SameShapeAllocator, SameShapeC, SameShapeR}; use base::constraint::{ AreMultipliable, DimEq, SameNumberOfColumns, SameNumberOfRows, ShapeConstraint, }; -use base::dimension::{Dim, DimMul, DimName, DimProd}; +use base::dimension::{Dim, DimMul, DimName, DimProd, Dynamic}; use base::storage::{ContiguousStorageMut, Storage, StorageMut}; use base::{DefaultAllocator, Matrix, MatrixMN, MatrixN, MatrixSum, Scalar}; @@ -384,6 +384,36 @@ where } } +impl iter::Sum for MatrixMN +where + N: Scalar + ClosedAdd + Zero, + DefaultAllocator: Allocator, +{ + /// # Example + /// ``` + /// # use nalgebra::DVector; + /// assert_eq!(vec![DVector::repeat(3, 1.0f64), + /// DVector::repeat(3, 1.0f64), + /// DVector::repeat(3, 1.0f64)].into_iter().sum::>(), + /// DVector::repeat(3, 1.0f64) + DVector::repeat(3, 1.0f64) + DVector::repeat(3, 1.0f64)); + /// ``` + /// + /// # Panics + /// Panics if the iterator is empty: + /// ```should_panic + /// # use std::iter; + /// # use nalgebra::DMatrix; + /// iter::empty::>().sum::>(); // panics! + /// ``` + fn sum>>(mut iter: I) -> MatrixMN { + if let Some(first) = iter.next() { + iter.fold(first, |acc, x| acc + x) + } else { + panic!("Cannot compute `sum` of empty iterator.") + } + } +} + impl<'a, N, R: DimName, C: DimName> iter::Sum<&'a MatrixMN> for MatrixMN where N: Scalar + ClosedAdd + Zero, @@ -394,6 +424,36 @@ where } } +impl<'a, N, C: Dim> iter::Sum<&'a MatrixMN> for MatrixMN +where + N: Scalar + ClosedAdd + Zero, + DefaultAllocator: Allocator, +{ + /// # Example + /// ``` + /// # use nalgebra::DVector; + /// let v = &DVector::repeat(3, 1.0f64); + /// + /// assert_eq!(vec![v, v, v].into_iter().sum::>(), + /// v + v + v); + /// ``` + /// + /// # Panics + /// Panics if the iterator is empty: + /// ```should_panic + /// # use std::iter; + /// # use nalgebra::DMatrix; + /// iter::empty::<&DMatrix>().sum::>(); // panics! + /// ``` + fn sum>>(mut iter: I) -> MatrixMN { + if let Some(first) = iter.next() { + iter.fold(first.clone(), |acc, x| acc + x) + } else { + panic!("Cannot compute `sum` of empty iterator.") + } + } +} + /* * * Multiplication