A Q# operation is a callable construct that accepts parameters, acts on qubits, and returns a value. Quantum gates are represented as operations; gates that change qubit states return Unit. Built-in gates live in the Std.Intrinsic namespace, while custom gates can be defined and called similarly. section 2.3.4
Operations can encode state preparation directly from equations. For example, PrepOneQubit computes theta = 2.0 * ArcTan2(beta, alpha) and applies Ry(theta, q) to prepare a qubit from coefficients alpha and beta.
Quantum-gate operations support specialized invocation forms:
- Declare adjoint and controlled capabilities with is Adj + Ctl; the compiler can generate these specializations for suitable Unit-returning operations acting on qubits. section 2.3.4
- Use Adjoint and Controlled to obtain the corresponding operation variants, or use ApplyControlledOnInt for integer-controlled application. section 2.3.4
- Fix selected arguments with partial application; supplied arguments become fixed, while underscores remain parameters of the resulting operation. section 3.2.2
Preparing and inspecting a two-qubit state
PrepTwoQubits derives intermediate coefficients, prepares one qubit, and applies controlled instances of PrepOneQubit. RunPrepTwoQubitsDemo supplies [0.36, 0.48, 0.64, -0.48], then DumpMachine reports amplitudes and probabilities for |00>, |01>, |10>, and |11>.
Listing 3.5 Python code to get the matrix of a Q# operation
import qsharp
from qsharp.utils import dump_operation
coef = [[0.6, -0.8], [0.8, 0.6]]
qsharp.init(project_root='.')
print(dump_operation(f"UnitaryImplementation.ApplyOneQubit(_, \{coef\})", 1))
Inspect a Q# operation's matrix from Python with qsharp.utils.dump_operation after partially applying its coefficient argument. section 3.2.2
