liveBook · Manning

Q# function

As explained in Quantum Programming in Depth

A Q# function is a deterministic classical callable in Q# that returns a value without producing side effects.

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

How Quantum Programming in Depth covers it

How deep it goes
Explains side-effect restrictions, compiler implications, and two concrete implementations, but does not survey general Q# function syntax.
Examples
Uses GetWStateAmps for amplitudes and GetRowPairInd for row-pair indexing in an N queens marking oracle.
What it assumes
Assumes Q# operations, mutable variables, and adjoints, while establishing why side-effect-free functions are needed for automatic adjoint generation.
What you can do after
Build it from scratch as a deterministic helper that supplies reusable classical values to Q# operations requiring automatic adjoints.
How it connects
Connects functions to Q# operations, adjoints, state preparation, Grover's algorithm, and marking oracles.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Quantum Programming in Depth. The section links point to the parts of the book it draws on.