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

1

6

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?

Pointdevice answered 11/9, 2019 at 11:41 Comment(0)
T
4

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://learn.microsoft.com/quantum/language/expressions#callable-invocation-expressions.

Telencephalon answered 11/9, 2019 at 15:55 Comment(2)
Chris Granade, thanks a lot for your answer. Indeed, partial application fits most use cases I've encountered so far. Thanks for reminding me of its existence :).Pointdevice
I've created a feature request to add anonymous functions to the Q# compiler (here).Pointdevice

© 2022 - 2024 — McMap. All rights reserved.