Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use lambda in Q# to operate on qubits?

I have a use case in Q# where I have qubit register qs and need to apply the CNOT gate on every qubit except the first one, using the first one as control. Using a for loop I can do it as follows:

for (i in 1..Length(qs)-1) {
    CNOT(qs[0], qs[i]);
}

Now, I wanted to give it a more functional flavor and tried instead to do something like:

ApplyToEach(q => CNOT(qs[0], q), qs[1..Length(qs)-1]);

The Q# compiler does not accept an expression like this, informing me that it encountered an unexpected code fragment. That's not too informative for my taste. Some documents claim that Q# supports anonymous functions a'la C#, hence the attempt above. Can anybody point me to a correct usage of lambdas in Q# or dispel my false belief?

like image 930
Wojciech Gac Avatar asked Sep 11 '19 11:09

Wojciech Gac


1 Answers

At the moment, Q# doesn't support lambda functions and operations (though that would be a great feature request to file at https://github.com/microsoft/qsharp-compiler/issues/new/choose). That said, you can get a lot of the functional flavor that you get from lambdas by using partial application. In your example, for instance, I could also write that for loop as:

 ApplyToEach(CNOT(Head(qs), _), Rest(qs));

Here, since CNOT has type (Qubit, Qubit) => Unit is Adj + Ctl, filling in one of the two inputs as CNOT(Head(qs), _) results in an operation of type Qubit => Unit is Adj + Ctl.

Partial application is a very powerful feature, and is used all throughout the Q# standard libraries to provide a functional way to build up quantum programs. If you're interested in learning more, I recommend checking out the docs at https://docs.microsoft.com/quantum/language/expressions#callable-invocation-expressions.

like image 166
Chris Granade Avatar answered Sep 27 '22 18:09

Chris Granade