Learn by Doing

Examples

Complete, runnable examples — from quantum Hello World to full molecular chemistry workflows. Copy any example into the code editor and click RUN.

Bell State — Hello World of Quantum

The Bell state is the simplest demonstration of quantum entanglement. After running this circuit, you will only ever measure "00" or "11" — never "01" or "10".

-- Bell State: quantum entanglement demonstration
-- Expected output: ~50% "00", ~50% "11", never "01" or "10"

let q = qubits(2)

-- Step 1: Put qubit 0 into superposition
H(q[0])                              -- |0⟩ → (|0⟩+|1⟩)/√2

-- Step 2: Entangle qubit 1 with qubit 0
CNOT(q[0], q[1])                     -- creates |00⟩+|11⟩/√2

-- Measure 1000 times and collect statistics
let r = measure_all(q, shots=1000)
print("Histogram:")
print(r.histogram)

-- Calculate fidelity to ideal Bell state
let q2 = qubits(2); H(q2[0]); CNOT(q2[0],q2[1])
let sv  = statevector(q2)
print(f"Statevector: {sv}")
Expected Output
Histogram: {"00": 503, "11": 497}
Statevector: [{state:"00",re:0.7071,im:0,prob:0.5},{state:"11",re:0.7071,im:0,prob:0.5}]

Grover Search — Quantum Speedup

Finds item 7 in an unsorted 16-item database. Classical search: average 8 queries. Grover's algorithm: ~3 queries. Quadratic speedup.

-- Grover search: find item 7 in 16-item database (nQ=4, 2^4=16)
let n_qubits = 4
let target   = 7   -- binary: 0111
let shots    = 2000

print(f"Searching for {target} in {2**n_qubits} items...")

let result = grover(n_qubits, [target], shots)

-- Target should appear ~96% of the time
let found = dict_get(result.histogram, "0111", 0)
print(f"Target '0111' found: {found}/{shots} ({round_to(found/shots*100,1)}%)")

-- Show top 5 results
let sorted = sort_by(items(result.histogram), fn(kv): return -kv[1])
print("Top results:")
for kv in sorted[:5]:
    print(f"  |{kv[0]}⟩ = {kv[1]} ({round_to(kv[1]/shots*100,1)}%)")

VQE — Hydrogen Molecule Energy

Calculates the ground state energy of H₂ using the Variational Quantum Eigensolver. The same calculation run on IBM Quantum hardware.

-- VQE: Ground state energy of H2 at equilibrium geometry
-- Exact FCI answer: -1.137270 Hartree
-- Chemical accuracy: error < 0.001 Hartree (1 mHartree)

molecule H2 {
    atoms:        [H, H],
    bond_length:  0.74,      -- Angstroms
    basis_set:    "STO-3G",
    charge:       0,
    multiplicity: 1
}

print("Running VQE for H2 molecule...")

let result = vqe(
    H2,
    ansatz="UCCSD",       -- Unitary Coupled Cluster Singles & Doubles
    optimizer="COBYLA",   -- Constraint-based optimiser
    max_iter=300,
    shots=2000
)

let exact = -1.137270
let error = abs(result.energy - exact) * 1000  -- in mHartree

print(f"VQE energy:   {result.energy:.6f} Hartree")
print(f"Exact FCI:    {exact:.6f} Hartree")
print(f"Error:        {error:.3f} mHartree")
print(f"Chemical acc: {error < 1.0}")
print(f"Converged in: {result.n_iter} iterations")

Quantum Teleportation

-- Quantum teleportation: transfer state from Alice to Bob
-- Uses 2 classical bits + 1 pre-shared Bell pair

def teleport(angle):
    let q = qubits(3)
    -- q[0]=Alice's secret, q[1]=Alice's Bell, q[2]=Bob's Bell
    
    Ry(q[0], angle)          -- Prepare secret state
    H(q[1]); CNOT(q[1], q[2])  -- Create Bell pair
    
    CNOT(q[0], q[1]); H(q[0])   -- Alice's Bell measurement
    let m0 = measure(q[0])
    let m1 = measure(q[1])
    
    if m1 == 1: X(q[2])   -- Bob's corrections
    if m0 == 1: Z(q[2])
    
    let expected = round_to(cos(angle/2)**2, 4)
    print(f"angle={round_to(angle,3)}: P(|0⟩) expected={expected}")

print("=== Quantum Teleportation ===")
for a in [0.0, PI/4, PI/2, PI]:
    teleport(a)

Quantum Random Number Generator

