2
$\begingroup$

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?

$\endgroup$
1

2 Answers 2

2
$\begingroup$

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).

$\endgroup$
1
$\begingroup$

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.

$\endgroup$
1
  • 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, 2020 at 22:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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