From b89a453c0764816218dff0208944666f025324c2 Mon Sep 17 00:00:00 2001 From: Andrew Milson Date: Wed, 20 Mar 2024 03:22:47 -0400 Subject: [PATCH] Implement 'Sum' and 'Product' on field types (#497) --- src/core/fields/mod.rs | 45 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/src/core/fields/mod.rs b/src/core/fields/mod.rs index 72693b5fa..ee4b9a8a9 100644 --- a/src/core/fields/mod.rs +++ b/src/core/fields/mod.rs @@ -1,4 +1,5 @@ use std::fmt::{Debug, Display}; +use std::iter::{Product, Sum}; use std::ops::{Mul, MulAssign, Neg}; use num_traits::{NumAssign, NumAssignOps, NumOps, One}; @@ -108,6 +109,10 @@ pub trait Field: + Sync + Sized + FieldExpOps + + Product + + for<'a> Product<&'a Self> + + Sum + + for<'a> Sum<&'a Self> { fn double(&self) -> Self { (*self) + (*self) @@ -160,6 +165,8 @@ impl ExtensionOf for F { #[macro_export] macro_rules! impl_field { ($field_name: ty, $field_size: ident) => { + use std::iter::{Product, Sum}; + use num_traits::{Num, One, Zero}; use $crate::core::fields::Field; @@ -232,6 +239,44 @@ macro_rules! impl_field { self.pow(($field_size - 2) as u128) } } + + impl Product for $field_name { + fn product(mut iter: I) -> Self + where + I: Iterator, + { + let first = iter.next().unwrap_or_else(Self::one); + iter.fold(first, |a, b| a * b) + } + } + + impl<'a> Product<&'a Self> for $field_name { + fn product(iter: I) -> Self + where + I: Iterator, + { + iter.map(|&v| v).product() + } + } + + impl Sum for $field_name { + fn sum(mut iter: I) -> Self + where + I: Iterator, + { + let first = iter.next().unwrap_or_else(Self::zero); + iter.fold(first, |a, b| a + b) + } + } + + impl<'a> Sum<&'a Self> for $field_name { + fn sum(iter: I) -> Self + where + I: Iterator, + { + iter.map(|&v| v).sum() + } + } }; }