-- True quantum randomness — NOT pseudo-random
def qrand(lo, hi):
    let range_size = hi - lo + 1
    let n = n_qubits_for(range_size)
    let q = qubits(n); H_all(q)
    let bits = [measure(q[i]) for i in range(n)]
    let v = bits_to_int(join([str(b) for b in bits], ""))
    if v >= range_size: return qrand(lo, hi)  -- rejection sampling
    return lo + v

print("10 quantum random integers (1-100):")
print([qrand(1, 100) for _ in range(10)])

print("Coin flip distribution (1000 flips):")
let flips = [qrand(0,1) for _ in range(1000)]
let heads = len(filter(fn(x): return x==0, flips))
print(f"Heads: {heads}  Tails: {1000-heads}")

Shor Factoring

-- Shor's algorithm: factor integers using quantum period finding
for N in [15, 21, 33, 35]:
    let r = shor_factor(N=N, a=2, n_count_qubits=8, shots=2000)
    print(f"{N} = {r.factors[0]} × {r.factors[1]}")
-- 15 = 3 × 5
-- 21 = 3 × 7
-- 33 = 3 × 11
-- 35 = 5 × 7

QAOA Portfolio Optimisation

-- QAOA: select best 2 assets from 4 to maximise Sharpe ratio
let assets  = ["RELIANCE", "TCS", "HDFC", "INFOSYS"]
let returns = [0.24, 0.31, 0.19, 0.28]
let vols    = [0.22, 0.25, 0.18, 0.26]

let edges = [[0,1],[1,2],[2,3],[3,0],[0,2],[1,3]]
let r = qaoa(n_nodes=4, edges=edges, p_layers=3, shots=2000)

let sorted = sort_by(items(r.histogram), fn(kv): return -kv[1])
print("Top portfolios:")
for kv in sorted[:3]:
    let sel = [assets[i] for i in range(4) if kv[0][i]=="1"]
    print(f"  {sel}: {kv[1]} times")

Statistical Analysis

let data = [2.3,4.1,3.8,5.2,4.7,3.9,6.1,4.5,5.0,4.3]

print(f"N:        {len(data)}")
print(f"Mean:     {mean(data):.4f}")
print(f"Std Dev:  {stdev(data):.4f}")
print(f"Median:   {median(data):.4f}")
print(f"IQR:      {iqr(data):.4f}")
print(f"95th pct: {percentile(data,95):.4f}")
print(f"Z-scores: {[round_to(z,3) for z in zscore(data)]}")
let t = t_test_one_sample(data, 4.0)
print(f"T-test vs 4.0: t={t.t_stat:.4f}")

Visual Canvas Example (UI Blocks)

The same Bell state program, built visually in the canvas. Steps:

  1. Search "Quantum Register" in palette → drag to canvas → set n_qubits=2, name=q
  2. Search "Hadamard" → drag → set qubit=0 → connect Register output → Hadamard input
  3. Search "CNOT" → drag → set control=0, target=1 → connect Hadamard output → CNOT input
  4. Search "Measure All" → drag → set shots=1000 → connect CNOT output → Measure input
  5. Search "Print" → drag → connect Measure output → Print input
  6. Click ▶ RUN → see {"00":503,"11":497} in the output panel

Rust Code Example

Direct usage of the Rust engine (for advanced users building custom simulations):

use quantum_engine::QReg;
use std::f64::consts::PI;

fn main() {
    // Bell state
    let mut q = QReg::new("q", 2);
    q.H(0);
    q.CNOT(0, 1);
    let hist = q.measure_all(1000);
    println!("{:?}", hist);
    // {"00": 503, "11": 497}

    // Grover search
    let results = QAlg::grover(4, &[7], 2000);
    let found = results.get("0111").copied().unwrap_or(0);
    println!("Target found: {}/2000", found);
}

Python Pre-computation Example

import subprocess, json
from pathlib import Path

# Run pre-computation (generates all 8 data files)
result = subprocess.run(["python3", "precompute.py"], capture_output=True)
print(result.stdout.decode())

# Load generated molecule Hamiltonians
with open("precomputed/molecule_hamiltonians.json") as f:
    data = json.load(f)

h2 = data["hamiltonians"]["H2"]
print(f"H2 FCI energy: {h2['fci_energy_hartree']} Ha")
print(f"Pauli terms: {len(h2['terms'])}")
for term in h2["terms"][:3]:
    print(f"  {term['coefficient']:+.6f} × {term['pauli']}")