A Q# function is a deterministic classical callable that returns a value without side effects. Separating classical calculations from quantum operations lets the Q# compiler generate operation adjoints safely: repeated calls with the same arguments produce the same result. section 8.2.3
Use a Q# function when an operation needs reusable classical data or indexing logic:
- Compute W-state amplitudes before state preparation, keeping mutable array construction outside the adjointable operation. section 8.2.3
- Calculate row-pair indices for a marking oracle without changing quantum state. section 8.2.3
Adjoint-safe amplitude calculation
function GetWStateAmps(n : Int) : Double[] { mutable amps = [0.0, size = 2 ^ n]; for i in 0 .. n - 1 { set amps w/= (1 << i) <- Sqrt(1.0 / IntAsDouble(n)); } return amps; } The adjointable PrepareMean_Bits operation calls this function and uses the returned amplitudes to prepare each W state. section 8.2.3
Listing 8.5 Q#: Solving N queens puzzle—state preparation
import Std.Arrays.Chunks;
import Std.Convert.IntAsDouble;
import Std.Math.Sqrt;
import Microsoft.Quantum.Unstable.StatePreparation.PreparePureStateD;
function GetWStateAmps(n : Int) : Double[] { #1
mutable amps = [0.0, size = 2 ^ n];
for i in 0 .. n - 1 {
set amps w/= (1 {\fontsize{9}{0}\selectfont<\hskip-1pt<\hskip-1pt<} i) <- Sqrt(1.0 / IntAsDouble(n));
}
return amps;
}
operation PrepareMean_Bits( #2
n : Int,
qs : Qubit[]
) : Unit is Adj {
let wstateAmps = GetWStateAmps(n);
for row in Chunks(n, qs) { #3
PreparePureStateD(wstateAmps, row);
}
}
Inspect the complete Q# state-preparation listing, including imports, amplitude construction, and the adjointable operation that consumes the function result. section 8.2.3
