Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Emulation in Q# (Advent calendar blog post, supplemental material)
<Project Sdk="Microsoft.Quantum.Sdk/0.14.2011120240">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net5.0</TargetFramework>
<TargetPlatform>x64</TargetPlatform>
<LanguageVersion>9.0</LanguageVersion>
</PropertyGroup>
</Project>
using System;
using static System.Console;
using Microsoft.Quantum.Simulation.Core;
using Microsoft.Quantum.Simulation.Simulators;
namespace Advent
{
public partial class ChristmasMessage
{
public class Native : ChristmasMessage
{
private readonly IOperationFactory simulator;
public Native(IOperationFactory m) : base(m)
{
simulator = m;
}
private QVoid ChristmasMessageFunction(string message)
{
if (simulator is ToffoliSimulator)
{
WriteLine(message);
}
else
{
WriteLine($"Ho ho ho: {message}");
}
return QVoid.Instance;
}
public override Func<string, QVoid> __Body__ => ChristmasMessageFunction;
}
}
}
using System;
using Microsoft.Quantum.Simulation.Core;
namespace Advent
{
public partial class DaysUntilChristmas
{
public class Native : DaysUntilChristmas
{
public Native(IOperationFactory m) : base(m) { }
// can be adjusted (e.g., 1/7, 1/6, 1/19, ...)
private static int ChristmasMonth => 12;
private static int ChristmasDay => 25;
// C# function with matching signature
private long DaysUntilChristmasFunction(QVoid input)
{
var today = DateTime.Today;
var christmas = new DateTime(today.Year, ChristmasMonth, ChristmasDay);
// make sure the next Christmas is today or in the future
if (christmas < today)
christmas = christmas.AddYears(1);
// return difference in days
return (christmas - today).Days;
}
// Override __Body__ property to use C# function
public override Func<QVoid, long> __Body__ => DaysUntilChristmasFunction;
}
}
}
using Advent;
using Microsoft.Quantum.Intrinsic;
using Microsoft.Quantum.Simulation.Core;
using Microsoft.Quantum.Simulation.Simulators;
var sim = new QuantumSimulator();
sim.Register(typeof(Message), typeof(ChristmasMessage), typeof(ICallable));
await RunProgram.Run(sim);
namespace Advent {
open Microsoft.Quantum.Intrinsic;
function DaysUntilChristmas() : Int {
body intrinsic;
}
function ChristmasMessage(message : String) : Unit {
body intrinsic;
}
operation RunProgram() : Unit {
Message($"It's {DaysUntilChristmas()} days until christmas.");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment