7

I have the following operation in my .qs files:

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

How do I send an array of qubits to this in the driver file? The following did not work:

Qubit[] qubits = new Qubit[2];
myOp.Run(sim, qubits);

I got the following error:

Driver.cs(13,32): error CS1503: Argument 2: cannot convert from 'Microsoft.Quantum.Simulation.Core.Qubit[]' to 'Microsoft.Quantum.Simulation.Core.QArray<Microsoft.Quantum.Simulation.Core.Qubit>' [/home/tinkidinki/Quantum/Warmup_Contest/BellState/BellState.csproj]

The build failed. Please fix the build errors and run again.

Also, as an aside: Would such a question be more suitable for this site, or for stack overflow?

Sanchayan Dutta
  • 17,945
  • 8
  • 50
  • 112
Mahathi Vempati
  • 1,731
  • 10
  • 21

3 Answers3

5

In general, there are exactly two ways to allocate qubits in Q#: the using statement, and the borrowing statement. Both can only be used from within Q#, and can't be directly used from within C#. Thus, you'd likely want to make a new Q# operation to serve as the "entry point" from C#; this new operation would then be responsible for allocating qubits and passing them down.

For instance:

// MyOp.qs
operation EntryPoint() : () {
    body {
        using (register = Qubit[2]) {
            myOp(register);
        }
    }
}


// Driver.cs
EntryPoint.Run().Wait();
Chris Granade
  • 1,088
  • 7
  • 10
3

All qubits must be allocated by the Simulator, so you can't create an instance and pass it down to your Operation.

Why do you want to create the Qubits on the driver? If anything, you should create an "entry" method on Q# that just allocates your qubits and then call your operation, and call that from the Driver.

El capi
  • 406
  • 2
  • 3
0

Of course you can allocate qubits from C#! After all, Q# compiles to C#, so it's not possible for something to be doable only from Q#.

Here's a small script I wrote that will show you the C# generated from a Q# file.

The relevant bit is Allocate.Apply, which allocates the qubits, and you can read the rest of the produced code to see where Allocate comes from.

With that in mind, should you be allocating qubits from C#? Well, no, probably not. It's annoyingly difficult, and it's best to leave the quantum stuff for a quantum language.

Pavel
  • 241
  • 1
  • 8