arraysvariable-length-arrayq#qubit

Find the length of the array that was passed to you in Q#


I have an operation as follows to which the driver needs to send an array of qubits.

operation myOp(qubits: Qubit[]) : () {
     // uses elements from the qubit array        
 }

How do I find the length of this array from within the code?


Solution

  • let n = Length(qubits)
    

    This will store the length in the variable n. Also n is a constant which can't be changed. If for any reason you want a mutable variable n then

    mutable n = Length(qubits) 
    

    which can be changed. Now you can iterate through the array using a for loop (works for both constant or mutable n)

    for(index in 0 .. (n-1)) {
    //process the element qubits[index]
    }