Boolean comparison and compare-exchange circuits #
The comparator reads key coordinates in selector order, with coordinate zero most
significant. Its formula has 6 * k + 1 gates for k selected input bits. Compare-exchange
computes the comparison once, retains it and its negation, and selects whole records using
three gates per output bit. Ties preserve the input order, including payload bits outside the key.
For two nonempty records of width r, the circuit uses exactly 6 * k + 6 * r + 2 gates,
including constants and negations. Empty records use no gates. Key positions may be arbitrary;
the usual prefix key is Fin.castLE h for h : k ≤ r.
Main definitions #
Cslib.Circuits.Formula.lexLt: compare two selected input sequences lexicographically.Cslib.Circuits.Boolean.compareSwapCircuit: order two records by selected key coordinates.Cslib.Circuits.Boolean.compareSwapCircuit.record: expose a shared swap flag and its complement.Cslib.Circuits.Boolean.compareSwapCircuit.switch: exchange payloads using saved controls.
Main results #
Cslib.Circuits.Formula.eval_lexLt_iff: agreement with Mathlib's lexicographic order.Cslib.Circuits.Boolean.eval_compareSwapCircuit: swap whole records exactly when out of order.Cslib.Circuits.Boolean.size_compareSwapCircuit: exact total gate count.Cslib.Circuits.Boolean.compareSwapCircuit_keys_ordered: the output keys are in ascending order.Cslib.Circuits.Boolean.compareSwapCircuit.cost_record_eq_exchange: exposing controls adds no gates toexchange, which computes its flag even at zero payload width.
References #
- Adapts the comparator endpoint of MassProduction/Sorting.lean in S. Schlesinger, Boolean circuit mass production formalization, using a linear-size comparison and sharing its result between outputs.
Compare two selected input sequences, with coordinate zero most significant.
Instances For
Compare two records by key, preserving their order when the keys agree. The comparison
and its negation are shared across all output bits. Empty records use the identity wiring.
Instances For
Retain a flag and compute its negation once.
Instances For
The control bits are supplied together: invalid pairs are not asserted to be swaps.
Recording returns both existing control wires without duplicating their computation.
Applying the same saved controls twice restores arbitrary payloads.
Compare-exchange swaps whole records precisely when the right key precedes the left key.
The selected keys of the two output records are in ascending order.