From 6d8aca43919154aab3944ebfb7d2f8e5e5378437 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Agust=C3=ADn=20Borgna?= <121866228+aborgna-q@users.noreply.github.com> Date: Wed, 7 Aug 2024 14:50:14 +0100 Subject: [PATCH] feat: `map_params` helpers on the parametric structs (#65) Some helpers to convert between parameter types without too much boilerplate. I wanted to add `ToOwned` instances or something similar, but most trait implementations clash with blanket impls, so these are just struct methods. --- src/circuit_json.rs | 58 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) diff --git a/src/circuit_json.rs b/src/circuit_json.rs index 566cf96..c4d34b2 100644 --- a/src/circuit_json.rs +++ b/src/circuit_json.rs @@ -252,4 +252,62 @@ impl

Operation

{ ..Operation::default() } } + + /// Applies a function over the parameters of the operation. + /// + /// Returns a new Operation with the same data, but with a new generic + /// type for the parameters. + pub fn map_params(self, f: impl FnMut(P) -> Q) -> Operation { + Operation { + op_type: self.op_type, + n_qb: self.n_qb, + data: self.data, + params: self + .params + .map(|params| params.into_iter().map(f).collect()), + op_box: self.op_box, + signature: self.signature, + conditional: self.conditional, + classical: self.classical, + wasm: self.wasm, + } + } +} + +impl

Command

{ + /// Applies a function over the parameters of the command. + /// + /// Returns a new Command with the same data, but with a new generic type + /// for the parameters. + pub fn map_params(self, f: impl FnMut(P) -> Q) -> Command { + Command { + op: self.op.map_params(f), + args: self.args, + opgroup: self.opgroup, + } + } +} + +impl

SerialCircuit

{ + /// Applies a function over the parameters of the circuit. + /// + /// Returns a new SerialCircuit with the same data, but with a new generic + /// type for the parameters. + pub fn map_params(self, mut f: impl FnMut(P) -> Q) -> SerialCircuit { + let phase = f(self.phase); + let commands = self + .commands + .into_iter() + .map(|c| c.map_params(&mut f)) + .collect(); + SerialCircuit { + name: self.name, + phase, + commands, + qubits: self.qubits, + bits: self.bits, + implicit_permutation: self.implicit_permutation, + number_of_ws: self.number_of_ws, + } + } }