In C# it is possible to have:

public void Fun (int n = 0){
    // ...

then the following method call examples will be compiled:

  • Fun()
  • Fun(10)

So I wonder whether or not such a useful facility is available in creating Q# operations with optional parameters?


Not at the moment. As of version 0.10, Q# doesn't support optional parameters, and it does not allow to define two operations with the same name that would only differ by the list of parameters (which would be a different way to do the same thing).


One way that I've found that works pretty well is to define a new UDT for options, and then provide a function that returns a reasonable set of defaults. For instance, in the case you gave, you might have something like:

newtype FunOptions = (
   N : Int,
   SomeOtherOption : Double[]

function DefaultFunOptions() : FunOptions {
    return (0, [0.0]);

function Fun(options : FunOptions) : Double {
    // do something using options::N and options::SomeOtherOption

This lets you call Fun by using the w/ to provide optional arguments as you see fit:

let w = Fun(DefaultFunOptions());
let x = Fun(DefaultFunOptions() w/ N <- 10);
let y = Fun(DefaultFunOptions() w/ SomeOtherOption <- [0.1, 0.2]);
let z = Fun(DefaultFunOptions() w/ N <- 42 w/ SomeOtherOption <- [0.1, 0.2]);

This is the approach taken, for instance, with the new quantum machine learning library currently under development. If you're interested, check out the pull request where the new TrainingOptions UDT was first introduced at https://github.com/microsoft/QuantumLibraries/pull/187.

  • 1
    $\begingroup$ I haven't run your solution on my machine yet, but I should thank you for this creative approach to the question! $\endgroup$ – Coder Jan 14 at 22:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.