Skip to the content.

Computation Expressions (CE) Reference

This document provides a complete reference for all computation expressions (CEs) available in FSharp.Azure.Quantum. Use this as a quick lookup when F# IntelliSense is not showing CE operations.

Overview

Computation expressions provide a declarative, F#-idiomatic way to construct quantum problems, circuits, and schedules. Each CE supports custom operations that are context-specific to its domain.

Quick Reference Table

CE Name Description Custom Operations
anomalyDetection Detect outliers and anomalies in data trainOnNormalData, sensitivity, contaminationRate, backend, shots, verbose, saveModelTo, note, progressReporter, cancellationToken
autoML Automated ML - finds best model automatically trainWith, tryBinaryClassification, tryMultiClass, tryAnomalyDetection, tryRegression, trySimilaritySearch, tryArchitectures, maxTrials, maxTimeMinutes, validationSplit, backend, verbose, saveModelTo, randomSeed, progressReporter, cancellationToken
binaryClassification Classify items into two categories trainWith, architecture, learningRate, maxEpochs, convergenceThreshold, backend, shots, verbose, saveModelTo, note, progressReporter, cancellationToken
circuit Build quantum circuits with gates and loops qubits, H, X, Y, Z, S, SDG, T, TDG, P, RX, RY, RZ, CNOT, CZ, CP, SWAP, CCX
coloredNode Define a node in graph coloring problem nodeId, conflictsWith, fixedColor, priority, avoidColors, property
constraintSolver<’T> Define constraint satisfaction problems (CSP) searchSpace, domain, satisfies, backend, maxIterations, shots
graphColoring Define graph coloring optimization problems node, nodes, colors, maxColors, objective, conflictPenalty
patternMatcher<’T> Define quantum pattern matching problems searchSpace, searchSpaceSize, matchPattern, findTop, backend, maxIterations, shots
periodFinder Define period finding (Shor’s algorithm) number, chosenBase, precision, maxAttempts, backend, shots
phaseEstimator Define quantum phase estimation (QPE) unitary, precision, targetQubits, eigenstate, backend, shots
predictiveModel Predict continuous values or categories trainWith, problemType, architecture, learningRate, maxEpochs, convergenceThreshold, backend, shots, verbose, saveModelTo, note, progressReporter, cancellationToken
quantumArithmetic Define quantum arithmetic operations operands, operandA, operandB, operation, modulus, qubits, exponent, backend, shots
quantumTreeSearch<’T> Define quantum tree search (game AI, decision trees) initialState, maxDepth, branchingFactor, evaluateWith, generateMovesWith, topPercentile, backend, shots, solutionThreshold, successThreshold, maxPaths, limitSearchSpace, maxIterations
resource<’T> Define scheduling resources resourceId, capacity, costPerUnit, availableWindow
scheduledTask<’T> Define tasks for scheduling taskId, duration, after, afterMultiple, requires, priority, deadline, earliestStart
schedulingProblem<’T> Define complete scheduling problems tasks, resources, objective, timeHorizon
similaritySearch Find similar items using quantum kernels indexItems, similarityMetric, threshold, backend, shots, verbose, saveIndexTo, note, progressReporter, cancellationToken

Detailed Documentation

1. circuit

Module: FSharp.Azure.Quantum.CircuitBuilder

Purpose: Declaratively construct quantum circuits with automatic validation

Example:

let bellState = circuit {
    qubits 2
    H 0
    CNOT (0, 1)
}

Custom Operations:

Features:


2. coloredNode

Module: FSharp.Azure.Quantum.GraphColoring

Purpose: Define individual nodes in a graph coloring problem

Example:

let node1 = coloredNode {
    nodeId "R1"
    conflictsWith ["R2"; "R3"]
    priority 1.0
}

Custom Operations:


3. constraintSolver<’T>

Module: FSharp.Azure.Quantum.QuantumConstraintSolver

Purpose: Solve constraint satisfaction problems (CSP) using Grover’s algorithm

Example:

let sudokuRow = constraintSolver<int> {
    searchSpace 9
    domain [1..9]
    satisfies (fun vars -> allDifferent vars)
    shots 1000
}

Custom Operations:

Features:


4. graphColoring

Module: FSharp.Azure.Quantum.GraphColoring

Purpose: Define complete graph coloring optimization problems

Example:

let problem = graphColoring {
    node (coloredNode { nodeId "R1"; conflictsWith ["R2"] })
    node (coloredNode { nodeId "R2"; conflictsWith ["R1"; "R3"] })
    colors ["EAX"; "EBX"; "ECX"]
    objective MinimizeColors
}

Custom Operations:


5. patternMatcher<’T>

Module: FSharp.Azure.Quantum.QuantumPatternMatcher

Purpose: Search for items matching complex patterns using Grover’s algorithm

Example:

let search = patternMatcher<Config> {
    searchSpace allConfigs
    matchPattern (fun cfg -> cfg.Performance > 0.8 && cfg.Cost < 100.0)
    findTop 5
    shots 500
}

