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?

Wojciech Gac
  • 1,538
  • 1
  • 16
  • 30

1 Answers1

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.

Chris Granade
  • 913
  • 7
  • 21
  • 1
    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 :). – Wojciech Gac Sep 12 '19 at 09:39
  • 2
    I've created a feature request to add anonymous functions to the Q# compiler ([here](https://github.com/microsoft/qsharp-compiler/issues/181)). – Wojciech Gac Sep 24 '19 at 11:39