Skip to content
You are reading gnark development version documentation and some displayed features may not be available in the stable release. You can switch to stable version using the version box at screen bottom.

Updated on April 21, 2021

Conditionals and loops

Loops

Use standard for loops inside a circuit definition.

Note

The for loop impact on the constraint system is identical to unrolling its content.

check that X*X*X*X*X... == Y

func (circuit *Circuit) Define(curveID ecc.ID, cs *frontend.ConstraintSystem) error {
    for i := 0; i < n; i++ {
        circuit.X = cs.Mul(circuit.X, circuit.X)
    }
    cs.AssertIsEqual(circuit.X, circuit.Y)
    return nil
}

Conditionals statements

In an imperative programming language, conditionals would use if and else statements. However, this doesn’t translate well in a declarative API to define the circuit, because the output of the frontend.Compile method is an arithmetic representation that must encode the various branches.

gnark offers cs.Select(...) API, which is similar to Prolog-like languages.

// Select if b is true, yields i1 else yields i2
func (cs *ConstraintSystem) Select(b Variable, i1, i2 interface{}) Variable {

Note

Work is ongoing to provide a if like statement. Github issue.

Questions or feedback? You can discuss issues and obtain free support on gnark discussions channel.
For paid professional support by Consensys, contact us at [email protected]