Custom Operations:

Features:


6. periodFinder

Module: FSharp.Azure.Quantum.QuantumPeriodFinder

Purpose: Find periods in modular exponentiation (Shor’s factorization algorithm)

Example:

let problem = periodFinder {
    number 15
    precision 12
    maxAttempts 10
    shots 2048
}

Custom Operations:

Notes:


7. phaseEstimator

Module: FSharp.Azure.Quantum.QuantumPhaseEstimator

Purpose: Estimate eigenvalues of unitary operators using Quantum Phase Estimation (QPE)

Example:

let problem = phaseEstimator {
    unitary TGate
    precision 8
    targetQubits 1
    shots 1024
}

Custom Operations:

Notes:


8. quantumArithmetic

Module: FSharp.Azure.Quantum.QuantumArithmeticOps

Purpose: Perform quantum arithmetic operations (addition, multiplication, exponentiation)

Example:

let operation = quantumArithmetic {
    operands 42 17
    operation Add
    qubits 8
    shots 100
}

Custom Operations:

Notes:


9. quantumTreeSearch<’T>

Module: FSharp.Azure.Quantum.QuantumTreeSearch

Purpose: Search game trees and decision trees using Grover’s algorithm

Example:

let search = quantumTreeSearch<Board> {
    initialState gameBoard
    maxDepth 3
    branchingFactor 9
    evaluateWith (fun board -> evaluatePosition board)
    generateMovesWith (fun board -> getLegalMoves board)
    topPercentile 0.2
    shots 100
    maxIterations 5
}

Custom Operations:

Features:


10. resource<’T>

Module: FSharp.Azure.Quantum.TaskScheduling.Builders

Purpose: Define resources for task scheduling problems

Example:

let cpu = resource<string> {
    resourceId "CPU"
    capacity 4.0
    costPerUnit 10.0
    availableWindow (0.0, 100.0)
}

Custom Operations:


11. scheduledTask<’T>

Module: FSharp.Azure.Quantum.TaskScheduling.Builders

Purpose: Define tasks for scheduling optimization

Example:

let task1 = scheduledTask<string> {
    taskId "Task1"
    duration (Duration 5.0)
    requires "CPU" 2.0
    priority 1.0
    deadline 50.0
}

Custom Operations:


12. schedulingProblem<’T>

Module: FSharp.Azure.Quantum.TaskScheduling.Builders

Purpose: Define complete task scheduling optimization problems

Example:

let problem = schedulingProblem<string> {
    tasks [task1; task2; task3]
    resources [cpu; memory]
    objective MinimizeMakespan
    timeHorizon 100.0
}

Custom Operations:


13. anomalyDetection

Module: FSharp.Azure.Quantum.Business

Purpose: Detect outliers and anomalies in data using quantum one-class classification

Example:

let detector = anomalyDetection {
    trainOnNormalData normalTransactions  // Only normal examples needed
    sensitivity High                       // High sensitivity to detect subtle anomalies
    contaminationRate 0.1                  // Expect ~10% anomalies
    shots 1000
}

match detector with
| Ok model ->
    let result = AnomalyDetector.detect suspiciousTransaction model
    if result.IsAnomaly then
        printfn "⚠️ Anomaly detected! Score: %.2f" result.AnomalyScore
| Error e -> printfn "Training failed: %s" e

Custom Operations:

Use Cases:


14. autoML

Module: FSharp.Azure.Quantum.Business

Purpose: Automated machine learning - tries multiple approaches and returns the best model automatically

Example:

let result = autoML {
    trainWith features labels
    
    // Optional: Control search space
    tryBinaryClassification true
    tryMultiClass 4
    tryRegression true
    tryAnomalyDetection false
    
    // Architectures to test
    tryArchitectures [Quantum; Hybrid; Classical]
    
    // Search budget
    maxTrials 20
    maxTimeMinutes 10
    
    verbose true
}

match result with
| Ok model ->
    printfn "Best model: %s (%.2f%%)" model.BestModelType (model.Score * 100.0)
    let prediction = AutoML.predict newSample model
| Error e -> printfn "AutoML failed: %s" e

Custom Operations:

Use Cases:


15. binaryClassification

Module: FSharp.Azure.Quantum.Business

Purpose: Classify items into two categories (yes/no, fraud/legitimate, spam/ham)

Example:

let classifier = binaryClassification {
    trainWith trainFeatures trainLabels
    architecture Quantum
    learningRate 0.01
    maxEpochs 100
    shots 1000
}

match classifier with
| Ok model ->
    let prediction = BinaryClassifier.predict newTransaction model
    if prediction.IsFraud then
        blockTransaction()
| Error e -> printfn "Training failed: %s" e

Custom Operations:

Use Cases:


16. predictiveModel

Module: FSharp.Azure.Quantum.Business

Purpose: Predict continuous values (regression) or categories (multi-class classification)

Example:

