From 322336e98560e743b57b45440769dd95b9836860 Mon Sep 17 00:00:00 2001 From: Thomas Coratger <60488569+tcoratger@users.noreply.github.com> Date: Tue, 19 Nov 2024 19:03:30 +0100 Subject: [PATCH] poly: small refactor for `SparsePolynomial` (#871) * poly: small refactor for SparsePolynomial * Update poly/src/polynomial/univariate/sparse.rs Co-authored-by: Pratyush Mishra * fix --------- Co-authored-by: Pratyush Mishra --- poly/src/polynomial/univariate/sparse.rs | 27 +++++++++++------------- 1 file changed, 12 insertions(+), 15 deletions(-) diff --git a/poly/src/polynomial/univariate/sparse.rs b/poly/src/polynomial/univariate/sparse.rs index 313bb1f5a..460cb8206 100644 --- a/poly/src/polynomial/univariate/sparse.rs +++ b/poly/src/polynomial/univariate/sparse.rs @@ -262,8 +262,7 @@ impl SparsePolynomial { *cur_coeff += &(*self_coeff * other_coeff); } } - let result = result.into_iter().collect::>(); - SparsePolynomial::from_coefficients_vec(result) + SparsePolynomial::from_coefficients_vec(result.into_iter().collect()) } } @@ -272,9 +271,7 @@ impl SparsePolynomial { // being higher than self.degree() fn append_coeffs(&mut self, append_coeffs: &[(usize, F)]) { assert!(append_coeffs.is_empty() || self.degree() < append_coeffs[0].0); - for (i, elem) in append_coeffs.iter() { - self.coeffs.push((*i, *elem)); - } + self.coeffs.extend_from_slice(append_coeffs); } } @@ -285,13 +282,13 @@ impl SparsePolynomial { domain: D, ) -> Evaluations { let poly: DenseOrSparsePolynomial<'_, F> = self.into(); - DenseOrSparsePolynomial::::evaluate_over_domain(poly, domain) + DenseOrSparsePolynomial::evaluate_over_domain(poly, domain) } /// Evaluate `self` over `domain`. pub fn evaluate_over_domain>(self, domain: D) -> Evaluations { let poly: DenseOrSparsePolynomial<'_, F> = self.into(); - DenseOrSparsePolynomial::::evaluate_over_domain(poly, domain) + DenseOrSparsePolynomial::evaluate_over_domain(poly, domain) } } @@ -307,14 +304,14 @@ impl From> for DensePolynomial { impl From> for SparsePolynomial { fn from(dense_poly: DensePolynomial) -> SparsePolynomial { - let coeffs = dense_poly.coeffs(); - let mut sparse_coeffs = Vec::<(usize, F)>::new(); - for (i, coeff) in coeffs.iter().enumerate() { - if !coeff.is_zero() { - sparse_coeffs.push((i, *coeff)); - } - } - SparsePolynomial::from_coefficients_vec(sparse_coeffs) + SparsePolynomial::from_coefficients_vec( + dense_poly + .coeffs() + .iter() + .enumerate() + .filter_map(|(i, coeff)| (!coeff.is_zero()).then(|| (i, *coeff))) + .collect(), + ) } }