Skip to content

Commit

Permalink
Implement 'Sum' and 'Product' on field types (#497)
Browse files Browse the repository at this point in the history
  • Loading branch information
andrewmilson authored Mar 20, 2024
1 parent 828bdf3 commit b89a453
Showing 1 changed file with 45 additions and 0 deletions.
45 changes: 45 additions & 0 deletions src/core/fields/mod.rs
Original file line number Diff line number Diff line change
@@ -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};
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -160,6 +165,8 @@ impl<F: Field> ExtensionOf<F> 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;

Expand Down Expand Up @@ -232,6 +239,44 @@ macro_rules! impl_field {
self.pow(($field_size - 2) as u128)
}
}

impl Product for $field_name {
fn product<I>(mut iter: I) -> Self
where
I: Iterator<Item = Self>,
{
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<I>(iter: I) -> Self
where
I: Iterator<Item = &'a Self>,
{
iter.map(|&v| v).product()
}
}

impl Sum for $field_name {
fn sum<I>(mut iter: I) -> Self
where
I: Iterator<Item = Self>,
{
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<I>(iter: I) -> Self
where
I: Iterator<Item = &'a Self>,
{
iter.map(|&v| v).sum()
}
}
};
}

Expand Down

0 comments on commit b89a453

Please sign in to comment.