// Regression: Predict revenue
let revenueModel = predictiveModel {
    trainWith customerFeatures revenueTargets
    problemType Regression
    learningRate 0.01
    maxEpochs 100
}

// Multi-class: Predict churn timing
let churnModel = predictiveModel {
    trainWith customerFeatures churnLabels  // 0=Stay, 1=Churn30, 2=Churn60, 3=Churn90
    problemType (MultiClass 4)
    architecture Quantum
    shots 1000
}

match churnModel with
| Ok model ->
    let prediction = PredictiveModel.predictCategory customer model
    match prediction.Category with
    | 0 -> printfn "Customer will stay"
    | 1 -> printfn "⚠️ Churn risk in 30 days!"
    | _ -> ()
| Error e -> printfn "Training failed: %s" e

Custom Operations:

Use Cases:


17. similaritySearch

Module: FSharp.Azure.Quantum.Business

Purpose: Find similar items using quantum kernels

Example:

let finder = similaritySearch<Product> {
    indexItems productCatalog  // Array of (item, features)
    similarityMetric CosineSimilarity
    threshold 0.7              // Minimum similarity threshold
    shots 1000
}

match finder with
| Ok index ->
    let similar = SimilarityFinder.findSimilar queryProduct 5 index
    printfn "Top 5 similar products:"
    similar |> Array.iter (fun (item, score) ->
        printfn "  %A: %.2f%% similar" item (score * 100.0)
    )
| Error e -> printfn "Indexing failed: %s" e

Custom Operations:

Use Cases:


Common Patterns

For Loops in CEs

Many CEs support for loops for adding multiple similar items:

// Circuit: Apply Hadamard to all qubits
let superposition = circuit {
    qubits 5
    for q in [0..4] do
        H q
}

// Constraint Solver: Add row constraints for Sudoku
let sudoku = constraintSolver<int> {
    searchSpace 81
    domain [1..9]
    for row in [0..8] do
        satisfies (checkRow row)
}

// Pattern Matcher: Combine multiple patterns with AND logic
let search = patternMatcher<Config> {
    searchSpace allConfigs
    for pattern in [perfPattern; costPattern; securityPattern] do
        matchPattern pattern  // All must match
}

Backend Configuration

Most quantum CEs support backend specification:

// Default: LocalBackend (simulation)
let problem1 = periodFinder {
    number 15
    precision 12
}

// Explicit backend
let ionqBackend = // Cloud backend requires Azure Quantum workspace
// createIonQBackend(...)
let problem2 = periodFinder {
    number 15
    precision 12
    backend ionqBackend
}

Auto-Scaling Parameters

Many CEs have auto-scaling parameters that adapt to backend type:

Parameter LocalBackend Cloud Backend
shots 100-1000 500-2048
maxIterations Auto-calculate Auto-calculate
solutionThreshold 1% 2%
successThreshold 10% 20%

Use None for auto-scaling (recommended), or specify explicit values for fine-tuning.

Progress Reporting and Cancellation

All ML builders (autoML, binaryClassification, predictiveModel, anomalyDetection, similaritySearch) support progress reporting and cancellation for long-running operations:

open System.Threading
open FSharp.Azure.Quantum.Core.Progress

// Example 1: Console progress reporter
let consoleReporter = createConsoleReporter(verbose = true)

let result1 = autoML {
    trainWith features labels
    maxTrials 20
    progressReporter consoleReporter  // Real-time console updates
}

// Example 2: Event-based progress with cancellation
let cts = new CancellationTokenSource()
let reporter = createEventReporter()
reporter.SetCancellationToken(cts.Token)

// Subscribe to progress events
reporter.ProgressChanged.Add(fun event ->
    match event with
    | TrialCompleted(id, score, elapsed) ->
        printfn $"Trial {id}: {score * 100.0:F1}%% in {elapsed:F1}s"
        if score > 0.95 then cts.Cancel()  // Early exit
    | _ -> ())

let result2 = autoML {
    trainWith features labels
    maxTrials 50
    progressReporter (reporter :> IProgressReporter)
    cancellationToken cts.Token
}

// Example 3: Timeout-based cancellation
let ctsTimeout = new CancellationTokenSource()
ctsTimeout.CancelAfter(TimeSpan.FromMinutes(5.0))

let result3 = binaryClassification {
    trainWith features labels
    maxEpochs 1000
    cancellationToken ctsTimeout.Token  // Auto-cancel after 5 minutes
}

Progress Event Types:

Built-in Reporters:

Use Cases:


IntelliSense Tips

If IntelliSense Doesn’t Show Operations

  1. Type the CE name explicitly:
    let problem = periodFinder {
        // Now press Ctrl+Space to see operations
    }
    
  2. Check you’re using the correct CE instance name (not the builder type):
    • periodFinder { } - Correct
    • PeriodFinderBuilder { } - Wrong
  3. For generic CEs, specify the type parameter:
    let search = patternMatcher<Config> {
        // Type parameter helps IntelliSense
    }
    
  4. Use this reference table when IntelliSense fails

See Also