Skip to content

Commit

Permalink
Implement Sum and Product for Expression (privacy-scaling-exploration…
Browse files Browse the repository at this point in the history
…s#209)

* Make it Eq to make it easier for tests

* Implement Sum and Product for Expression

* Make it readable
  • Loading branch information
pnyda authored and Velaciela committed Oct 13, 2023
1 parent f47c31d commit 75be70d
Showing 1 changed file with 59 additions and 0 deletions.
59 changes: 59 additions & 0 deletions halo2_proofs/src/plonk/circuit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use ff::Field;
use sealed::SealedPhase;
use std::collections::BTreeMap;
use std::fmt::Debug;
use std::iter::{Product, Sum};
use std::ops::Range;
use std::{
convert::TryFrom,
Expand Down Expand Up @@ -1375,6 +1376,20 @@ impl<F: Field> Mul<F> for Expression<F> {
}
}

impl<F: Field> Sum<Self> for Expression<F> {
fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
iter.reduce(|acc, x| acc + x)
.unwrap_or(Expression::Constant(F::ZERO))
}
}

impl<F: Field> Product<Self> for Expression<F> {
fn product<I: Iterator<Item = Self>>(iter: I) -> Self {
iter.reduce(|acc, x| acc * x)
.unwrap_or(Expression::Constant(F::ONE))
}
}

/// Represents an index into a vector where each entry corresponds to a distinct
/// point that polynomials are queried at.
#[derive(Copy, Clone, Debug)]
Expand Down Expand Up @@ -2473,3 +2488,47 @@ impl<'a, F: Field> VirtualCells<'a, F> {
Expression::Challenge(challenge)
}
}

#[cfg(test)]
mod tests {
use super::Expression;
use halo2curves::bn256::Fr;

#[test]
fn iter_sum() {
let exprs: Vec<Expression<Fr>> = vec![
Expression::Constant(1.into()),
Expression::Constant(2.into()),
Expression::Constant(3.into()),
];
let happened: Expression<Fr> = exprs.into_iter().sum();
let expected: Expression<Fr> = Expression::Sum(
Box::new(Expression::Sum(
Box::new(Expression::Constant(1.into())),
Box::new(Expression::Constant(2.into())),
)),
Box::new(Expression::Constant(3.into())),
);

assert_eq!(happened, expected);
}

#[test]
fn iter_product() {
let exprs: Vec<Expression<Fr>> = vec![
Expression::Constant(1.into()),
Expression::Constant(2.into()),
Expression::Constant(3.into()),
];
let happened: Expression<Fr> = exprs.into_iter().product();
let expected: Expression<Fr> = Expression::Product(
Box::new(Expression::Product(
Box::new(Expression::Constant(1.into())),
Box::new(Expression::Constant(2.into())),
)),
Box::new(Expression::Constant(3.into())),
);

assert_eq!(happened, expected);
}
}

0 comments on commit 75be70d

Please sign in to comment.