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

427 Views Asked by At

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?

2

There are 2 best solutions below

0
Indrajit Banerjee On BEST ANSWER
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]
}
0
Mariia Mykhailova On

Length(qubits)

It is mentioned in the documentation on numeric expressions: https://learn.microsoft.com/en-us/quantum/quantum-qr-expressions#numeric-expressions